Skip to content

[CALCITE-7974] Many query rewrites lose the WITHIN GROUP sort order and/or FILTER and/or WITHIN DISTINCT of an Aggregate - #5464

Open
mihaibudiu wants to merge 1 commit into
apache:mainfrom
mihaibudiu:issue7974
Open

mihaibudiu wants to merge 1 commit into
apache:mainfrom
mihaibudiu:issue7974

Conversation

@mihaibudiu

@mihaibudiu mihaibudiu commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Jira Link

CALCITE-7974

Changes Proposed

This is fixing many instances of the same kind of bug, across many files. I will post a comment to help the reviewers navigate the many changes. Solving this as separate JIRA issues would probably help reviewers but make my life much more difficult.

An AggregateCall has four fields that refer to fields of the Aggregate input:

Field SQL
argList the arguments
filterArg FILTER (WHERE ...)
distinctKeys WITHIN DISTINCT (...)
collation WITHIN GROUP (ORDER BY ...)

Many places that build or rewrite an AggregateCall remap argList and filterArg, but drop the other fields or keep their old indexes. The result is a wrong result, a lost sort order, or a crash.

Each fix is small and independent.

…nd/or FILTER and/or WITHIN DISTINCT of an Aggregate
@mihaibudiu

Copy link
Copy Markdown
Contributor Author

An AggregateCall has four fields that refer to fields of the Aggregate input:

Field SQL
argList the arguments
filterArg FILTER (WHERE ...)
distinctKeys WITHIN DISTINCT (...)
collation WITHIN GROUP (ORDER BY ...)

Many places that build or rewrite an AggregateCall remap argList and filterArg, but drop the other fields or keep their old indexes. The result is a wrong result, a lost sort order, or a crash.

Each fix is small and independent.

Bugs and tests

Bugs exercised by the default JDBC path

Class Bug Fix Test
RelDecorrelator decorrelateRel(Aggregate) and RemoveCorrelationForScalarAggregateRule do not remap the WITHIN GROUP and WITHIN DISTINCT keys remap them with the same rules as the arguments sub-query.iq, 5 queries after the CALCITE-7974 header
AggregateCaseToFilterRule the new call drops WITHIN GROUP and WITHIN DISTINCT keep the sort; do not change calls with WITHIN DISTINCT agg.iq, 2 queries after the CALCITE-7974 header
AggregateMergeRule merges SUM over SUM ... WITHIN DISTINCT reject calls with WITHIN DISTINCT within-distinct.iq, "AggregateMergeRule merges SUM over SUM WITHIN DISTINCT"
AggregateExpandDistinctAggregatesRule keeps the old WITHIN DISTINCT keys at 4 sites (crashes and wrong results) pass null for the keys within-distinct.iq, 3 queries after "AggregateExpandDistinctAggregatesRule keeps the WITHIN DISTINCT keys"; JdbcTest.testAggregateExpandDistinctDistinctWithinDistinct
AggregateExpandWithinDistinctRule drops the sort of a DISTINCT call sort the outer call within-distinct.iq, "AggregateExpandWithinDistinctRule drops the WITHIN GROUP sort order"
SqlFilterOperator the validator throws on PERCENTILE_DISC(...) WITHIN GROUP (...) FILTER (...) the operator binding gives the type of the sort key agg.iq, "The validator fails on FILTER after WITHIN GROUP in PERCENTILE_DISC"
TopDownGeneralDecorrelator reads a group key at its old position after a join moves the columns map the key through oldToNewOutputs sub-query.iq, last query (fails in CoreQuidemTest2)

Bugs in optimization rules

