Skip to content

Look through an alias on the filter column in read-in-order analysis - #116835

Merged
Michicosun merged 8 commits into
ClickHouse:masterfrom
groeneai:read-in-order-alias-on-filter-column
Sep 4, 2026
Merged

Michicosun merged 8 commits into
ClickHouse:masterfrom
groeneai:read-in-order-alias-on-filter-column

Conversation

@groeneai

@groeneai groeneai commented Aug 28, 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):

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 ALIAS node 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 the LIMIT applied. This reaches a table with a normal PROJECTION, whose rewrite wraps the query filter in such an alias, and a table-level ALIAS column used as a predicate. #116854 separately made a base table that can serve the ORDER BY itself 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 n over a table with a normal PROJECTION whose sorting key starts with k.

Root cause. appendFixedColumnsFromFilterExpression collects the columns a filter pins to a constant, but descends only FUNCTION nodes. The projection rewrite wraps the query filter in an ALIAS when there is exactly one filter node, so the walker collects nothing, the WHERE-fixed key column is not skipped, and the read degrades to ReadType: Default plus a full sort. The alias predates the bisected commit; #103723 only made the blindness reachable.

Change. Look through ALIAS nodes in that walker. An ALIAS has the same value as its child, so it fixes the same columns: a value identity, not a heuristic. optimizeUseNormalProjection.cpp already carries this unwrap for this wrapper, and enrichFixedColumns and addMonotonicChain are already alias-transparent, restoring an invariant the file asserts elsewhere. Eight sibling walkers share the same FUNCTION-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:

rows read bytes read CPU duration
before 5,021,696 100,134,928 316,386 us 46 ms
after 98,304 1,712,208 10,309 us 5 ms

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 BY column 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 to InReverseOrder when a fixed column precedes a DESC one, reading fewer rows with results unchanged. Third, with FINAL and a DESC sorting-key column, the recognised fixed key makes topKThroughJoin defer to a reverse read that requestReadingInOrder rejects, 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 ALIAS predicate; 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 c87e2eddfecc771 first, which disables the virtual row when a key column is skipped. Absent there, latent only because read_in_order_use_virtual_row defaults 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]

