Skip to content

Do not erase the source column of a filter deferred after FINAL - #114578

Merged
yariks5s merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai-fix-deferred-filter-bare-column-after-final
Aug 26, 2026
Merged

yariks5s merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai-fix-deferred-filter-bare-column-after-final

Conversation

@groeneai

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):

Fixes THERE_IS_NO_COLUMN / NOT_FOUND_COLUMN_IN_BLOCK when a filter that runs after FINAL is a plain column reference. This affected an explicit PREWHERE b under FINAL and, with default settings, a row policy whose expression is a bare column.

Description

Closes: #114512

SELECT count() FROM t FINAL PREWHERE b threw Code: 8. Cannot find column 'b' in source stream. No SETTINGS clause is needed: apply_row_policy_after_final defaults to 1, so a row policy defers PREWHERE past FINAL.

Root cause: a filter deferred after FINAL runs in a FilterTransform built with remove_filter_column = true. When the predicate is a bare column reference, the predicate node is the DAG's own input node, so the transform erases the source column the stream carries. The existing restoreDAGInputs guard cannot help: it only re-adds an input that is not already an output, and a bare predicate is already one. A wrapped predicate (b = 1, NOT b) has a distinct result node, so erasing it leaves the input alone. Hence only the bare form failed.

The fix clears the local remove_column flag in add_deferred_filter when the filter column is one of the DAG's own inputs, which is how optimizePrewhere.cpp already resolves the same case. That lambda is shared by the deferred row policy and the deferred PREWHERE, so one change covers both.

The defect is broader than reported: a bare-column row policy with no PREWHERE anywhere in the query fails identically under default settings. That shape is in the test.

Validated in both directions on a debug build. Every shape in the issue's matrix now returns what its WHERE equivalent returns, and the new test fails on an unfixed binary. Covered: all four projections, subcolumns, a stacked policy plus PREWHERE, the four FINAL engines, and Nullable/LowCardinality/Float predicates. SELECT * stays byte-identical to the WHERE equivalent. A versioned fixture whose predicate flips across deduplication pins that the filter runs after FINAL, on the source column.

Pre-existing and unchanged here: a row policy on a bare subcolumn fails NOT_FOUND_COLUMN_IN_BLOCK on the non-deferred read path, with and without FINAL.

A filter deferred until after FINAL is executed by a FilterTransform with
remove_filter_column = true. When the predicate is a bare column reference the
predicate node is the DAG's own input node, so the transform erased the source
column the stream carries, and the query then failed with THERE_IS_NO_COLUMN or
NOT_FOUND_COLUMN_IN_BLOCK depending on whether a result projection existed.

The existing restoreDAGInputs guard does not cover that shape: it adds an input
to the outputs only when it is not already there, and a bare predicate is
already an output. A wrapped predicate such as b = 1 builds a distinct function
result node, so erasing it leaves the input alone, which is why only the bare
form failed.

Clear the remove flag when the filter column is one of the DAG's own inputs,
the same resolution optimizePrewhere.cpp already uses for a prewhere column
that is needed later. The lambda is shared by the deferred row policy and the
deferred PREWHERE, so this covers both. The row policy half is reachable with
stock default settings, because apply_row_policy_after_final defaults to 1.

Closes: ClickHouse#114512
…lumn

The regression test asserted the right values on a fixture that could not
distinguish two plausible wrong fixes. Every ReplacingMergeTree fixture had no
version column and one row per sorting key, so FINAL deduplicated nothing and a
fix that re-applied the filter before FINAL produced byte-identical output. And
because the predicate column was 0 or 1, a fix that substituted a synthesized
truth column for the real one also passed.

Add a versioned fixture whose predicate flips across the deduplication group:
one key passes only before deduplication, another only after, so the two filter
orders must disagree. The surviving value is 7, which a synthesized UInt8 truth
column cannot produce. Both halves are covered, the explicit PREWHERE and the
bare-column row policy that needs no SETTINGS clause.

Merges are stopped per table because a merge collapses the versions and removes
the flip, which would silently retire the arms.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent model reviewed this change cold against the PR contract, over two rounds. Verdicts below are mine.

Finding Verdict
⚠️ The regression test asserted the right values on a fixture where FINAL deduplicates nothing (every ReplacingMergeTree fixture had no version column and one row per key), so re-applying the bare filter before FINAL would have produced byte-identical output. Every surviving predicate value was also 1, so a synthesized truth column would have passed the SELECT * comparison. AGREE, fixed. Added a versioned fixture whose losing and winning rows carry opposite predicate values plus a truthy value other than 1, so the deferred and pre-FINAL arms now assert different results (2 vs 3) in both the PREWHERE and the row-policy half. Both mutation arms were run: the test reddens on an unfixed binary, and turning the deferral off on the fixed binary changes every new arm.
💡 Relationship line should use the full GitHub URL, and the changelog entry should be present tense per docs/changelog_entry_guidelines.md. AGREE, both applied.
💡 The test pins no enable_analyzer, unlike some sibling deferred-FINAL tests. DISAGREE. Those pin it only because they assert EXPLAIN actions=1 plan text; 03915, the result-only test of the same shape, pins nothing, and bare-subcolumn PREWHERE without a pin is existing precedent in 01475_read_subcolumns_3.sql. Neither deferral setting is CI-randomized.