Class Bug Fix Test
AggregateFilterToCaseRule drops WITHIN GROUP keep the sort JdbcTest.testAggregateFilterToCaseKeepsSortOrder
AggregateFilterToCaseRule changes FILTER to CASE for a function that does not skip NULL inputs leave the call unchanged (the reverse rule has this check since CALCITE-7330) RelOptRulesTest.testAggregateFilterToCaseWithCustomNullAwareUdaf
AggregateExtractProjectRule removes the columns of the sort and WITHIN DISTINCT keys take the used fields from RelOptUtil.getAllFields JdbcTest.testAggregateExtractProjectKeepsSortKey, testAggregateExtractProjectKeepsWithinDistinctKey
AggregateFilterTransposeRule rolls up a WITHIN DISTINCT call refuse JdbcTest.testAggregateFilterTransposeWithinDistinct
AggregateUnionTransposeRule splits a WITHIN DISTINCT call refuse JdbcTest.testAggregateUnionTransposeWithinDistinct
AggregateJoinTransposeRule (extended) splits a WITHIN DISTINCT call refuse JdbcTest.testAggregateJoinTransposeWithinDistinct
AggregateJoinTransposeRule (extended) splits BIT_XOR without the count of joined rows (x XOR x is 0) refuse BIT_XOR JdbcTest.testAggregateJoinTransposeBitXor
AggregateExpandDistinctAggregatesRule (TO_JOIN) splits a WITHIN DISTINCT call convertSingletonDistinct refuses it JdbcTest.testAggregateExpandDistinctToJoinWithinDistinct
MeasureRules.AGGREGATE drops the FILTER of AGGREGATE(m) refuse JdbcTest.testMeasureAggregateRuleKeepsFilter

Bugs in materialized views and lattices

Class Bug Fix Test
MaterializedViewAggregateRule matches calls without comparing WITHIN DISTINCT and WITHIN GROUP refuse such query calls; skip view calls with WITHIN DISTINCT MaterializationTest.testMaterializationWithinDistinct, testMaterializationWithinGroup, testMaterializationRollUpWithinDistinct, testMaterializationViewWithinDistinct
SubstitutionVisitor rolls up a WITHIN DISTINCT call no roll-up for these calls MaterializationTest.testMaterializationRollUpWithinDistinctKey
SubstitutionVisitor drops the FILTER when it computes a call from the group keys of the view map the filter column like the arguments MaterializationTest.testMaterializationRollUpFilter
AggregateStarTableRule the tile measure COUNT(*) answers COUNT(*) WITHIN DISTINCT (...) and COUNT(*) FILTER (...) refuse calls with FILTER, WITHIN DISTINCT or WITHIN GROUP LatticeTest.testTileWithinDistinct
MaterializationService defineTile chooses the best roll-up tile but does not return it (since CALCITE-6763) return it LatticeTest.testTileRollUp

Bugs in tools

Class Bug Fix Test
SqlImplementor (rel2sql) writes a WITHIN GROUP sort expression as an ordinal no ordinals in WITHIN GROUP RelToSqlConverterTest.testWithinGroupExpression
SqlImplementor (rel2sql) drops WITHIN DISTINCT write it, inside FILTER RelToSqlConverterTest.testWithinDistinct, testWithinDistinctFilter
SqlImplementor (rel2sql) hasNested checks only the arguments, so a window function goes into FILTER or WITHIN GROUP check all the fields of the call RelToSqlConverterTest.testAggregateFilterAndSortOnWindowFunction
RelJson, RelJsonReader the JSON form drops FILTER, WITHIN DISTINCT, WITHIN GROUP, APPROXIMATE and IGNORE NULLS write and read them, only when set RelWriterTest.testAggregateCallFieldsRoundTrip, testAggregateCallFlagsRoundTrip
RelBuilder a WITHIN GROUP sort key that is an expression throws use the field of the registered expression RelBuilderTest.testAggregateCallSortByExpression
RelBuilder pivot replaces the FILTER of the call AND the two filters RelBuilderTest.testPivotKeepsFilter
RelBuilder over() drops FILTER, WITHIN DISTINCT, WITHIN GROUP and pre-operands throw for these calls RelBuilderTest.testOverRejectsFilterAndSort
AggregateCall equals ignores rexList, but hashCode uses it, so LITERAL_AGG(1) equals LITERAL_AGG(2) compare rexList RelBuilderTest.testLiteralAggCallEquals, testAggregateDuplicateLiteralAggCalls

Test fixture

Since CALCITE-7712, ReflectiveSchema.Factory requires @ReflectiveSchema.Input. MaterializationTest.HrFKUKSchema and testkit HrSchema did not have it, so 8 MaterializationTest tests failed. The class is tagged slow, so the build did not run it.

Testing

  • Each new test failed before its fix.
  • The expected results were validated with PostgreSQL 14 (some also with DuckDB). The comment of each test says how the query was translated.
  • LatticeTest and MaterializationTest are tagged slow, and the CI build does not run them. MaterializationTest passes. LatticeTest has 15 failures that also occur without this PR: no lattice query on a JDBC or clone schema uses a tile.

@sonarqubecloud

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant