Skip to content

Fix stale argument names of derived indexHint and let them prune below GROUP BY and LIMIT BY - #126219

Merged
fm4v merged 12 commits into
ClickHouse:masterfrom
groeneai:groeneai/derived-index-hint-below-group-by
Oct 28, 2026
Merged

fm4v merged 12 commits into
ClickHouse:masterfrom
groeneai:groeneai/derived-index-hint-below-group-by

Conversation

@groeneai

@groeneai groeneai commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124502
Related: #122975

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed wrong results when an outer WHERE compares columns of a remote() or Distributed subquery that gives a column the name of another one (SELECT w AS k ...) and optimize_and_compare_chain derives an indexHint from it. Such derived hints are now also used for primary key analysis below GROUP BY and LIMIT BY.

Description

On 26.9.19.9 and master, with t ORDER BY k, SELECT count() FROM (SELECT w AS k, v FROM remote('127.0.0.1', currentDatabase(), t) AS t WHERE t.k < 1000) WHERE k < v AND v < 3 returns 0 instead of 5. The chain adds indexHint(k < 3), whose argument is bound by name inside the hint. Merging actions rebinds the filter's inputs through k := w but not the hint, and in the local-replica plan k is the physical key.

Since #122975, filters pushed below GROUP BY or LIMIT BY refuse every hint, so with ORDER BY a these read the whole table:

SELECT a, b FROM t GROUP BY a, b HAVING a < b AND b < 10;                -- 782/782 granules, 8/782 with this fix
SELECT a, b FROM t GROUP BY a, b HAVING (b < a AND a < 10) OR a = 500;   -- 782/782, 10/782

A derived hint follows from the other conjuncts of its and, so every row it prunes is rejected by the filter. The compare-chain and OR-LIKE rewrites now mark their hints (FunctionIndexHint::isImplied), and key steps admit only marked hints; user hints and the optimize_append_index hint stay refused, and a user hint merged with an equal derived one clears the mark. ActionsDAG::mergeInplace rebinds a marked hint's arguments to what the actions below compute, and drops it when a name changes type or those actions are arrayJoin or non-deterministic. The GROUPING SETS check counts the columns a marked hint reads. Hints stay above totals, which are not filtered. The query condition cache key now includes a hint's own DAG.

Validation: 05401_index_hint_derived_below_group_by (782/782 granules without the fix, 8 to 94 with it; also the remote() alias, ARRAY JOIN, GROUPING SETS and WITH TOTALS cases) and 05401_index_hint_derived_query_condition_cache (4 rows instead of 100 when warm); 50/50 randomized, 10/10 Replicated database.


Workflow [PR]
Sync PR [sync-upstream/pr/126219]

Version info

  • Merged into: 26.11.1.846-master (included in 26.11 and later)
  • Backported to: 26.10.3.20

groeneai and others added 9 commits October 15, 2026 21:34
Since ClickHouse#122975 a filter pushed below AggregatingStep / MergingAggregatedStep /
LimitByStep refuses every indexHint, because a user-written hint is row-level
TRUE and pruning by it below a key step can drop part of a group. That also
refuses the hints optimize_and_compare_chain derives (`a < b AND b < 10` adds
`indexHint(a < 10)`), and since a hint blocks its ancestors, an OR holding one,
so such HAVING / outer WHERE filters read the whole table.

A derived hint is implied by the other conjuncts of its `and`, so the granules
it prunes contain only rows of groups the filter rejects anyway. Mark such
hints in FunctionIndexHint, carry the mark through the planner and
buildFilterActionsDAG, and admit only marked hints at key steps. The planner
deduplicates equal hints by name, so a user hint equal to a derived one
clears the mark of the shared node.

Closes ClickHouse#124502

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ConvertOrLikeChainPass rewrites a pure LIKE chain into
`and(optimized_or, indexHint(original_or))`. The rewrite preserves results,
so `optimized_or` implies the hint, which is exactly the property the
implied mark stands for. Without the mark the hint was refused below
GROUP BY / LIMIT BY and kept every ancestor above the step, so
`HAVING (a < 10 AND (s LIKE '%1%' OR ... 4 substrings)) OR a = 500`
still read the whole table. Create both derived hints through
`FunctionIndexHint::createImplied`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The arm F granule line also holds when no hint exists, so assert the hint first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A factored hint is implied only if every copy was.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Arm G only checks the final count, so it passes on every build when
`optimize_extract_common_expressions` does not factor `indexHint(k < 3)`
out of the `OR`: each branch then keeps its own copy and the false-wins
rule is never exercised. An EXPLAIN SYNTAX line before it now requires
the factored `WHERE and(indexHint(...` form for the same query and
settings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An `indexHint` keeps its arguments in a private DAG bound by name, and `ActionsDAG::mergeInplace` rebound only the
filter's own inputs, so below a renaming projection a derived hint kept the outer name, which in a `remote()`
local-replica plan binds to the physical column it shadows. `mergeInplace` now rebinds the private DAG of implied
hints to the outputs that compute those names (user hints are left as they are), so
`SELECT count() FROM (SELECT w AS k, v FROM remote('127.0.0.1', currentDatabase(), t_w) AS t GROUP BY w, v, t.k) WHERE k < v AND v < 3`
returns 5 instead of 0.

The 05401 test gains that query and a derived hint from an outer WHERE pruning through a GROUP BY subquery.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A derived hint lifted below ARRAY JOIN read the array under the element's
name, so rebinding it made valid queries throw (J2: `ARRAY JOIN arr GROUP BY
arr, v` under an outer `arr < v AND v < 3`), and such a hint is now dropped.
A filter made of one hint had no identifiers for the GROUPING SETS check, so
a rebound outer hint pruned rows that a set without its key needs (S: 1 row
instead of 0), and the hint's own inputs now count as identifiers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`FunctionIndexHint::createImplied` and `FunctionIndexHint::tryGet` are now
called from dbms (the analyzer passes, `ActionsDAG`, filter push-down), so
targets that link only dbms, such as `format_fuzzer`, failed with undefined
symbols. Move the file to `DBMS_FUNCTIONS` like the other helpers dbms uses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (rounds 1-7)

Bounce cap reached: published as is; residual findings listed below.

  • ❌ remote() / Distributed local replica: a derived hint that passed GROUP BY kept names from above the projection and pruned on the shadowed column (SELECT count() FROM (SELECT w AS k, v FROM remote('127.0.0.1', currentDatabase(), t) AS t GROUP BY w, v, t.k) WHERE k < v AND v < 3 = 0 instead of 5, also poisoning the query condition cache): AGREE, fixed (merged actions rebind the hint like the filter's inputs; new test arm).
  • ❌ That rebind bound a hint lifted below ARRAY JOIN to the array of the same name, so KeyCondition threw ILLEGAL_TYPE_OF_ARGUMENT on valid queries (... FROM t ARRAY JOIN arr GROUP BY arr, v) WHERE arr < v AND v < 3): AGREE, fixed (a retyped hint is dropped; new test lines).
  • ❌ A filter of one derived hint has no identifiers, so it passed the GROUPING SETS check and pruned rows another set needs (1 row instead of 0): AGREE, fixed (the check sees what the hint reads; new test arm).
  • ⚠️ optimize_or_like_chain hints stayed refused below GROUP BY / LIMIT BY: AGREE, fixed (both passes mark through one helper; new test arm).
  • ⚠️ That arm would pass if the rewrite stopped firing: AGREE, fixed (precondition check).
  • ⚠️ optimize_extract_common_expressions kept the marked copy of a user hint equal to a derived one (6 rows instead of 13 via a remote() local replica): AGREE, fixed (the factored hint stays marked only if every copy was; new test arm).
  • ⚠️ The outer WHERE and factored-hint arms would pass if their producer stopped firing: AGREE, fixed (precondition checks).
  • ⚠️ A derived hint from an outer WHERE kept stale names below a subquery boundary: AGREE (first dismissed as pre-existing), fixed by the same rebind.
  • ✅ GROUP BY ... WITH TOTALS with an outer chain WHERE: the derived hint pruned groups below totals (totals row 0 119 instead of 0 199). Fixed in 5b22d2d: no hint is pushed below totals.
  • ⚠️ optimize_append_index hint stays unmarked: DISAGREE. It follows from CHECK/ASSUME constraints (createIndexHintGroup in ConvertQueryToCNFPass.cpp), not from the filter's conjuncts, and ASSUME is never checked. Named in the description.
  • 💡 The description's no-GROUP BY remote() query has no test line of its own (arm W covers the rebind): noted, not blocking.
  • 💡 Pass-created hints are not listed in query_log.used_functions: noted, not blocking.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new 05401 test on a base build prints Granules: 782/782 on all five granule lines, every run.
b Root cause explained? #122975 passes allow_index_hints = false at Aggregating / MergingAggregated / LimitBy push-down, so getConjunctionNodes refuses every indexHint and its ancestors, including the hints optimize_and_compare_chain / optimize_or_like_chain derive; the read stays unpruned.
c Fix matches root cause? Yes. Derived hints are marked as implied by their sibling conjuncts and key steps admit only those; user hints stay refused as in #122975.
d Test intent preserved / new tests added? New 05401: GROUP BY, hint in an OR, aggregate-derived hint, LIMIT BY, OR-LIKE hint, user/derived collision both orders, factored hint over remote(), outer WHERE through GROUP BY, renaming remote() subquery, two ARRAY JOIN and one GROUPING SETS case, each producer-dependent line after a precondition check. 05291_index_hint_below_window unchanged and green.
e Both directions demonstrated? Base 782/782, fix 8, 10, 94, 10, 10 of 782 with equal counts. Mutants: no mark reddens all five granule lines, OR-LIKE unmarked the fifth, no collision rule 6 instead of 13, no extraction retention 6 instead of 13, no rebind 0 instead of 5, no type check Code: 43 on both ARRAY JOIN lines, no GROUPING SETS inputs 1 instead of 0; disabling a producer fails its precondition check.
f Fix is general across code paths? Both key-step sites share getConjunctionNodes; both producers mark through FunctionIndexHint::createImplied; every other hint source stays unmarked.
g Fix generalizes across inputs (params/datatypes/wrappers)? 20-shape matrix (TOTALS, ROLLUP, CUBE, GROUPING SETS, group_by_use_nulls, Nullable/LowCardinality keys, LIMIT BY) identical with push-down on, off and chain off; stable over coarse granularity 2-32 and 50 randomized runs.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format, default or EXPLAIN change; an unaware server treats the hint as user-written.
i Invariants and contracts preserved? An admitted hint is implied by its filter; merging rebinds it to what computes its names or drops it on a type change; the filter's own conjuncts are still applied in full.

Session id: cron:clickhouse-impl-slot-40:20261016-051100

@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0d0eb80]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR fixes stale bindings in derived indexHint predicates and restores safe pruning below GROUP BY and LIMIT BY. No unresolved findings remain. Both added regression tests match their reference output on the PR binary, and 126 additional result comparisons pass.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin @KochetovNicolai, could you review this and add can be tested (CI did not start without it)? Since #122975, filters pushed below GROUP BY / LIMIT BY refuse every indexHint, including the ones optimize_and_compare_chain derives, so these queries read the whole table; this marks derived hints as implied by their sibling conjuncts, admits only those at key steps, and rebinds their private DAG in ActionsDAG::mergeInplace, which also fixes a wrong result over a renaming remote() subquery.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 16, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Oct 16, 2026
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
groeneai and others added 2 commits October 16, 2026 09:03
An implied hint rebound by `mergeInplace` keeps its outer name, and it has
no children, so `Node::updateHash` keyed it by that name alone. The query
condition cache then served one binding's exclusions to another: after
`SELECT n FROM (SELECT k AS a, max(b) AS m, count() AS n FROM t GROUP BY a) WHERE a < m AND m < 3`
the same outer query over `w AS a` read only the granules where `k < 3`
(n = 4 instead of 100, default settings).

Only the exact hash includes the private DAG. Build-independent hashes key
statistics, already drop the names that tell hints apart, and would pick up
the branch-local `__tableN` names of the hint's inputs.

The test is `no-parallel` because its cache-hit check, which proves the
entry was written, can be evicted by a sibling test's
`SYSTEM CLEAR QUERY CONDITION CACHE`, like the other query condition cache
tests that assert hits.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The totals row is not filtered, so it aggregates every group. An implied
hint pushed below `TotalsHavingStep` then passed the aggregation and pruned
granules: for
`SELECT * FROM (SELECT a, max(b) AS m FROM t GROUP BY a WITH TOTALS) WHERE a < m AND m < 120`
the totals row was computed over the kept granules only (`0 119` instead of
`0 199`), which also depends on the part layout.