groeneai and others added 2 commits August 28, 2026 05:47
`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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent model re-reviewed this change cold against the diff and the plan.

  • ✅ No blocking or major findings on the code. The unwrap was checked for soundness in the widening
    direction (every node the walker pops must be truthy for a row to pass the filter, and an ALIAS
    is value-identical to its child), for termination, and against all three call sites, both order
    builders and the two consumers of wouldReadInOrderBeUseful.
  • ⚠️ Scope was corrected before publication: the second shape reported on the issue is a different
    root cause and this change is a no-op for it, so this PR is Related: rather than Closes:. It is
    tracked separately.
  • 💡 The regression test was moved into its own file rather than appended to an existing one, and one
    results-equality assertion was added for the aliased-filter-column case.

@clickhouse-gh clickhouse-gh Bot closed this Aug 28, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ecfad69]

Summary: ✅


AI Review

Summary

This PR makes appendFixedColumnsFromFilterExpression alias-transparent so read-in-order analysis still recognizes fixed key columns when the filter DAG is wrapped in an ALIAS, and it updates 05045 so the regression remains covered after #116854 changed the old fixture's plan shape. I rechecked the current diff, the touched code paths, and every existing review thread, and I did not find any new blocker, major, or metadata issue that still holds in the current code.

Final Verdict

✅ No new review findings.

LLVM Coverage Report

⚠️ No coverage measurement for commit ecfad69: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_7.profdata.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @CurtizJ, could you review this? Read-in-order analysis descends only FUNCTION nodes when collecting the columns a filter pins to a constant, so an ALIAS on the filter column stops the walk and the WHERE-fixed leading sorting key is never skipped; the projection rewrite wraps a single-predicate filter in exactly such an alias, so the projection read lost read-in-order and fell back to a full sort before the LIMIT applied.

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ecfad6966 with master e903c5a56 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 17 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a71843f

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

Read the per-run columns, not the rollup. clickhouse-gh[bot] closed this PR at 07:40:04Z and
reopened it at 07:40:06Z, so two full PR workflow runs exist at this one commit
(33152308605 created 07:40:00Z, 33152317881 created 07:40:08Z, 175 checks each, 358 check-runs
at the head, Finish Workflow and ~150 other names duplicated). Both completed; neither was
cancelled. Every red below has a same-tree PASS in the sibling run, which is a free control for
"state or timing dependent, not tree dependent".

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Cannot start clickhouse-server Alias table cannot refer to another Alias table while loading test_1.outer_alias_to_inner_alias__fuzz_4, i.e. the StorageAlias alias-chain trunk bug (45 PRs + 5 master hits in 30d). Failed in run 33152317881, passed in 33152308605 #116153 (ours, open)
Stateless tests (amd_binary, flaky check) job-level ERROR 8 seconds in, before any test ran: the praktika pre-run step could not download build_amd_binary/clickhouse and died with S3 PreconditionFailed / S3DownloadFailedError, which the log itself reports as Failed to do a job pre-run step, it is praktika bug or misconfiguration. The two concurrent runs race the same per-sha S3 keys #116701 (ours, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) 3 FAILED/ERROR lines emitted at a single instant with no pytest failure section and no assertion text, across unrelated tests, i.e. a teardown cascade in the losing run. The same job is green at the identical tree in run 33152317881 #116701 (ours, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

Not a red: request-reviews-fork shows one cancelled and one skipped instance, a
concurrency-superseded duplicate of the Documentation Team Review Requests automation (6 such
runs exist at this commit). It tests no code and produces no CIDB rows.

On the flaky check specifically, since a flaky-check failure normally means a bad new test: it is
not one here. The changed test 05045_read_in_order_normal_projection_fixed_key ran the full
--test-runs 50 in the sibling run and passed 50/50, 0 skipped, zero FAIL lines. The red
attempt executed no test at all.

Session id: cron:our-pr-ci-monitor:20260828-123000

Comment on lines +191 to +193
/// 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();

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.

Can't we reuse the outer stack loop? Something like:

Suggested change
/// 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());

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@Michicosun Michicosun self-assigned this Aug 28, 2026
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4aba48e

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

One PR workflow run at this commit (153 distinct check runs, 290,201 CIDB rows, exactly 2 FAIL),
so unlike the previous head there is no duplicate-run ambiguity: the rollup and the per-run columns
agree.

Check / test Reason Owner / fixing PR
Stress test (arm_release) / Logical error: 'Not-ready Set is passed as the second argument for function 'globalNotIn'' (STID 0250-3e49) Chronic trunk logical error in set readiness, not caused by this PR. 38 hits on master and release branches plus roughly 50 unrelated pull requests over 30 days, across Stress test, AST fuzzer and BuzzHouse on every sanitizer. Two true-master hits landed today on this same check name, ea30edba1ba6 at 19:14Z and 6ea4e96d02cc at 20:00Z, either side of this run. This PR's diff is a two-line alias unwrap in optimizeReadInOrder.cpp and does not touch set building #102308 (external, open as draft)
AST fuzzer (amd_debug, targeted) / Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID 2508-36d8) Not caused by this PR, and this is a discriminator rather than a breadth argument, because a sorted-range assertion is a plausible consequence of a read-in-order change: the fuzzed query pins SETTINGS optimize_read_in_order = 0 in both EXCEPT branches, so the code path this PR changes is switched off in the failing query. The abort is the chronic family site checkEqualRangeEndAssumeSorted, reached through SELECT DISTINCT a, c FROM merge(currentDatabase(), '^mt_fixed_key$') ... ORDER BY c DESC. The owner PR stops sorting being pushed into Merge children across an order-breaking cast, which is exactly that shape #113242 (ours, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

Reports:

Mergeable Check and PR are red only as rollups of the two owned failures above. Everything else
at this commit is green: Config Workflow, Style check, Fast test, Fast test (arm_darwin) and
Finish Workflow all pass. The 4 unstable rows are per-query Performance Comparison verdicts on
a passing job.

The fixture table mt_fixed_key that the fuzzer mutated is created by this PR's own new test, which
explains why the fuzzer reached this shape here. That is reachability, not causation, and the mutated
query disables the changed path anyway.

Session id: cron:our-pr-ci-monitor:20260828-220000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger: a6838f1

Every failure below has an owner: a fixing PR (ours 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
AST fuzzer (amd_release, oracle) / TLP Aggregate oracle mismatch real wrong result, not this diff: a bare count() over a STREAM BOUNDED CURSOR read is answered from part metadata and reports the whole table, while the oracle's three WHERE-carrying partitions honour the cursor and sum to the bounded number #117188 (ours, open)

The mismatch is a true positive, not an oracle artifact: the gate is
canUseProjectionForReadingStep, which declines FINAL and SAMPLE but never tested for a
streaming read. #117188 adds the missing isStream() guard and records the same mismatch on two
other unrelated diffs, which places it on master rather than in any of the three.

This diff touches optimizeReadInOrder.cpp only, and that pass already carries the isStream()
guard #117188 cites as its model. count() with no ORDER BY does not use read-in-order.

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)

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.

add else if here

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - dc130c51b042857ce21f45ecd51364315a04b99e

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 (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

@Michicosun
Michicosun enabled auto-merge September 3, 2026 16:02
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.
auto-merge was automatically disabled September 3, 2026 19:30

Head branch was pushed to by a user without write access

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed two commits after the master merge, both test-only.

Fast test reddened on this PR's own test. The first block of 05045 pinned a plan that #116854 changed: that fixture keys the table on (c, b), which serves ORDER BY c DESC by itself, so with read-in-order restored ahead of projection selection the query now reads the base table and the projection is not selected. Measured on this tree against the same tree with this PR's src hunk reverted, the block is 1/0/1/1 on both arms, so it no longer shows anything this PR does. The first commit updates the reference to the plan master now produces.

The second commit adds mt_proj_only, keyed on a so the projection is the only read that can serve ORDER BY c. There ReadType: InOrder is 1 with the alias unwrap and 0 without it, while the projection step stays 1 on both arms, so the count is attributed to the projection and not to a base-table read. Two of the fourteen assertions now fail without the unwrap, this one and the table-level ALIAS one. 50 of 50 runs pass at --jobs 8.

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.

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ecfad69

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
Stress test (arm_release) / Logical error: Coordination mode mismatch for stream A: got B, expected C (STID 7334-5b92) pre-existing trunk parallel-replicas coordination defect, not this diff: under query_plan_optimize_join_order_randomize = 1 each plan of one query rolled its own seed, so replicas pick a different leftmost relation, a different table receives requestReadingInOrder, and the second announcement for one stream carries a different CoordinationMode. 32 unrelated PRs over 45 days, first seen 2026-07-23, weeks before this branch #112660 (mine, open)

Session id: cron:our-pr-ci-monitor:20260904-040000

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
@Michicosun
Michicosun enabled auto-merge September 4, 2026 14:09
@Michicosun
Michicosun added this pull request to the merge queue Sep 4, 2026
Merged via the queue into ClickHouse:master with commit e5e1466 Sep 4, 2026
512 of 515 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 4, 2026
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... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Projection selection ignores base-table read_in_order + LIMIT benefit, causing large regressions since 26.5

4 participants