A final cold pass over the second round found no blocker and no major. The new fixture depends on the two inserts landing in separate parts, which holds because wait_for_async_insert defaults to true and SYSTEM STOP MERGES is table-scoped; 03742_apply_row_policy_after_final asserts the same order-sensitive outcome untagged. The order-sensitive arms also cannot be reached by a path that filters before FINAL, since supportsBucketedRead returns false for any deferred filter.

Session id: cron:clickhouse-review-slot-9:20260813-021000

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a0f2195]

Summary: ✅


AI Review

Summary

This PR fixes a real deferred-after-FINAL filtering bug: when the predicate itself was a source column, the deferred FilterTransform erased that source column instead of a temporary filter result, which then broke both explicit PREWHERE and deferred row-policy filtering with THERE_IS_NO_COLUMN / NOT_FOUND_COLUMN_IN_BLOCK. The implementation matches the existing PREWHERE handling for the same invariant, and the added stateless test covers the important bare-column, subcolumn, stacked-policy, and SELECT * shapes. I did not find a remaining code-level correctness issue in the touched path.

Missing context / blind spots
  • ⚠️ I could not run the new stateless test locally because this workspace does not have a ready build directory/binary. The current CI artifacts I could inspect also still show the two per-arch functional bugfix-validation subresults as pending/empty, so I could not independently confirm the expected fail-on-master path from CI alone.
Final Verdict

✅ No new code-level findings in the current PR diff. The fix and regression coverage look correct; the only remaining gap is independent execution evidence for the new regression test.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · Uncovered code

Full report · Diff report

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% and single-command: SELECT count() FROM t FINAL PREWHERE b SETTINGS apply_prewhere_after_final = 1 on a ReplacingMergeTree returns Code: 8 ... only columns: [] against a WHERE b truth of 10. The same failure needs no SETTINGS clause when a row policy defers the filter.
b Root cause explained? Yes. A filter deferred after FINAL runs in a FilterTransform with remove_filter_column = true. For a bare column predicate the predicate node IS the DAG's own input node, so FilterTransform::transformHeader erases the source column the stream carries, and the pre-existing restoreDAGInputs guard is a no-op there because it only re-adds an input that is not already an output. It then fails at ReadFromMergeTree.cpp:4608 (makeConvertingActions, Code 8) or :4602 (updateHeader, Code 10).
c Fix matches root cause? Yes. add_deferred_filter clears its local remove_column when the filter column is one of the DAG's own inputs. optimizePrewhere.cpp:154-162 already resolves the identical "already an output" case the same way. No downstream guard was added.
d Test intent preserved / new tests added? Yes. New 04882_deferred_filter_after_final_bare_column, 52 value assertions against WHERE ground truths, parallel-safe with no no-parallel (verified by 8 concurrent copies, 16 of 16 green). Two mutation arms were RUN: the test fails on an unfixed binary with the predicted stack, and separately with the deferral turned off it returns different values, so the arms provably distinguish before-FINAL from after-FINAL. A versioned fixture whose predicate flips across the deduplication group carries that, and it asserts a surviving source value of 7, so neither a re-ordered filter nor a synthesized truth column can pass. The row-policy half was proven to redden separately because the runner aborts at the first failure. No existing test was weakened.
e Both directions demonstrated? Yes, on two Build-ID-verified binaries (base 25c39c9b, fix 36e05958). All 10 failing shapes of the reporter's matrix go from Code 8/10 to the value their WHERE equivalent returns; all controls unchanged.
f Fix is general across code paths? Yes. The lambda is shared by the deferred row policy and the deferred PREWHERE, so both halves are covered by one change. Nine invariant carriers dispositioned, including the sampling filter (passes a literal false), the in-read PREWHERE path, and the two MergeTreeFinalMerge engine filters, which build equals(col, literal) and so are structurally immune; verified empirically on Collapsing and Replacing(ver, del) regardless.
g Fix generalizes across inputs? Yes. Predicates measured: UInt8, Nullable, LowCardinality, LowCardinality(Nullable), Float64 and subcolumns, each matching its WHERE truth (LowCardinality(Nullable) confirmed Code 8 on base, so it is a real both-directions arm). Also all four projections, the four FINAL-capable engines, and stacked policy plus PREWHERE including the same column in both.
h Backward compatible? Yes. No setting default change, no new setting, no format or serialization change, so no SettingsChangesHistory.cpp entry. Queries that throw today start returning correct results; shapes that work today are untouched, since clearing an already-false flag is a no-op.
i Invariants and contracts preserved? Yes. The invariant is that a filter executed above the read must not erase a stream column that is also its own input. remove_column is a by-value lambda parameter used only in the FilterTransform construction, both call sites pass a copy, and addSimpleTransform invokes the getter synchronously so the added capture cannot dangle. The step's declared output header is built from the nulled in-read filters, not from the deferred copies, and SELECT * output is byte-identical to the WHERE equivalent, so no extra column escapes.

Session id: cron:clickhouse-impl-slot-5:20260812-181700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @novikd, could you review this? A filter deferred until after FINAL runs in a FilterTransform with remove_filter_column set, so when the predicate is a bare column reference the predicate node is the DAG's own input and the transform erases the source column the stream still needs; this clears that flag when the filter column is one of the DAG inputs, the way optimizePrewhere already resolves the same case.

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a0f219506 with master b05b99a64 (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
Binary Master PR Δ
programs/clickhouse-stripped 692.21 MiB 689.20 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

7 translation units recompiled, 34 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 - a0f2195

CI is fully finished on this head and there are no failures to own.

Check / test Reason Owner / fixing PR
(none) - no failed checks on this head

177 leaf jobs: 159 OK, 18 skipped, 0 failed, 0 dropped. Praktika reports this head top-level OK
with zero DROPPED jobs, and every skip carries an explicit reason (not labeled with 'pr-performance' x6, reused from cache x3, no integration tests updates x3, Not affected by the changed files and not required x2, not labeled with 'ci-toolchain' x2, and two more), so the
matrix ran rather than being dropped. The two Config Workflow / Pre Hooks and two Finish Workflow / Post Hooks FAIL rows in the CI database are from the 02:56Z and 03:32Z attempts that
preceded the can be tested label; both jobs are success on the final attempt (07:42Z, 12:07Z),
and their GitHub check conclusions are success.
Session id: cron:our-pr-ci-monitor:20260813-123000

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

This PR is a narrow correctness fix in ReadFromMergeTree that keeps a bare-column filter predicate alive in the stream when a filter is deferred until after FINAL (row policies or apply_prewhere_after_final). None of the flagged ClickBench queries (Q18, Q28, Q32) use FINAL, row policies, or after-final filtering, so they never reach the changed code. All three are already not_sure, sit within master's variance band, and show essentially flat CPU time, so the small median deltas are run-to-run variance rather than a real effect of this change.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 1062 1134 +6.7% <0.0001 This PR only changes the deferred-filter-after-FINAL path; ClickBench Q18 uses no FINAL, row policy, or apply_prewhere_after_final, and its CPU time is flat, so the +6.7% median is run-to-run variance.
⚠️ 28 not_sure 1082 1183 +9.3% <0.0001 Q28 does not exercise the changed FINAL filter code path and its CPU time barely moved (15.7s to 16.6s), so the +9.3% median is unrelated to this PR.
⚠️ 32 not_sure 1300 1369 +5.3% <0.0001 The two tests disagree and CPU time is essentially flat; Q32 does not touch the deferred-filter-after-FINAL change, so the +5.3% is borderline noise.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 7d184007-bc81-44a7-ae5a-778b99b016ba
  • MIRAI run: 6d2ced1c-5495-4e95-9c33-d967af9ab92e
  • PR check IDs:
    • clickbench_155385_1787549003
    • clickbench_155391_1787549003
    • clickbench_155401_1787549003
    • tpch_adapted_1_official_155414_1787549003
    • tpch_adapted_1_official_155428_1787549003
    • tpch_adapted_1_official_155456_1787549003

@yariks5s
yariks5s added this pull request to the merge queue Aug 26, 2026
Merged via the queue into ClickHouse:master with commit 362cbd2 Aug 26, 2026
531 of 537 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 26, 2026
alexey-milovidov added a commit that referenced this pull request Oct 11, 2026
…earch_lightweight_delete_limit`

Reading `SELECT ... FINAL PREWHERE _row_exists` with `apply_prewhere_after_final = 1`
fails with `THERE_IS_NO_COLUMN` in 26.8 regardless of the vector index (reproduced
without any index). The bug is fixed on master by
#114578, which is not in 26.8. Keep the
`EXPLAIN` check that the index is not used in this case, which is what this backport changes.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=125108&sha=76bfddc8e3fe65c82d6272e7107fb6cb46e658ca&name_0=BackportPR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29
PR: #125108

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

PREWHERE <bare column> with FINAL throws THERE_IS_NO_COLUMN when PREWHERE is deferred after FINAL

4 participants