`allow_index_hints` becomes `PushDownIndexHints`: all hints, implied ones
only (GROUP BY, LIMIT BY), or none (totals). A user hint pushed below totals
used to stop at the aggregation anyway, so only implied hints change. A
query with `WITH TOTALS` keeps master's behaviour and does not prune.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5b22d2d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (arm_binary, 3/4) / test_backward_compatibility/test_custom_s3_disk_remote_url_allow_hosts.py (both tests) not from this PR: red on master since 09:59Z and on many other PRs. The old server image now runs the remote_url_allow_hosts check for SQL disks, so the first CREATE fails with Code: 491 ... is not allowed in configuration file #126289 (mine, open)
Performance Comparison (arm_release, master_head, 5/6) / datetime_comparison #4, #6 dashboard confirmed_regression +17.7% / +17.1%, reproduced after restart. These queries filter numbers(1000000000) by a materialized date comparison, with no GROUP BY, HAVING or indexHint; this diff only changes indexHint nodes and their pushdown, at plan time. The same shard flagged datetime_comparison on two unrelated PRs today (#5/#6 and #1) a fix task is created (investigating at full effort, fixing-PR link to follow here)
CH Inc sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR praktika rollups of the rows above #126289 and the fix task above (the owners of the first two rows)

Session id: cron:our-pr-ci-monitor:20261016-133003

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the datetime_comparison arm_release perf red: #126306

@fm4v
fm4v added this pull request to the merge queue Oct 28, 2026
Merged via the queue into ClickHouse:master with commit 524cebd Oct 28, 2026
350 of 355 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 28, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @fm4v — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

#128077 fixes the GROUPING SETS full scan from #128072.

@groeneai

Copy link
Copy Markdown
Collaborator Author

#128079 fixes the set index finding from #128071.

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 29, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 29, 2026
Backport #126219 to 26.10: Fix stale argument names of derived `indexHint` and let them prune below `GROUP BY` and `LIMIT BY`
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 31, 2026
Master now limits the nesting depth of a deserialized ActionsDAG to 1000
levels (ClickHouse#126548), counted through the recursive calls for lambda captures.
The predicate of indexHint is deserialized by the same recursion, but the
call did not pass the depth, so a QueryPlan packet with nested indexHint
nodes was not covered by the limit (only by checkStackSize). Measured on a
debug build: chains of 1001, 1500 and 3000 levels were accepted, 5000 was
rejected by checkStackSize. Now every chain above 1000 levels gets
TOO_DEEP_RECURSION, and 05427 has an indexHint arm at 1500 levels.

Also use FunctionIndexHint::tryGet, which ClickHouse#126219 added on master, instead
of the same two casts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fm4v fm4v self-assigned this Nov 2, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…Hint` and let them prune below `GROUP BY` and `LIMIT BY`
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 13, 2026
Since ClickHouse#126219 the GROUPING SETS check in tryPushDownFilter also counts the
columns that an implied indexHint reads, so that a filter consisting only of
such a hint cannot prune rows below a set that lacks its key. But the hint's
own actions are built from the query tree and read the table column (`k` of
key `intDiv(k, 10)`, `ts` of `toDate(ts)`), which is in no grouping set. The
check then rejected the whole filter, and its other conjuncts (`v < 3`),
which 26.10 pushed to the read, stopped pruning: the query from ClickHouse#128072 read
78/78 granules instead of 3/78.

Collect the hint inputs separately. The filter's own identifiers still gate
it as before. When a hint input is missing from some set, push the filter
with PushDownIndexHints::None, so the other conjuncts go below the
aggregation as on 26.10 and every hint stays above it; otherwise keep
PushDownIndexHints::Implied as on master. Applies to MergingAggregated too.

The existing GROUPING SETS ((a, b), (b)) case of 05401 still returns 0; with
the hints pushed (Implied instead of None) it returns 1.

Closes ClickHouse#128072

Co-Authored-By: Claude Opus 5.5 <[email protected]>
arwenizEr pushed a commit to arwenizEr/ClickHouse that referenced this pull request Nov 18, 2026
`k < v AND v < 3` derives `indexHint(k < 3)`. Since ClickHouse#126219 the hint's
own DAG is rebound through the projection and keeps aliases, so for
`SELECT w AS k ...` it holds `k` as an alias of `w`. `getArguments` in
the set index imported that DAG with `ActionsDAG::mergeNodes`, which
binds every node to an existing node of the same name. When the read
also references the physical `k` (`t.k < 1000`), the alias was bound to
that column, and the exact per-value evaluation tested `k < 3` on `k`,
dropping granules whose rows match (ClickHouse#128071).

Import the hint's nodes with `ActionsDAG::unite`, which matches nothing
by name. Key columns are bound by their alias-free name in
`atomFromDAG`, the same way `KeyCondition` and the RPN-based skip
indexes read the hint, so a hint over the key column itself still
prunes.

This also fixes the `remote()` local-replica shape with a set index,
which still returned 0 instead of 5 on master after ClickHouse#126219.

Closes ClickHouse#128071

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Derived indexHint in HAVING/QUALIFY stops key pruning, blocks OR pushdown

6 participants