It's a complex PR/topic and don't understand all the code / hard to review so focused on looking at tests. Ran the system tests for most premium features and they seem to pass. Also checked custom reports generates similar queries that still work (some SQLs changed but are still valid). As nothing seems to break I reckon it's good to merge (in 3.8).
I'll also go through the code and try to make it more expressive.
Tried to make the code a bit clearer.
fyi we will need to test this with all premium features again, and especially custom reports to make sure the generated queries are still correct.