Skip to content

Fix NOT_FOUND_COLUMN_IN_BLOCK when the optimize_and_compare_chain budget runs out between copies of an alias - #125735

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-and-compare-chain-budget-alias-copies
Oct 19, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-and-compare-chain-budget-alias-copies

Conversation

@groeneai

@groeneai groeneai commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

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 NOT_FOUND_COLUMN_IN_BLOCK when the optimize_and_compare_chain_max_hash_work budget ran out between two copies of an expression, for example a SELECT alias of an AND chain of comparisons that is reused in GROUP BY. The transitive comparisons of optimize_and_compare_chain are now derived for the whole query or not at all.

Description

On 26.8.18.2 and 26.9.9.28, SELECT (number < (number + 1)) AND ((number + 1) < 3) AS r FROM numbers(5) GROUP BY r SETTINGS optimize_and_compare_chain_max_hash_work = 100 fails with Code: 10 NOT_FOUND_COLUMN_IN_BLOCK instead of returning 0 and 1. With the default budget a large query fails the same way when its WHERE spends the budget (projection, WHERE and GROUP BY are visited in that order).

The budget (#108757) is one counter per run of LogicalExpressionOptimizerVisitor, and the compare chain stops once it is spent. The analyzer keeps separate copies of an alias (projection, GROUP BY key, ...). When the budget ran out between them, only one copy got the derived indexHint(number < 3), the action names differed and the planner could not find the key.

The derivation now runs as its own traversal, after the JOIN ON rewrites as before, and ahead of the other rewrites of the pass. It records each and node it appended to, and if the budget was exceeded it restores all of them, so equal copies stay equal. The other rewrites run afterwards, so the conflict detector still sees derived conjuncts. A query over the budget now gets no derived conjuncts at all.

The new test sweeps the budget over 0..600 with the identifier resolve cache on and off; on master 20 to 31 of the 122 runs per shape fail. A 721-test batch of tests that use the optimization or EXPLAIN an AND, with random settings on and off, shows no new failure and no changed reference. EXPLAIN QUERY TREE, median of 7: 5000 disjuncts 0.87 s before and after; an over-budget query 5.26 s before, 4.75 s after.

Related: #123925 (its review found this; a different root cause)
Related: #108757


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

Version info

  • Merged into: 26.11.1.192-master (included in 26.11 and later)

groeneai and others added 3 commits October 14, 2026 02:46
…or not at all

`optimize_and_compare_chain_max_hash_work` is one budget per run of
`LogicalExpressionOptimizerVisitor`, and `tryOptimizeAndCompareChain` stops
once it is spent. The analyzer keeps separate copies of an alias expression
(the projection and the GROUP BY key, ORDER BY, ...), which the visitor
reaches at different times. When the budget ran out between two copies, one
of them got the derived conjuncts (e.g. `indexHint(number < 3)`) and the other
did not, their action names differed, and the planner failed with
`NOT_FOUND_COLUMN_IN_BLOCK`:

    SELECT (number < (number + 1)) AND ((number + 1) < 3) AS r
    FROM numbers(5) GROUP BY r
    SETTINGS optimize_and_compare_chain_max_hash_work = 100

The same happens with the default budget on a large query whose WHERE
exhausts it between the projection and GROUP BY.

The derivation now runs as its own traversal before the other rewrites of
the pass. It records every `and` node it appended to (with the original
argument count and function), and if the budget was exceeded anywhere,
it restores all of them, so equal copies are rewritten the same way. The
main traversal no longer calls the compare chain; it still runs after the
derivation, so the conflict detector sees the derived conjuncts as before.
The budget keeps its unit and bounds the same hashing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…erivation

The first traversal now also runs the `JOIN ON` visitor at the join node,
where the single traversal ran it before, so the derivation sees the
rewritten `JOIN ON` again (including its common-expression extraction).
The second traversal no longer runs the `JOIN ON` visitor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the budget and revert comments; drop the sentence duplicated by the revert function's comment.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex) plus my own cold review, two rounds; 5 findings.

# Sev Finding Verdict Evidence / action
1 ⚠️ The derivation ran on JOIN ON before the JOIN ON rewrites, so (k AND c1) OR (k AND c2) could lose its single-side conjunct after common-expression extraction AGREE, fixed @ c7e5cfa the JOIN ON rewrites run in the first traversal, at the same point as before relative to the derivation; EXPLAIN SYNTAX / EXPLAIN PLAN of that JOIN ON are byte-identical to master
2 💡 The first traversal's caches inflated use_count() for the JOIN ON visitor (extra clone) AGREE, fixed @ c7e5cfa same change as 1
3 💡 04492's header still says the optimization backs off "for the rest of the query" DISAGREE its assertions are unchanged; editing it would put a test that passes on master into Bugfix validation
4 💡 PR body used shorthand references AGREE full-URL Related: lines
5 💡 An and that replaces its parent in the same visit (e.g. the and of (a < b AND b < 3) = 1) was never entered by the single traversal; the derivation now reaches it, and the notEquals fold still does not AGREE, noted derived conjuncts are implied by the chain, so results do not change, and every copy of an expression takes the same path; no reference changed in the 721-test batch

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. The second round (Gate B on the fix commit) found nothing new.

Session id: cron:clickhouse-review-slot-9:20261014-034100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT (number < (number + 1)) AND ((number + 1) < 3) AS r FROM numbers(5) GROUP BY r ORDER BY r SETTINGS optimize_and_compare_chain_max_hash_work = 100 (or 170) fails with Code 10 every time, with enable_identifier_resolve_cache 0 and 1. With default settings, a query whose WHERE holds 200 comparison chains over a 5000-element expression fails the same way (also on 26.8.18.2 and 26.9.9.28).
b Root cause explained? The budget is one counter per visitor run, and the compare chain stops once it is spent. The projection copy and the GROUP BY copy of an alias are visited at different times. If the budget runs out between them, only one gets indexHint(...), their action names differ, and the planner cannot find the key.
c Fix matches root cause? Yes. The decision is made per query at the budget: the derivation runs as its own traversal, and every and node it appended to is restored if the budget was exceeded. The planner, the analyzer and the derivation logic are unchanged.
d Test intent preserved / new tests added? New test 05394_optimize_and_compare_chain_budget_alias_copies.sh: budget 0..600 x cache 0/1, with and without ORDER BY, an all-or-nothing EXPLAIN arm, and a liveness check at the default budget. 04492 and the other optimizer tests pass unchanged.
e Both directions demonstrated? Yes. On master the test fails (16 instead of 122 rows per value; 20 EXPLAIN arms derive only one copy). With the fix it passes, and 50/50 with random settings. Both on Build-ID-verified binaries.
f Fix is general across code paths? Every caller goes through LogicalExpressionOptimizerPass::run: the pass manager, row policies / additional filters, the gtest. The JOIN ON rewrites run in the first traversal at the join node, so the derivation sees the rewritten JOIN ON as on master (EXPLAIN SYNTAX of a disjunctive JOIN ON is byte-identical to master's). Nothing else reads the budget.
g Fix generalizes across inputs (params/datatypes/wrappers)? The change is in the traversal, independent of types and shapes. Covered: 61 budget values, cache on and off, ORDER BY / GROUP BY, and the default-budget variant. Nullable and nodes are skipped by the derivation as before.
h Backward compatible? (maintainer-approved exception only) Yes. No default and no new setting. Results are unchanged by construction (derived conjuncts are implied). A 721-test batch shows no changed reference. Only an over-budget query now gets no derived conjuncts at all.
i Invariants and contracts preserved? In the derivation traversal, appends are the only writes to an and node's arguments. Truncating to the recorded size and re-resolving the recorded function restores the node exactly. A shared node keeps its first record. Map keys are strong references, and exceptions propagate as before.

Session id: cron:clickhouse-impl-slot-5:20261014-032200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd, could you review this? The optimize_and_compare_chain_max_hash_work budget could run out between the projection copy and the GROUP BY copy of an alias, so only one copy got the derived indexHint and the planner failed with NOT_FOUND_COLUMN_IN_BLOCK; the derivation now runs as its own traversal and is reverted for the whole query when the budget is exceeded.

@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d866847]

Summary: ✅


AI Review

Summary

This PR fixes NOT_FOUND_COLUMN_IN_BLOCK when optimize_and_compare_chain_max_hash_work is exhausted between copies of an alias by reverting all transitive-comparison additions before the remaining rewrites. Reviewed head d866847ecde2fe1f882f19916455eb9de89b2ff1, the current code, and all prior discussion. No actionable findings.

Final Verdict

✅ Approve. The focused regression test passed in Fast test. Additional local checks against that job's binary covered grouping, windows, joins, and nested subqueries; result comparisons and 4,422 rollback variants passed.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 14, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Oct 14, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 15, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Oct 18, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 18, 2026
Merged via the queue into ClickHouse:master with commit 74d99c6 Oct 19, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 3, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #125735 to 26.10: Fix `NOT_FOUND_COLUMN_IN_BLOCK` when the `optimize_and_compare_chain` budget runs out between copies of an alias
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…optimize_and_compare_chain` budget runs out between copies of an alias
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 15, 2026
The flaky check runs a changed test 50 times on parallel workers that
contend only with each other, and 05394 sends 368 statements per run.
Its master version already averaged 131.7 s there (ClickHouse#125735), and the
PR's copy failed 2 of 50 runs at 182-183 s with the other 48 averaging
126.9 s, so any PR touching it is a coin flip against the 180 s limit.
On master it also averages 175.6 s per run in the `amd_msan` parallel
job.

`long` is the exemption `tests/clickhouse-test` documents for this case;
the test now runs 5 times instead of 50 in the flaky check and is skipped
by Fast test.

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-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). 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.

4 participants