Skip to content

Fix TopK dynamic filtering on a projection that stores _part_offset and on a column named __topKFilter(...) - #122486

Merged
PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:topk-dynamic-filter-read-column-checks
Oct 21, 2026
Merged

PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:topk-dynamic-filter-read-column-checks

Conversation

@groeneai

@groeneai groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122469
Closes: #122470
Related: #117968

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 and NOT_FOUND_COLUMN_IN_BLOCK errors in ORDER BY ... LIMIT queries with use_top_k_dynamic_filtering (enabled by default) when the query sorts by _part_offset and is served by a projection that stores _part_offset, and when the table has a column named __topKFilter(<sort column>).

Description

On 26.8.10.6 and 26.9.1.1629, at default settings, SELECT _part_offset, a, b FROM t WHERE b < 5000 ORDER BY _part_offset LIMIT 3 over a projection p (SELECT a, b, _part_offset ORDER BY b) returns wrong a (13 29827 2947 instead of 13 13 2947), and on a table with a column __topKFilter(k) the query SELECT k, `__topKFilter(k)` AS x FROM t WHERE pred = 3 ORDER BY k, x LIMIT 3 fails with NOT_FOUND_COLUMN_IN_BLOCK. Since #117968 the first query throws and the second returns 1 for that column.

Both come from installTopKDynamicFilter, which merges __topKFilter(<sort column>) into the read's PREWHERE:

  • The read of a projection that stores _part_offset produces it as _parent_part_offset, but it takes over the TopK stamp, so the filter's input is not in its block. The install now refuses when the read does not read the sort column, the check tryOptimizeTopK makes when it stamps the read. Binding the filter to _parent_part_offset is what 26.8/26.9 do, and it returns the wrong values above.
  • The generated __topKFilter(k) node was checked only against the PREWHERE DAG. The reader does not read a stored column whose name a PREWHERE step computes, so the stored __topKFilter(k) was replaced by the filter's result. The install now also refuses when the read's header has that name, as the branch without an existing PREWHERE already did.

Both are refusals, so the worst case is a missed optimization. The fix should follow #117968 to the branches it is backported to.

The new test fails on master and passes here in 50 randomized runs; removing either check turns its own section red. A separate, TopK-independent case of wrong values with a _part_offset condition, a projection and lazy materialization is not changed here.


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

Version info

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

groeneai and others added 2 commits September 26, 2026 23:02
`installTopKDynamicFilter` merges `__topKFilter(<sort column>)` into the read's PREWHERE in the
second optimization pass. It gave a wrong answer in two cases:

- A normal projection that stores `_part_offset` takes over the TopK stamp, but its read produces
  the column as `_parent_part_offset` and renames it above the read. The filter's `_part_offset`
  input is not in the read's block, so `ORDER BY _part_offset ... LIMIT` over such a projection
  threw `NOT_FOUND_COLUMN_IN_BLOCK` (ClickHouse#122469). Refuse when the read does not read the stamp's sort
  column, the predicate `tryOptimizeTopK` checks when it stamps the read. Translating the column is
  not an option: a `_parent_part_offset` condition in the projection PREWHERE together with lazy
  materialization returns wrong values, which is what 26.8 and 26.9 return for this query.
- In the merged-PREWHERE branch the generated node was only checked against the PREWHERE DAG. A
  stored column of the same name (`__topKFilter(k)`) is read after PREWHERE, and the reader does not
  read a column that a PREWHERE step already computes, so the column read back as the filter's 1s
  (ClickHouse#122470). Also refuse when the read's header has that name, as the no-PREWHERE branch does.

Both are refusals, so the worst case is a missed optimization.
State the projection-read rename as the invariant it is: only a projection that stores `_part_offset` reads it as `_parent_part_offset`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 26, 2026
@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; one full pass; 0 findings), plus my own cold review (1 nit).

# Sev Finding Verdict Evidence / action
1 💡 The test's header comment can be read as the projection sorting by _part_offset; the projection sorts by b and the query sorts by _part_offset (05259_top_k_dynamic_filter_read_columns.sql:4-6) AGREE Wording only; noted, not blocking

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-11:20260926-230900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master both issue queries fail every time: NOT_FOUND_COLUMN_IN_BLOCK for #122469, 3 1 / 13 1 / 23 1 for #122470. The new test fails 50 of 50 randomized runs on master.
b Root cause explained? #122469: the projection read takes over the TopK stamp but reads _part_offset as _parent_part_offset, so the filter's input is not in its block. #122470: the generated __topKFilter(k) node was checked only against the PREWHERE DAG; the reader does not read a stored column of that name once a PREWHERE step computes it.
c Fix matches root cause? Yes. installTopKDynamicFilter refuses in exactly those two states. Binding the filter to _parent_part_offset instead is what 26.8 and 26.9 do, and it returns wrong values there.
d Test intent preserved / new tests added? New test 05259_top_k_dynamic_filter_read_columns. Removing either check turns only its own section red.
e Both directions demonstrated? Master: 50/50 FAIL. This PR: 50/50 OK, and 100/100 OK with 16 parallel copies.
f Fix is general across code paths? Covers both install branches (with and without an existing PREWHERE). clone and the local parallel-replicas read copy the stamp onto a read with the same columns. Aggregate projections never carry it. A partial-projection union keeps the filter on the table read only.
g Fix generalizes across inputs (params/datatypes/wrappers)? Explicit PREWHERE and promoted WHERE, ASC/DESC, no WHERE, lazy materialization on/off, optimize_read_in_order 0/1, one or several PREWHERE steps, Compact/Wide parts, index_granularity 1 to 65536. Positive controls: a projection column stored under its own name and a column with another name keep the filter.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change. Refusals only, so the worst case is a missed optimization.
i Invariants and contracts preserved? Both refusals return before the PREWHERE is replaced, so the read's PREWHERE and header are unchanged. The stamp stays, as in the function's other refusals.

Session id: cron:clickhouse-impl-slot-6:20260926-222100

@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1758228]

