gortiz opened a new pull request, #20293:
URL: https://github.com/apache/pinot/pull/20293

   ## Summary
   
   **What.** The multi-stage engine (MSE) can now run `GROUP BY 
ARRAY_TO_MV(col)` in every stage of a query: above a join, in a subquery, with 
group trimming, and directly on a table scan. Before this change, the query 
worked only when the whole aggregate ran directly on a table scan.
   
   **Why.** In the single-stage engine (SSE), `GROUP BY mvCol` groups each row 
by every element of the multi-value (MV) column. The MSE has no equivalent 
above the leaf stage. `ARRAY_TO_MV` is only a type trick that the leaf stage 
removes. In an intermediate stage, the planner rejects it.
   
   **How.** This PR adds a new plan node, the *MV aggregate*, and a runtime 
operator for it. The broker uses it only for a query that fails without it:
   
   > The broker first plans the query exactly as master does. Only if that plan 
groups by `ARRAY_TO_MV(expr)` and fails the `ARRAY_TO_MV` validation does the 
broker plan the query again, with the MV aggregate.
   
   So a query that works on master keeps the plan, the types and the results 
that it has on master, and servers that predate this PR can run it during a 
rolling upgrade. Only a query that fails on master changes. There is no 
configuration.
   
   This PR replaces 
[apache/pinot#20061](https://github.com/apache/pinot/pull/20061). It keeps the 
MV aggregate from that PR and drops every change to queries that work on 
master. The reviews of #20061 found that each of those changes broke a query 
that works today. The dropped changes are listed in [Out of 
scope](#out-of-scope).
   
   ## Background
   
   ### SSE semantics
   
   The MV aggregate uses the SSE rules for `GROUP BY` on an MV column:
   
   - A row goes into the group of each of its elements.
   - If an element occurs two times in one row, the row counts two times in 
that group.
   - An empty array goes into no group. A stored MV value is never empty, but a 
function such as `filterMv` can return an empty array.
   - When null handling is on, a null MV value goes into one null group.
   - In an intermediate stage, a null MV value from an outer join goes into the 
null group, also when null handling is off. `MvKeyExpander` maps a null value 
to one null element.
   - Two or more MV keys give, for each row, the cartesian product of their 
elements.
   
   A few rows with large arrays can create a very large number of combinations. 
The operator creates at most 1M group ids (4 MB) at a time. When a block needs 
more, it splits the block into batches, and it splits a row with more 
combinations than one batch across batches. It checks for query termination 
after each batch, so a cancel or a timeout stops a large product. A row with 
more combinations than an `int` holds fails the query with 
`SERVER_RESOURCE_LIMIT_EXCEEDED`. A row with an empty MV key creates no group, 
whatever the size of the other keys.
   
   `CROSS JOIN UNNEST(col)` gives the same groups, but it drops a null MV value.
   
   ### Why the exchange must carry scalars
   
   The MV aggregate always runs as LEAF + exchange + FINAL, and the LEAF side 
expands the MV keys before the exchange. The exchange must partition by 
element: with whole arrays, rows that share an element but have different 
arrays go to different workers, and the FINAL side returns the same group more 
than once. Also, the MSE has no array equality: `Key` compares arrays by 
reference, and the exchange hashes `toString()`.
   
   ### Why a new plan node
   
   `MvAggregateNode` does not extend `AggregateNode`. A `PlanNodeVisitor` that 
handles only `visitAggregate` must fail at compile time. It must not treat the 
MV aggregate as a plain aggregate. The proto gets a new `MvAggregateNode` 
message (field 19 of `PlanNode.node`). Only the second plan uses it.
   
   In the runtime, `MvAggregateOperator` extends `AggregateOperator`. The only 
difference is the group-by executor, which expands the MV keys. The operator 
reports its stats as `AGGREGATE`, so a server that predates this PR can read 
them. There is no new operator type id.
   
   ## The fallback
   
   ```
   compile:  SQL -> copy (only if the query calls ARRAY_TO_MV)
                 -> validate -> convert -> optimize                        -> 
plan A (the plan of master)
             plan A groups by ARRAY_TO_MV(expr)?
                 no  -> plan A
                 yes -> fragments -> ArrayToMvValidationVisitor (no routing)
                          passes -> plan A
                          fails  -> new PlannerContext (MV aggregate on, 
nullable ARRAY_TO_MV)
                                    -> validate the copy -> convert -> optimize 
-> plan B
   CompiledQuery: one plan, never replaced
   ```
   
   - `QueryEnvironment.compile` makes the decision, so `CompiledQuery` has only 
the plan that runs. Its table names, which the broker reads for authorization 
and row-level security, are the tables of that plan. `CompiledQuery`, 
`PlannerContext` and `PinotDispatchPlanner` do not change after construction.
   - The second plan starts from the SQL. The Calcite validator changes the 
tree that it validates, so `compile` keeps a copy of the parsed query before 
the first validation (`SqlNodeCopier`), only when the query calls 
`ARRAY_TO_MV`. The broker rewrites of the query (the IdSet rewrite, the 
row-level security options) change the parsed query before `compile`, so the 
copy has them. A new parse of the SQL text would lose them.
   - The check runs `ArrayToMvValidationVisitor.validateFragments` on the 
fragments of plan A. It needs no routing or worker assignment: a fragment is a 
leaf fragment when it scans a table. If the second plan fails, its error is 
thrown with the error of the first plan as a suppressed exception.
   - The type of `ARRAY_TO_MV` is different in the two plans:
     - In plan A, `ARRAY_TO_MV` has the type that it has on master: the 
component type of the array, which is NOT NULL also for a nullable array. 
Calcite removes `COALESCE` and folds `IS NULL` around it, as on master.
     - In plan B, `PlannerContext` gets a validator whose operator table has 
`PinotOperatorTable.NULLABLE_ARRAY_TO_MV`. Its type is nullable when the array 
or the component type is nullable, and the MV aggregate gives its MV keys this 
type. A null array forms the null group at runtime, so Calcite must not fold 
`IS NULL` on the key. `CASE WHEN ARRAY_TO_MV(col) IS NULL ...` above the 
aggregate gives the correct result.
   - Only plan B uses the new rule behavior 
(`PinotRuleUtils.isMvAggregateEnabled`):
     - `PinotAggregateExchangeNodeInsertRule` plans the MV aggregate.
     - `PinotProjectJoinTransposeRule` does not push an expression with 
`ARRAY_TO_MV` below a join, so the group expression stays in the `Project` 
under the aggregate.
     - `PinotFilterAggregateTransposeRule` keeps a filter that reads an MV key 
above the aggregate. Below the aggregate, that filter becomes a multi-value 
predicate in the leaf stage, which keeps the other elements of a matching row. 
In plan A, the rule is the stock `FilterAggregateTransposeRule`.
   - The physical optimizer (`usePhysicalOptimizer=true`) does not use the MV 
aggregate, so it never falls back.
   - Cost: a copy of the parsed query for a query that calls `ARRAY_TO_MV`. For 
a query that groups by `ARRAY_TO_MV`, one more `makePlan` to check plan A. For 
a query that falls back, one more validation, conversion and optimizer pass.
   
   ## Plan shapes
   
   `SELECT ARRAY_TO_MV(e.mcol), COUNT(*) FROM e JOIN d ON e.k = d.k GROUP BY 
ARRAY_TO_MV(e.mcol)` fails on master. With this PR:
   
   ```
   Aggregate FINAL              <- plain aggregate over scalar keys
     Exchange hash[0]           <- scalar elements, never arrays
       MvAggregate LEAF         <- MvAggregateOperator, mvKeys=[0]
         Project e.mcol         <- ARRAY_TO_MV removed, the key is the array
           Join e.k = d.k
             Exchange hash[0]
               TableScan e
             Exchange hash[0]
               TableScan d
   ```
   
   When plan B has the MV aggregate directly on a table scan (for example with 
the hint `is_skip_leaf_stage_group_by`, which makes plan A fail), 
`ServerPlanRequestVisitor` sends it to the SSE as `GROUP BY mcol`, and the SSE 
groups by each element.
   
   Notes on the rule:
   
   - The hints `is_skip_leaf_stage_group_by` and 
`is_partitioned_by_group_by_keys` are ignored for an MV aggregate. A skip-leaf 
plan hashes whole arrays. A partitioned plan assumes a partitioning by element 
that no partition function gives.
   - The hint `is_leaf_return_final_result` is honored. Group trimming applies.
   - If an MV key column is also an aggregate argument, as in 
`SUM(ARRAY_TO_MV(c)) ... GROUP BY ARRAY_TO_MV(c)`, or in the `FILTER (WHERE 
...)` clause of an aggregate call, the rule keeps the plain aggregate.
   - An aggregate with `GROUPING SETS`, `ROLLUP` or `CUBE` is never an MV 
aggregate.
   
   ## Behavior before and after this PR
   
   In the table, `A` is `ARRAY_TO_MV(c)`, and "on the scan" means directly on a 
table scan.
   
   | # | Query | Master | This PR |
   |---|---|---|---|
   | 1 | Any query that plans on master | Its plan | Same plan, same types, 
same results |
   | 2 | `GROUP BY A` above a join, in a subquery, or with 
`is_skip_leaf_stage_group_by` | Error | MV aggregate in the intermediate stage |
   | 3 | `GROUP BY A` above a lookup join | Error when the query runs | MV 
aggregate in the leaf stage, above the leaf boundary |
   | 4 | Row 2 or 3 with `HAVING A = 'x'` or an outer filter on the key | Error 
| Correct: the filter stays above the MV aggregate |
   | 5 | Row 2 or 3 with `CASE WHEN A IS NULL THEN 'none' ELSE A END` above a 
`LEFT JOIN` | Error | Correct: the group `none` |
   | 6 | Row 2 or 3 with `COALESCE(A, 'none')` as the key | Error | Error: 
`COALESCE` nests `A` in another expression |
   | 7 | `A` in the SELECT list, in a JOIN condition, in a window function, or 
nested in a key above a join | Error | Error, with a new message |
   | 8 | `A` above a lookup join or an `UNNEST` in a leaf fragment, other than 
as a group key | Error when the query runs | Error at planning time |
   
   Rows 7 and 8 are the only changes to queries that do not fail on master at 
planning time. Row 8 queries fail on master when they run: the nodes above the 
leaf boundary run as multi-stage operators, which have no implementation of 
`ARRAY_TO_MV`. `ArrayToMvValidationVisitor` now treats those nodes as 
intermediate stage, which the fallback needs to plan row 3.
   
   The error messages of `ArrayToMvValidationVisitor` are new. Each one ends 
with `ArrayToMvValidationVisitor.SUPPORTED_USES`:
   
   ```
   ARRAY_TO_MV is supported only: (1) as a complete GROUP BY key, GROUP BY 
ARRAY_TO_MV(expr), where expr is a multi-value column or an array expression; 
(2) in WHERE predicates that run in the leaf stage (directly on a table scan). 
It is not supported nested inside another expression (for example CASE WHEN 
ARRAY_TO_MV(col) IS NOT NULL ...), in the SELECT list, in aggregate arguments, 
in filters above a join or an aggregate, in JOIN conditions, or in window 
functions.
   ```
   
   ## Rolling upgrade
   
   Pinot upgrades brokers before servers. So, for a time, a new broker sends 
queries to old servers.
   
   - A query that plans on master gets plan A, which is the plan of master. Old 
servers run it. The compatibility suite runs two leaf-only `GROUP BY 
ARRAY_TO_MV` queries at every step of the upgrade and rollback.
   - A query that fails on master gets plan B. An old server fails it with 
`Unsupported PlanNode type`, where master failed it with the `ARRAY_TO_MV` 
error.
   - The MV aggregate reports its stats as `AGGREGATE`, so an old server that 
receives them keeps the `numGroupsLimitReached` and `partialResult` flags.
   
   ## Decisions and trade-offs
   
   - **The fallback applies to the whole query.** If one `GROUP BY ARRAY_TO_MV` 
of a query needs the MV aggregate, plan B uses it for every `ARRAY_TO_MV` group 
key of the query, with the nullable type. A per-aggregate choice needs one 
planner pass for each aggregate, and the plan of one aggregate can change the 
stages of another.
   - **The null semantics of `ARRAY_TO_MV` depend on the plan.** In plan A, 
`ARRAY_TO_MV(c) IS NOT NULL` folds to `TRUE` and `COALESCE` around it is 
removed, as on master. In plan B, the same expressions are correct. So adding a 
join to a query can change these results. Fixing plan A changes queries that 
work today, so it is out of scope.
   - **In plan B, a filter that reads an MV key stays above the aggregate as a 
whole.** Its conditions on other keys do not go into the leaf stage, and the 
leaf stage gets no pre-filter on the MV key. Such queries fail on master, so no 
query gets slower.
   - **The groups limit does not stop the expansion.** After the limit, a 
combination of a row can still belong to a group that exists, and that group 
must get its values, as in the single-value path. The query timeout bounds the 
time.
   - **There is no switch.** The fallback is always on for the default planner. 
A query that needs the MV aggregate fails on an old server, as it fails today.
   - **Performance was not measured** against `CROSS JOIN UNNEST`.
   
   ## Out of scope
   
   These changes were in 
[apache/pinot#20061](https://github.com/apache/pinot/pull/20061). Each one 
changes queries that work on master, so each one needs its own PR:
   
   - The `HAVING` fix for leaf-only queries. On master, `SELECT 
ARRAY_TO_MV(tags), COUNT(*) FROM t GROUP BY ARRAY_TO_MV(tags) HAVING 
ARRAY_TO_MV(tags) = 'vip'` also returns the other tags of a matching row. This 
PR keeps that result for such queries.
   - The null results of `ARRAY_TO_MV` in plan A: `IS NOT NULL` folded to 
`TRUE`, and `COALESCE` removed.
   - The rejection of a plain `GROUP BY mvCol` with the hint 
`is_partitioned_by_group_by_keys`.
   
   ## Testing
   
   Planner (`pinot-query-planner`):
   
   - Every plan fixture that exists on master is unchanged, except the error 
messages in `ValidationErrorPlan.json` and one case there that now plans with 
the MV aggregate.
   - `MvAggregatePlans.json` in `ResourceBasedQueryPlansTest`: MV keys on a 
scan that keep the plain aggregate, the MV aggregate through the skip-leaf hint 
(two MV keys, MV and single-value keys, group trimming, `DISTINCT`, 
`is_leaf_return_final_result`, an array-function key, a leaf `WHERE`, a 
nullable MV column), above a join, above a lookup join, in a subquery, grouping 
sets, and the error cases.
   - `MvAggregateFallbackTest`:
     - leaf-only queries keep the plain plan, also with a semi-join and with 
`HAVING` on the MV key;
     - queries that fail on master get the MV aggregate, also with `EXPLAIN 
PLAN WITHOUT IMPLEMENTATION`;
     - the table names are the tables of the plan that runs (a `HAVING ... IS 
NULL` that removes a table in plan A but not in plan B);
     - a filter on the MV key above a semi-join falls back, and the filter 
stays above the MV aggregate;
     - plan A has the NOT NULL type of master, plan B the nullable type.
   - `SqlNodeCopierTest`, `ArrayToMvGroupKeysTest`, 
`ArrayToMvValidationVisitorTest`, `ArrayToMvFunctionNameTest`, 
`PinotLogicalMvAggregateTest`, `MvAggregateNodeTest`, `PlanNodeSerDeTest`, 
`PlanNodeToRelConverterTest`, `NodeEquivalenceFieldCoverageTest`.
   
   Runtime (`pinot-query-runtime`):
   
   - `MvAggregateOperatorTest`: the SSE rules above, FILTER clauses, group 
trimming, the groups limit, each stored type, `BYTES` keys, list and 
primitive-array values, too many combinations, an empty key after keys whose 
product overflows, batches with and without FILTER clauses, and the `AGGREGATE` 
stats type. Most cases run with row-heap and serialized input blocks.
   - `MvKeyExpanderTest`, `ServerPlanRequestVisitorMvAggregateTest`.
   - `MvAggregate.json` in `ResourceBasedQueriesTest`: results on a scan and 
above a join, two MV keys, subqueries, `DISTINCT`, `HAVING`, `ORDER BY ... 
LIMIT`, FILTER clauses, lookup joins, the `CROSS JOIN UNNEST` equivalent, and a 
table with column-based null handling.
   
   Integration (`pinot-integration-tests`): `MultiStageEngineIntegrationTest` 
runs the `ARRAY_TO_MV` group-by tests with the plain aggregate and with the MV 
aggregate, and compares them with the SSE and with `CROSS JOIN UNNEST`.
   
   Compatibility 
(`compatibility-verifier/multi-stage-query-engine-test-suite`): two leaf-only 
`GROUP BY ARRAY_TO_MV` queries run at every step of the rolling upgrade and 
rollback.
   
   Docs: 
[pinot-contrib/pinot-docs#1153](https://github.com/pinot-contrib/pinot-docs/pull/1153).
   
   Thanks to @yashmayya for the fallback design, and for the review of #20061 
that this PR follows: the decision in `compile()`, the filter rule only in plan 
B, and `MvAggregateOperator extends AggregateOperator`.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to