Repository navigation
Look through an alias on the filter column in read-in-order analysis - #116835
Conversation
`appendFixedColumnsFromFilterExpression` collects the columns that a filter pins to a constant, so that a sorting key column fixed by WHERE can be skipped and a later key column can still drive the read direction. It descends only FUNCTION nodes, handling `and` and `equals`. An `ALIAS` node on the filter therefore stops the walk on its first iteration and no fixed columns are collected at all. `fixed_key_columns` ends up empty, the skip at `buildInputOrderFromSortDescription` cannot fire, the ORDER BY column never matches the sorting key, and the read falls back to ReadType::Default with a full sort of every matching row before the LIMIT applies. That state is reachable, and normal projections reach it on every single-predicate query: the projection rewrite wraps the query filter in an ALIAS named `_projection_filter` when there is exactly one filter node, and builds an `and(...)` function otherwise. So the same query reads the projection in order when its filter root happens to be a function and out of order when it is a value-identical alias. Measured on the fixture from ClickHouse#116801, 20M rows: 10,027,008 rows read versus 172,032 once the alias is unwrapped, on the same projection and the same 1223 granules, with byte-identical results. An ALIAS has the same value as its child, so it fixes exactly the columns its child fixes. Unwrapping is a value identity rather than a heuristic, so it needs no setting and no threshold. Doing it inside the walker rather than at a call site covers all three call sites, hence both order builders, and unwrapping at the stack-pop point rather than only at the root also covers an alias nested inside an `and(...)`. This is not specific to projections. A table level `UInt8 ALIAS (a = 1)` column used bare as a predicate, a row policy filter on a Merge table, and an in-place rewrite by filter push-down all produce an ALIAS root, and all were equally blind. ALIAS transparency for this same FixedColumns set is already an invariant of the file: `enrichFixedColumns` propagates fixedness through an alias and `addMonotonicChain` reconstructs through one. `optimizeUseNormalProjection` also already carries this exact unwrap for this exact wrapper, for the same reason. The regression is a performance one only, and read direction can now flip to InReverseOrder where a fixed column precedes a DESC column, which measured 2.2x fewer rows read. A read whose ORDER BY column is itself the filtered column loses the virtual row optimisation, because a fixed key column disables it; that was measured at zero cost in marks, rows and bytes, since every candidate part's virtual row carries the same constant there and cannot discriminate between parts. Co-Authored-By: Claude Opus 5 <[email protected]>
The arms were appended to `04109_read_in_order_with_normal_projection`, which is the existing test of this mechanism. `.claude/CLAUDE.md` asks for the opposite: when writing tests in tests/queries, prefer adding a new test instead of extending existing ones. `04109` is restored to its previous content, byte for byte, and the arms move to `05045_read_in_order_normal_projection_fixed_key`, whose number was assigned by `tests/queries/0_stateless/add-test`. The new file pins the settings the arms had been inheriting from `04109`. Each one is either a setting `clickhouse-test` randomizes, which would blind an arm, or a pin of the plan shape being asserted. `enable_analyzer` and `optimize_use_implicit_projections` are deliberately not pinned: neither is randomized and both already default to the asserted value. One assertion is new. Of the arms that change behaviour with the fix, the one reading through an `ALIAS` at a `FilterStep` was the only one asserting plan shape without also asserting the rows, and a read that claims an order it does not have is the failure this change could introduce. It compares the aliased in-order read against the same query with `optimize_read_in_order = 0`, in the same form as the existing guard on the `PREWHERE` arm. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model reviewAn independent model re-reviewed this change cold against the diff and the plan.
|
|
Workflow [PR], commit [ecfad69] Summary: ✅
AI ReviewSummaryThis PR makes Final Verdict✅ No new review findings. LLVM Coverage Report |
|
cc @novikd @CurtizJ, could you review this? Read-in-order analysis descends only |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 17 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - a71843fEvery failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link Read the per-run columns, not the rollup.
Not a red: On the flaky check specifically, since a flaky-check failure normally means a bad new test: it is Session id: cron:our-pr-ci-monitor:20260828-123000 |
| /// An `ALIAS` has the same value as its child, so it fixes the same columns. | ||
| while (node->type == ActionsDAG::ActionType::ALIAS && !node->children.empty()) | ||
| node = node->children.front(); |
There was a problem hiding this comment.
Can't we reuse the outer stack loop? Something like:
| /// An `ALIAS` has the same value as its child, so it fixes the same columns. | |
| while (node->type == ActionsDAG::ActionType::ALIAS && !node->children.empty()) | |
| node = node->children.front(); | |
| if (node->type == ActionsDAG::ActionType::ALIAS) | |
| stack.push(node->children.front()); |
There was a problem hiding this comment.
Applied in 4aba48e.
Equivalent, yes: an ALIAS is never a FUNCTION, so the rest of the loop body is a no-op for it, and std::stack pops the pushed child on the very next iteration, so the visit order is unchanged. An alias chain now unwinds one node per iteration instead of in an inner loop, and it reaches the same terminal node.
I dropped the empty-children guard along with it, because an ALIAS always has exactly one child: all five construction sites in ActionsDAG.cpp set exactly one (createAlias, addAliases, project, split, and removeUnusedConjunctions under new_children.size() == 1), and deserialization rejects anything else with Deserialized alias must have one children (ActionsDAG.cpp:4588). Lines 177, 205, 950 and 4161 of that file already descend unguarded.
05045_read_in_order_normal_projection_fixed_key still reproduces its reference byte for byte, and pristine master reddens 5 of its 11 assertions. No arm distinguishes the two spellings, since the only way they could differ is an ALIAS whose child count is not one.
Per review: push the alias child back onto the traversal stack instead of unwrapping it locally. An ALIAS is never a FUNCTION, so the rest of the loop body is a no-op for it, and std::stack pops the pushed child on the very next iteration, so the visit order is unchanged. Alias chains unwind one node per iteration instead of in an inner loop, and fixed_columns is a set, so neither the terminal node nor the result can differ. The empty-children guard goes with it, because an ALIAS always has exactly one child. All five construction sites in ActionsDAG.cpp set exactly one (createAlias, addAliases, project, split, and removeUnusedConjunctions under new_children.size() == 1), and deserialization rejects anything else with INCORRECT_DATA "Deserialized alias must have one children" (ActionsDAG.cpp:4588). Four sites in that file already do the descent unguarded (lines 177, 205, 950, 4161). 05045_read_in_order_normal_projection_fixed_key still reproduces its reference byte-for-byte, and pristine master reddens 5 of its 11 assertions.
CI finish ledger - 4aba48eEvery failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will One
Reports:
The fixture table Session id: cron:our-pr-ci-monitor:20260828-220000 |
CI finish ledger: a6838f1Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose
The mismatch is a true positive, not an oracle artifact: the gate is This diff touches Session id: cron:our-pr-ci-monitor:20260831-093000 |
| stack.pop(); | ||
| if (node->type == ActionsDAG::ActionType::ALIAS) | ||
| stack.push(node->children.front()); | ||
| if (node->type == ActionsDAG::ActionType::FUNCTION) |
There was a problem hiding this comment.
Applied in dc130c5.
ActionType is a single-valued uint8_t field (ActionsDAG.h:72-85), so ALIAS and FUNCTION are distinct values one node cannot both hold: chaining the second test onto the first skips a test that could never succeed, and the walk order is unchanged.
Verified rather than assumed. On the rebuilt binary, with its build id asserted against SELECT lower(buildId()) on the probe server, 05045_read_in_order_normal_projection_fixed_key reproduces its reference byte for byte, including the two alias assertions this loop drives.
…exclusive `ActionType` is a single-valued `uint8_t` enum, so a node that is `ALIAS` cannot also be `FUNCTION`: chaining the second test onto the first as `else if` skips a test that can never succeed and states the exclusivity in the code. Requested in review by @ Michicosun.
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) |
the shard's nested containers breach the /docker cgroup leaf, the kernel OOM-kills processes inside it and the job errors with no test attributed |
#117412 (external, merged 2026-09-01T11:31:33Z) |
Docs examples / Documentation examples |
the documented output of Function/toYYYYMM#0 was pinned to 202608, so the example self-broke at the month boundary |
#117459 (mine, merged 2026-09-01T13:55:50Z) |
Bugfix validation (functional tests, amd64 / aarch64), Finish Workflow / Post Hooks |
both per-arch jobs abort on assert build_urls, "Could not find master builds in S3", so nothing could validate and new_tests_check.py then reds the post hook |
#117433 (mine, open) |
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) |
the scanned file holds Cluster: Code: 198. DB::NetException: Not found address of host: <250-byte host>, which is 04725's deliberately unresolvable Remote host being resolved by a restarted server's cluster discovery, not a compatibility break |
#117284 (mine, open) |
The /docker breach is a job-level condition, not a test result. I measured #117412 ABSENT from the tree that ran, from the job's own environment rather than from git ancestry: this job was launched with CI_DIND_INIT_RESERVE=17179869184 (the 16 GiB share #117412 replaces), and so were all ten failing legs I read this tick. The probe discriminates, with a positive control: two shards launched at 14:53Z and 14:59Z carry CI_DIND_INIT_RESERVE=8589934592 (the flat 8 GiB reserve #117412 introduces) and both passed. So this is rule 3c and not rule 3d, and #117411 is not a co-owner: it was closed unmerged at 11:11:48Z in favour of #117412, whose own diff comment states the causal link.
The docs example is a trunk-wide, date-dependent break, not something specific to this PR: 226 distinct pull requests and 10 true-master runs carry it. I measured #117459 ABSENT from the tree that ran, from the failure text itself: the reported query is still the old toYYYYMM(now(), ...) form, and the string the fix introduces appears in 0 of the 164 Docs examples failure rows recorded in the last day. The control is master's own line - Docs examples is FAIL at d8aa6cab7800, which is 4 commits behind the fix and has 0 occurrences of the new string, and OK at 8627fa22f015, which is the fix's own merge commit.
The upgrade-check row is a log-scan allowlist gap, and #117284 is the fix for exactly this string: it adds grep -av -e "Cluster: Code: 198.*Not found address of host: \\(.\\)\\1\\{63,\\}" to upgrade_runner.sh, keyed on a first host label of 64 or more identical characters, which is past the 63 octets RFC 1035 permits, so a genuine failure to resolve a cluster peer still reds the job.
I have not merged master to pick those fixes up yet. It would not clear Mergeable Check on this head, because the Upgrade check allowlist gap and the Bugfix validation abort both remain, and neither fix is merged, so a merge now would cost a full CI cycle and leave the head red on the same count. One master merge picks everything up once the remaining fixes land.
Mergeable Check reports Failed: 4 at this head, which counts only the jobs it gates on. The table above is the complete non-OK, non-SKIPPED node set of the head's praktika report, so it also covers the rows Mergeable Check does not gate.
CH Inc sync was success at this head.
Session id: cron:our-pr-ci-monitor:20260901-163000
Since 26.5 the projection-on-fixed-key shape was planned as a reverse read of the projection; ClickHouse#116854 (merged 2026-09-03) runs read-in-order on the base table before projection selection again, so the same query now reads the base table in reverse order and the projection is not selected. The four counters in the first block therefore move from 1/1/0/1 to 1/0/1/1: the reverse read is unchanged, the projection step goes away and the base-table step appears. Measured on this tree, fix arm vs the same tree with this PR's src hunk reverted (build ids 2e96eb1f0f8dbb47 and 388167cacbbba085, server buildId() asserted on each arm): the first block is 1/0/1/1 on BOTH arms, so its new shape comes from ClickHouse#116854 and not from this change. The aliased-filter-column assertion is 1 on the fix arm and 0 on the reverted arm, and with this updated reference that assertion is the only mismatch the reverted arm produces, so the reference still fails without the alias unwrap.
The `mt_fixed_key` block stopped discriminating once ClickHouse#116854 restored read-in-order on the base table ahead of projection selection: its table key `(c, b)` serves `ORDER BY c DESC` on its own, so that query now reads the base table whether or not the alias is looked through, and the block cannot show the regression the issue reports. `mt_proj_only` keys the table on `a`, which cannot serve `ORDER BY c`, so the projection is the only read that can and only once its leading key `b` is seen as fixed by the `WHERE`. Measured on this tree against the same tree with this PR's src hunk reverted (build ids 2e96eb1f0f8dbb47 and 388167cacbbba085, server buildId() asserted per arm): `ReadType: InOrder` is 1 with the unwrap and 0 without it, while the projection step stays 1 on both arms, so the count attributes the in-order read to the projection rather than to a base-table read. Rows are [1,4,7,10,13] on both arms. Two of the fourteen assertions now fail without the unwrap, this one and the table-level `ALIAS` one; the rest are controls and results-and-order guards. Passes 10 of 10 runs at `--jobs 4`, so it is safe to run in parallel with itself and needs no tag.
Head branch was pushed to by a user without write access
|
Pushed two commits after the master merge, both test-only.
The second commit adds I also re-derived the description and changelog against current master, since the earlier measurement predated #116854: on 10M rows the still-sensitive shape reads 5,021,696 rows before and 98,304 after at the same 612 marks, with identical results. The stale assertion count is corrected and the changelog now says which case this covers and which #116854 covers. |
CI finish ledger - ecfad69Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260904-040000 |
e5e1466
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a large performance regression, present since 26.5, for a query that filters on a column with an equality and orders by a later column of the same sorting key. Read-in-order analysis did not look through an
ALIASnode on the filter column, so the filtered column was not recognised as constant and the read was not done in order, forcing a full sort of every matching row before theLIMITapplied. This reaches a table with a normalPROJECTION, whose rewrite wraps the query filter in such an alias, and a table-levelALIAScolumn used as a predicate. #116854 separately made a base table that can serve theORDER BYitself preferred; this fixes the case where only the projection can.Description
Requested in issuecomment-5445795893 by @ fm4v. The shape reported is
SELECT ... WHERE k = 'x' ORDER BY <later key column> DESC LIMIT nover a table with a normalPROJECTIONwhose sorting key starts withk.Root cause.
appendFixedColumnsFromFilterExpressioncollects the columns a filter pins to a constant, but descends onlyFUNCTIONnodes. The projection rewrite wraps the query filter in anALIASwhen there is exactly one filter node, so the walker collects nothing, the WHERE-fixed key column is not skipped, and the read degrades toReadType: Defaultplus a full sort. The alias predates the bisected commit; #103723 only made the blindness reachable.Change. Look through
ALIASnodes in that walker. AnALIAShas the same value as its child, so it fixes the same columns: a value identity, not a heuristic.optimizeUseNormalProjection.cppalready carries this unwrap for this wrapper, andenrichFixedColumnsandaddMonotonicChainare already alias-transparent, restoring an invariant the file asserts elsewhere. Eight sibling walkers share the sameFUNCTION-only shape; none has a measured user-visible consequence, so they are out of scope.Scope. #116854 has since merged and closed #116801 by restoring read-in-order ahead of projection selection, so the issue's own fixture is now served from the base table and no longer depends on this change. What remains is the alias blindness itself: when the base key cannot serve the
ORDER BY, only the projection can, and it is read in order only once its leading key is seen through the alias. Measured below, and now what the test covers. It does not fix the second shape, added in issuecomment-5448842849, whose projection key omits a column of the table's own key and so satisfies a strictly shorter prefix; this change is a no-op there, and that missing base-table sort-order term is worked separately.Related: #116801
Validation
Measured on current master (10M rows, ~50/50 split, table keyed so only the projection can serve the
ORDER BY), one arm per server process, this change reverted for the before arm, profile events:51x fewer rows, 58x fewer bytes, 31x less CPU. Both arms select the same projection and the same 612 marks, and the returned rows are identical, so only the read order changes.
Three second-order effects. A read whose leading
ORDER BYcolumn is the filtered one loses the virtual row, since a fixed key column disables it for the whole matched prefix: no measured cost where every candidate part carries the same constant there. That guard is pre-existing; this change only widens the set of filters reaching it. Read direction can flip toInReverseOrderwhen a fixed column precedes aDESCone, reading fewer rows with results unchanged. Third, withFINALand aDESCsorting-key column, the recognised fixed key makestopKThroughJoindefer to a reverse read thatrequestReadingInOrderrejects, so neither optimization applies; rows are unchanged and that plan is what master already produces for the same predicate on the plain column.Fourteen assertions were added. Two fail without the fix, the in-order read of the projection and the table-level
ALIASpredicate; the other twelve are negative controls and results-and-order guards. The projection-step count stays 1 on both arms, so the in-order count is attributed to the projection and not to a base-table read.A backport to 26.5, 26.6 or 26.7 needs
c87e2eddfecc771first, which disables the virtual row when a key column is skipped. Absent there, latent only becauseread_in_order_use_virtual_rowdefaults to false; present on master and 26.8.#111457 reworks a different part of this file, with no textual overlap, but it interacts: it compares the virtual row on its covered sort-key prefix, which is exactly the skipped-key population this change enlarges.
Workflow [PR]
Sync PR [sync-upstream/pr/116835]