Summary: ✅


AI Review

Summary

The PR prevents invalid TopK PREWHERE installation when a projection renames _part_offset or a stored column collides with the generated __topKFilter result. Both reported failures have focused regression coverage. No actionable findings.

Missing context / blind spots
  • ⚠️ The current head's CI is still running. Completion of the regression jobs would validate the final master merge. The test and installTopKDynamicFilter are unchanged from 87a3e1ba8c19, where the test passed 50 runs in both ARM ASan/UBSan and amd64 flaky checks. No local build or test run was performed.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 26, 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 Sep 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1f8fe49

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
AST fuzzer (amd_debug, targeted) / Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-348f) logical error from a bug already on master, not from this diff. The aborting query SELECT DISTINCT b, a, _part_offset FROM merge(currentDatabase(), '^t_topk_part_offset__fuzz_0$') WHERE b < 5000 LIMIT 3 has no ORDER BY, so installTopKDynamicFilter, the only function this PR changes, never runs. A minimal repro with no TopK setting aborts the same way on master: ReadFromMerge asks its child to read in the table's sorting-key order (a), and the child then reads projection p, which is sorted by b. The targeted fuzzer reached it through the tables of this PR's new test. In the last 30 days the same STID failed on 14 other PRs a fix task is created (the fix is in progress, fixing-PR link to follow here)
PR rollup, red only because of the row above a fix task is created (the same one as for the row above)

All 169 check runs completed (129 pass, 39 not selected, 1 red), Finish Workflow and
Mergeable Check are green, and CH Inc sync passed. CIDB has one FAIL test row on this
head, the row above.

Session id: cron:our-pr-ci-monitor:20260927-090146

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer (amd_debug, targeted) 'Equal values are not contiguous' (STID: 2508-348f) row of the ledger above: #122520

@PedroTadim PedroTadim self-assigned this Oct 8, 2026
# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeTopK.cpp
@PedroTadim PedroTadim removed their assignment Oct 9, 2026
@PedroTadim

Copy link
Copy Markdown
Member

#122520 should be merged first

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

Agreed. The AST fuzzer (amd_debug, targeted) failure on your merge commit is STID 2508-348f again, which #122520 fixes. Your conflict resolution looks right to me: 05259_top_k_dynamic_filter_read_columns passed in every job that ran it, including the 50x flaky checks. Once #122520 is merged, I'll merge master here so CI picks up the fix.

@PedroTadim
PedroTadim added this pull request to the merge queue Oct 21, 2026
Merged via the queue into ClickHouse:master with commit b00ad43 Oct 21, 2026
179 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 21, 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 #122486 to 26.10: Fix TopK dynamic filtering on a projection that stores `_part_offset` and on a column named `__topKFilter(...)`
leshikus pushed a commit that referenced this pull request Nov 13, 2026
… that stores `_part_offset` and on a column named `__topKFilter(...)`
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-review-bot PR origin: review-bot finding on a groeneai PR 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Collision guard checks the and name, not the __topKFilter(k) step column TopK filter reads _part_offset on a projection read that renamed it

5 participants