Skip to content

Fix wrong results with query_plan_optimize_lazy_final and a filter applied before FINAL - #112526

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-lazy-final-pre-final-row-filter
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-lazy-final-pre-final-row-filter

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 wrong results (silently missing rows, including a count() of 0) for a ReplacingMergeTree FINAL query with query_plan_optimize_lazy_final = 1 and a row-level filter or PREWHERE applied before the FINAL merge. The lazy-FINAL replacement selected each key's winner over unfiltered rows, so a key whose highest-versioned row failed the filter produced no row instead of the highest-versioned row satisfying it. Reachable with apply_row_policy_after_final = 0, and with an explicit PREWHERE at default settings.

Description

Related: #112332 (report), #106734 (exposed it)

ReadFromMergeTree::deferFiltersAfterFinalIfNeeded decides which side of the FINAL merge a filter runs on. A deferred filter is re-applied above the merge (apply_row_policy_after_final = 1, the default). A non-deferred filter is applied while reading, so it changes which rows participate in deduplication: apply_row_policy_after_final = 0, and the default for an explicit PREWHERE. Both orderings are valid.

optimizeLazyFinal ignored the distinction and re-applied both filters as FilterSteps above JoinLazyColumnsStep, i.e. always after the merge. The Aggregating step inside LazyReadReplacingFinal picks each key's winner with argMax(..., version) over the unfiltered part contents, and that outer filter then discards the winner, so such a key returned nothing.

This applies a non-deferred filter to the winner-selection read itself, so the lazy path computes the same winner the real FINAL merge would. The optimization stays enabled rather than being switched off, which the new test asserts both through EXPLAIN and through a server-side trace proving the lazy branch really executed: disabling it would be a silent perf regression.

The discriminator is getDeferredRowLevelFilter() / getDeferredPrewhereInfo(), not the filter's presence in query_info, because deferral only records the filters. A presence-based test would misclassify a default deferred row policy and push it below winner selection, which is worse than the bug fixed here.

Blast radius: only ReplacingMergeTree FINAL with query_plan_optimize_lazy_final = 1 and a non-deferred filter, which return wrong results today, so every behaviour change is a fix. No new setting, no default or serialization change.

Further detail: carriers, filter ownership, the guards
  • additional_table_filters and lightweight DELETE (_row_exists) are not carriers, contrary to the report; the second carrier besides row policies is PREWHERE. query_plan_optimize_lazy_final seems to be break partition pruning #106810 and 04359_distributed_final_modifiers are distinct defects.
  • The filters are owned clones, because getQueryInfo() shares them with the false branch's FINAL read. cloneFilterSubDAG exposes every predicate input as a pass-through output, so the DAG cannot erase the sorting-key, version or is_deleted columns the aggregation reads. The test covers a filter on is_deleted itself and on a sorting-key column.
  • The push-in adds one predicate evaluation on the winner-selection read, so it is admitted only for a predicate that is neither nondeterministic nor stateful (hasNonDeterministic() / hasStatefulFunctions()); otherwise the query keeps the ordinary FINAL read. Repeated evaluation in the lazy plan is pre-existing on master. Make logTrace not suitable for constant folding #110188 addresses the stateful half more broadly; I can drop this guard in favour of it if it lands first.
  • The deferral accessors are populated only once the deferral pass has run, so the optimization leaves the automatic-parallel-replicas candidate plan (built with query_plan_optimize_primary_key = false) untouched. That precondition is fail-closed, not a live path: supportsDataflowStatisticsCollection() is !isQueryWithFinal(), so a FINAL read fails the statistics walk in considerEnablingParallelReplicas and the candidate is never built for a query this optimization applies to.
  • The post-merge FilterStep is kept: it recomputes the predicate from columns re-read by LazilyReadFromMergeTree, and optimizePrewhere retains a derived predicate column when a residual WHERE consumes it, which 04493_lazy_final_prewhere_derived_filter_column exercises. The two lazy_final_* performance tests carry neither filter and take the unchanged path.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: 10 rounds, 52 findings, all resolved before publication

Before opening this PR I ran it through an independent internal review harness: each round is a cold
code review plus a separate second-model gate, adjudicated against measured evidence rather than
prose. 52 findings over 10 rounds: 44 AGREED and fixed, 1 DISAGREED with evidence, 7 dropped as
already-resolved or no-action. The final round found nothing. The reviewer never edits source, so
every fix below was implemented and re-measured separately. An approach gate ran first, before any
code: 7 rounds, 14 findings, the last returning clean.

Findings that changed the fix itself

finding verdict resolution
❌ A prescribed early return landed mid-partial-split. trySplitNonIntersectingParts has three outcomes, and the partial-split one returns after already narrowing the read (analyzed_result->parts_with_ranges = std::move(split.intersecting_parts_ranges), then setAnalyzedResult) while holding the non-intersecting half in a local whose only consumer is the later UnionStep. Returning there drops that half. AGREE The prescription was withdrawn in writing and replaced: the boolean fully_replaced became a 3-valued SplitResult::Outcome (PlanReplaced / DeclinedLeaveUntouched / BuildLazyBranch), defaulting to declining so an unnamed outcome fails closed, with the caller testing for the one outcome that continues rather than against the ones that stop.
❌ With the eligibility gate placed as prescribed, three bare return {} sites above it yielded "carry on" while the winner-selection filter bundle did not exist, so the caller reached std::move(*pre_final_filters) on a nullopt: a plan-time abort on ordinary tables (Float/Nullable keys, mixed-direction sorting keys). Introduced, not pre-existing: 6 fatal lines on that build, 0 on master. AGREE Withdrawn in full. All nine return sites were tabulated and mapped explicitly onto the three outcomes, and the gate moved to dominate exactly the sites that build the branch. A defensive if (!pre_final_filters) return; was explicitly rejected: it would have silently reinstated the lost fast path for the declining shapes, recreating the regression the item existed to remove.
❌ The two "the part splitter cannot analyse this key" returns bypassed both later preconditions (text-index read tasks, read-in-order), so an unsafe-key query could build the lazy branch where the ordinary path declines. AGREE Both returns now re-test the same three conditions the ordinary path honours. Those shapes turned out to be carriers of this PR's own defect in their own right: on master they returned [2.5] where [1.5,2.5] is correct.
⚠️ The guards ran after the all-non-intersecting fast path had already been given up, so an unavailable lazy branch cost that replacement too. AGREE The availability check moved above the narrowing, and EXPLAIN actions = 1 arms now assert FINAL: 1 is absent for the replaced read, with a declining query as the negative control.
⚠️ The re-applied filters' required inputs could be consumed away by the filter's own DAG. AGREE Both filters are cloned through cloneFilterSubDAG, which exposes every predicate input as a pass-through output, and the remove-column flags are cleared when the predicate column is itself one the aggregation reads. A bare-required-column arm covers both filter kinds.

Findings that changed how the fix is tested

finding verdict resolution
❌ Every plan-shape assertion silently changes answer under the old analyzer, since optimize_lazy_final is query_plan_optimize_lazy_final && allow_experimental_analyzer. Reachable both by the dedicated old-analyzer job and by stress compatibility randomization. Found independently by the cold review and by the gate in the same round. AGREE A session --enable_analyzer=1 pin, chosen over a no-old-analyzer tag because applyCompatibilitySetting skips manually-changed settings, so one pin covers both routes. Load-bearing: without it 67 of 78 reference rows move.
⚠️ The "the lazy branch executed" assertion grepped a trace emitted one statement upstream of the signal that selects the branch. A mutation resetting that signal left the whole test green with zero rows moved, while the branch provably stopped running (SelectedMarksTotal 24 to 12). AGREE Re-keyed onto the true-branch-only LazyMaterializingTransform trace, which has a single emitter in the tree. The same mutation now reddens exactly the three positive execution arms and leaves the negative control at 0.
⚠️ Result-only arms cannot see a runtime fallback to the ordinary FINAL read: the false branch is the correct path, so every comparison stays equal and every EXPLAIN row unchanged. AGREE Runtime execution arms added, with a negative control so a helper that always reported "enabled" would fail them.
⚠️ Blanket no-random-settings / no-random-merge-tree-settings tags suppressed randomization wholesale instead of pinning the settings that matter. AGREE Both tags dropped; only the settings each arm depends on are pinned per statement, then 50 randomized plus 50 non-randomized runs re-measured. This paid off immediately: the randomized arm failed 20 of 50 on a single row, isolating a real second gating setting (use_skip_indexes_if_final, whose 0 draw returns from index analysis before any index is collected) now pinned on the two arms that need it.
⚠️ Several oracles were vacuous: a combined row-policy plus PREWHERE arm whose predicate never removed a row; a deferred-PREWHERE discriminator with no deferred PREWHERE case; an unsafe-PREWHERE safety check no arm reached; a parallel-replicas arm that was dead because the fixture's plan cannot reach that path. AGREE Each was rebuilt to be killed by a mutation, or removed and replaced by a documented statement of the invariant. Every assertion in the shipped test is killed by at least one of fourteen recorded mutations.
⚠️ A three-way conjunct was covered only in its middle term: deleting the text-index term left the entire test tree green. AGREE A Float64-key-plus-text-index fixture closes it. Deleting the term now moves the arm and turns its result comparison into [] against the ordinary FINAL read's two rows, so the missing term reproduces this PR's own wrong-results symptom.

Not accepted, and noted

finding verdict reasoning
💡 PREWHERE k on a bare sorting-key column raises NOT_FOUND_COLUMN_IN_BLOCK under this optimization. DISAGREE (pre-existing, out of scope) Reproduces identically on the master snapshot, so it predates this PR and is not its contract. Tracked separately.
💡 An earlier commit message describes as a follow-up something a later round actually closed. Noted, no action .claude/CLAUDE.md forbids amend and rebase, and the later commit message states what closed it, which is the sanctioned remedy.
💡 Whether the prewhere-promotion pins were load-bearing. Noted, no action Measured inert three independent ways and structurally explained, so they were dropped rather than kept defensively.

Final round: the cold review raised 4 items (test tagging, arm liveness, pin scope, comment accuracy)
and each resolved to no-action on verification; the gate returned 0 findings.

Session id: cron:clickhouse-review-slot-53:20260730-023800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A 3-key ReplacingMergeTree(version) ORDER BY k, index_granularity = 1, 6 single-row parts, SYSTEM STOP MERGES. SELECT arraySort(groupArray(k)) FROM t FINAL SETTINGS apply_row_policy_after_final = 0, query_plan_optimize_lazy_final = 1, min_filtered_ratio_for_lazy_final = 0.0 returns [2] where [1,2] is required; the count() form returns 1 instead of 2. Reproduces on every run, on master's own debug build. SETTINGS must be at top level and there must be no ORDER BY (it disables the optimization via readsInOrder), and the parts must stay unmerged. The two ORDER BY arms added this round are the converse case and are asserted on the PLAN, not the rows: for an unanalysable key the lazy plan was built (1 before, 0 after) while the results were equal both ways, so losing the order guarantee is invisible in the fixture's output.
b Root cause explained? optimizeLazyFinal re-applies query_info.row_level_filter / query_info.prewhere_info as FilterSteps above JoinLazyColumnsStep, i.e. always after the merge, and never consults the deferral decision. The Aggregating step inside LazyReadReplacingFinal picks each key's winner with argMax(..., version) over the unfiltered part contents, so for a key whose highest-versioned row fails a filter that should run before the merge, that winner is chosen and then discarded, and the key yields no row instead of the highest-versioned row that satisfies the filter. Measured discriminator: deferred (post-FINAL) is correct, non-deferred (pre-FINAL) is wrong.
c Fix matches root cause? Yes. The non-deferred filter is applied to the winner-selection read's input, which is where the lazy path's deduplication happens, so the argMax sees exactly the row set the real FINAL merge would. Not a band-aid: disabling the optimization for these queries was implemented as a mutation and rejected, because it silently loses the optimization while looking correct. The eligibility decision is expressed as an explicit three-valued SplitResult::Outcome (PlanReplaced / DeclinedLeaveUntouched / BuildLazyBranch) rather than a boolean, because the previous boolean conflated "stop, the read must be left alone" with "carry on" across nine return sites; a gate keyed on it has to be placed at one line, and every line splits that group wrongly. The enum defaults to declining, so a return that names no outcome fails closed.
d Test intent preserved / new tests added? No existing test was weakened, removed or re-referenced. The reference diff for this round is +5 / -0 lines, all of them new rows at one insertion point, with every pre-existing row byte-identical (verified under full randomization). New .sh test 04652_lazy_final_pre_final_row_filter with 75 assertion arms over 75 label-headed reference rows (counting rule: one row per arm, each beginning with the arm's label; the 91-line reference additionally holds 10 echo section headers, 4 continuation lines from the two multi-row ORDER BY arms and 2 bare part-count rows): 33 paired lazy-ON/OFF result comparisons, 29 EXPLAIN checks of whether LazyReadReplacingFinal is still built, 4 runtime checks of whether the lazy branch actually EXECUTED, 5 plan-shape checks (InputSelector, Union, NonIntersectingSplit, the direct-read marker), 3 EXPLAIN actions = 1 checks of whether the read still carries FINAL, and the ratio_default row. Every assertion is killed by at least one mutation. Thirteen mutations across the last six rounds, each restored with the source verified byte-identical afterwards: reconstruct the conflated-boolean shape; delete the eligibility gate; force the gate always-open; fold the all-intersecting return into the decline group; drop the required-column guard from the prewhere consumer; drop it from the row-level consumer; drop the pinned optimize_on_insert; revert the two cannot-analyse sites to an unconditional decline; drop their gate so they always build the lazy branch; make createNonIntersectingPlan leave FINAL set; reset the lazy-branch signal after both trace branches of work(), which is the mutation that exposed the runtime assertion as blind; and revert only the unanalysable-key gate added in the previous round, which reddens exactly its two plan-shape rows; and delete the text-index term from that gate's three-way conjunct, which reddens the text-index arms added this round and turns their result comparison into [] against the ordinary FINAL read's two rows. Three of those mutations had to be re-expressed because their literal spelling is rejected by the compiler (-Wunused-variable, -Wunreachable-code, -Wlogical-op-parentheses); each replacement is a runtime-opaque predicate inversion that compiles, moves the Build ID and reproduces the same verdict, since a compiler rejection is not a passed mutation.
e Both directions demonstrated? Yes. Against master's debug build (/worktrees/snapshots/master-debug-build, whose optimizeLazyFinal.cpp is md5-identical to origin/master) the sorting-key carrier arms and the three partial-split arms all return wrong results where this build returns correct ones ([2.5] vs [1.5,2.5], [2] vs [1,2], [2,10] vs [1,2,10]), while every control arm and the retained-fast-path arms are identical between master and this build. This round established that the three unsafe-key tables are carriers with a safe predicate too, not only with an unsafe one: on master all six of those arms differ from the ordinary FINAL read and all six build the lazy branch, because neither cannot-analyse return consulted the filter bundle. Per-mutation: reconstructing the conflated boolean reproduces a plan-time abort on the carrier arms (6 fatal lines on that build, 0 on the shipped one); folding the all-intersecting return into the decline group reddens 13 arms with all results still correct; forcing the gate always-open reddens the three nondeterministic/stateful arms; dropping the row-level required-column guard reddens exactly one arm and only it; dropping the pinned optimize_on_insert reddens exactly the three plan-shape rows. This round: reverting the two cannot-analyse sites to an unconditional decline reddens exactly the three new safe-predicate arms and nothing else; dropping their gate reddens the three unsafe arms and lands on the same plan-time abort (Logical error: 'pre_final_filters.has_value()'); making createNonIntersectingPlan leave FINAL set reddens exactly the two FINAL-absent arms; and folding the all-intersecting return into the decline group still reddens exactly its 13 arms, so the outcome partition was not weakened. 50/50 with randomization and 50/50 without, both clean, 0 fatals. The sibling suite was compared as an A/B against a merge-base rebuild over an identical 106-test selection (absolute counts are meaningless in a sandbox with no ZooKeeper, no named clusters and no system.query_log): 30 failures with the fix vs 35 on the baseline, 27 shared, and each of the 3 only-in-fix rows fails with Code: 701 CLUSTER_DOESNT_EXIST on the baseline binary too when re-run three times, so there are no attributable regressions. This round closed a gap in the runtime assertion itself: it had grepped a trace emitted one statement before the signal that selects the branch, so a mutation resetting that signal left the whole test green with zero rows moved. Keyed on the true-branch-only LazyMaterializingTransform trace instead, the same mutation reddens exactly the three positive execution arms (1 -> 0) and leaves the negative control at 0, with the reference byte-identical. The four earlier mutations keep their discriminating sets; three of their row counts grow by one, each time because the new assertion notices the branch no longer executing for exactly the table that mutation targets. Re-ran 50/50 both ways on the final file: 50 passed under randomization and 50 passed with randomization disabled, 0 fatals each, plus 20/20 randomized. This round added the read-in-order half of the unanalysable-key story and measured it in both directions: the lazy plan was built for SELECT k FROM t_float FINAL PREWHERE flag = 0 ORDER BY k and its mixed-reverse mirror before the fix and is not after it, while the results are equal either way (which is why those two arms assert the plan rather than the rows), and reverting only that hunk reddens exactly those two rows. The existing matrix was re-run against the final tree with its discriminating sets unchanged: m-r5-1 4 rows and m-r5-3 2 rows byte-identical to the previous round, m-r5-2 51 rows with the same Logical error: 'pre_final_filters.has_value()' abort (43 previously, plus the 8 new reference lines), m-r4-4 14 rows, and m-r7-1 still exactly the three execution arms with the negative control untouched. All twelve lazy-FINAL family tests are green, and 50/50 both ways was re-measured on the shipped content: 50 passed / 0 fatal randomized (with no suppression tags at all) and 50 passed / 0 fatal with randomization disabled. This round closed the last uncovered term of that gate. The gate is a three-way conjunct and the two arms added previously vary only its middle term, so deleting the text-index term left every test in the tree green - measured. The new unsafe-key-plus-text-index fixture fixes that: with the term deleted the arm goes 0 -> 1 and its result comparison goes [3.5,4.5] same to [] DIFFERENT, i.e. the missing term reproduces this fix's own wrong-results symptom rather than merely a plan-shape change, while the two earlier arms stay at 0. A positive pin asserts the direct read's synthetic column is present, so the declining 0 cannot be confused with a query that never rewrote a text predicate, and a control arm without the token search shows the same table still builds the lazy branch. Full randomization then exposed one further genuine dependency: use_skip_indexes_if_final is randomized 0/1, and at 0 a FINAL query's index analysis returns before collecting any index, so no read task is registered and the branch legitimately builds - 20 of 50 runs, one row, isolated one axis at a time over eight skip-index settings and pinned per statement on the new arms only, verified load-bearing against a hostile client option. The existing matrix was re-run: m-r5-3 2 rows, m-r4-4 14 rows and m-r7-1 3 rows byte-identical; m-r5-2 56 rows with the same abort signature (51 previously plus the 5 new reference lines); and m-r8-1/m-r5-1 grew into strict supersets, both because their mutations target the very term the new arms cover. No discriminating set shrank. 50/50 both ways re-measured on the final content: 50 passed / 0 fatal randomized, 50 passed / 0 fatal with randomization disabled.
f Fix is general across code paths? optimizeLazyFinal has exactly two call sites, both in optimizeTree.cpp, and is gated on MergingParams::Replacing over the generic MergeTreeData, so there is no separate Replicated/Shared entry point to mirror. trySplitNonIntersectingParts has exactly one caller (grep -rn 'trySplitNonIntersectingParts' src/ gives the declaration, that call site, and nothing else), so the outcome type has no other consumer. All nine of its return sites were classified explicitly rather than relying on a default, and the caller tests for the one outcome that continues (!= BuildLazyBranch) instead of listing the ones that stop, so a future fourth outcome keeps the ordinary FINAL read rather than falling into the lazy branch. Both halves of the deferral discriminator (row-level filter and prewhere) and both invocations of the safety check have their own arms; both consumers of the required-column containment check are exercised. Fixed at the source (winner selection) rather than guarded at the symptom.
g Fix generalizes across inputs (params/datatypes/wrappers)? Covered and asserted: row policy, explicit PREWHERE, PREWHERE promoted by optimize_move_to_prewhere_if_final, row policy and PREWHERE together, deferred row policy, deferred PREWHERE, ReplacingMergeTree(version, is_deleted), a filter on is_deleted itself, a filter on a sorting-key-only column, a bare required-column predicate in both filter kinds, nondeterministic predicates in both a row policy and an explicit PREWHERE, deterministic-but-stateful and throwing predicates, the count() form, and the min_filtered_ratio_for_lazy_final default. Sorting-key shapes: plain UInt64, Float64, Nullable(UInt64) and a mixed (a ASC, b DESC) reverse key. The last three are the ones the part splitter cannot analyse, so it returns before inspecting parts; each now has BOTH an unsafe-predicate arm (the two conditions coincide, and the read must be left alone) and a safe-predicate arm (the lazy branch is still built, and the filter must reach it); the safe arms are carriers in their own right. Part layouts: all-intersecting, all-non-intersecting (the fast path, asserted to survive an unavailable lazy branch) and a genuine partial split (asserted structurally via Union and NonIntersectingSplit so it cannot silently stop being one). additional_table_filters and lightweight DELETE were measured and are not carriers. Each unanalysable-key table now also has a read-in-order arm, which is the shape whose order guarantee the lazy replacement cannot honour, and one carries a text index as well: a direct read from a text index is the third condition those returns re-test, and it is reachable on an unsafe key because the direct-read rewrite has no key-safety gate of its own, so an unsafe-key table registers index read tasks exactly like a safe one. This round the test also stopped suppressing randomization wholesale: the blanket no-random-settings / no-random-merge-tree-settings tags are gone, so the arms are now exercised against 223 randomized settings plus the merge-tree randomizer, which is what surfaced the genuine dependencies: optimize_read_in_order (randomized at p=0.5), pinned per statement on the four arms that need it, and use_skip_indexes_if_final (randomized 0/1), pinned per statement on the text-index arms alongside query_plan_direct_read_from_text_index because either one being off suppresses the direct read the arms exist to observe. Two prewhere pins were tried and then dropped after measurement: forcing both switches off, individually and together and on both sides of every comparison, is byte-identical, because for a FINAL query the WHERE-to-PREWHERE promotion additionally requires optimize_move_to_prewhere_if_final (default false, deliberately not randomized), 31 arms use an explicit PREWHERE, and every comparison applies the same settings to both of its sides.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting, no default change, no serialization or format change; the diff touches neither Settings.cpp nor SettingsChangesHistory.cpp. Affected queries change from returning wrong (missing) rows to returning correct rows, which is the intended user-visible fix.
i Invariants and contracts preserved? The synthetic read is constructed non-FINAL, so deferFiltersAfterFinalIfNeeded returns immediately on it and cannot re-defer the filter just attached. cloneFilterSubDAG exposes every predicate input as a pass-through output, so the header derived through MergeTreeSelectProcessor::transformHeader keeps the sorting-key, version and is_deleted columns the aggregation consumes; do_remove_column / remove_prewhere_column are additionally forced off when the predicate column is one of those. The filters are owned clones, so the false branch's own FINAL read is untouched. New this round: the eligibility gate sits ABOVE the block that narrows analyzed_result to the intersecting parts, so a declined split never leaves a half-mutated reading step observable; declining after the narrowing was implemented and rejected for exactly that reason. Control reaches the winner-selection step only on BuildLazyBranch, and every return of it is either below the gate or itself guarded by lazy_branch_available, so the pre-FINAL filters are always present there; that is asserted with a chassert rather than a runtime branch, because a runtime fallback there would silently restore the ordinary-FINAL path for shapes that must take the fast path. The two cannot-analyse returns were previously justified on the ground that they fire above the narrowing block, so the read is un-narrowed either way; that is true but it is the wrong invariant, and this round corrects it. Being un-narrowed does not make an UNORDERED replacement safe: optimizeReadInOrder runs before optimizeLazyFinal and converts the sort above the read into a FinishSorting whose MergingSortedTransform requires every input sorted, so a read-in-order query over an unanalysable key reached a state 04539_lazy_final_read_in_order_limit_disabled declares forbidden for a safe key. Both returns now re-test the same two conditions the bottom of the function applies (getIndexReadTasks() and allow_partial_split), which leaves the all-non-intersecting fast path byte-identical because it is reached only for a safe key and never consults the new local. Both re-tested conditions now have their own carrier arm, so neither term of the conjunct can be dropped without a test noticing; the text-index one additionally shows that dropping it does not merely lose the order guarantee but returns no rows at all. The __global_row_index identity contract is exercised by the is_deleted and lazy-materialization tests, which pass.

Session id: cron:clickhouse-impl-slot-42:20260730-004800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @novikd, could you review this? optimizeLazyFinal re-applied the row-level filter and PREWHERE as FilterSteps above JoinLazyColumnsStep, i.e. always after the merge, so the argMax(..., version) winner selection ran over unfiltered rows and a key whose highest-versioned row failed a non-deferred filter returned nothing at all; this applies such a filter to the winner-selection read itself, keyed on getDeferredRowLevelFilter / getDeferredPrewhereInfo rather than on the filter being present.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aed6b55]

Summary: ❌

job_name test_name status info comment
Stress test (arm_release) FAIL
Hung check failed, possible deadlock found FAIL cidb

AI Review

Summary

This PR fixes wrong results in ReplacingMergeTree lazy FINAL queries when a non-deferred row policy or PREWHERE must participate in winner selection, by cloning those pre-FINAL filters into the synthetic winner-selection read and extending the regression coverage around the lazy-FINAL plan shape. I did not find a remaining correctness, compatibility, or test-evidence gap in the current tree.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 30, 2026
Comment on lines +150 to +151
query_info.row_level_filter = pre_final_filters.row_level_filter;
query_info.prewhere_info = pre_final_filters.prewhere_info;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This wires the cloned pre-FINAL filters into query_info, but the synthetic winner-selection read never goes through optimizePrimaryKeyConditionAndLimit, so nobody adds those predicates to the step's filter_nodes before selectRangesToRead() runs in LazyFinalKeyAnalysisTransform::work. The result is that query_info.filter_actions_dag still contains only the IN-set filter, so PK/skip-index pruning and the min_filtered_ratio_for_lazy_final gate ignore the newly-supported pre-FINAL predicate. A selective PREWHERE or row policy can therefore still read far more marks than the ordinary FINAL path, or even flip the branch back to the false side at the default ratio threshold, which is exactly the silent perf regression this PR is trying to avoid. Can we add the cloned filters into the synthetic read's filter DAG before applyFilters() here, mirroring what optimizePrimaryKeyConditionAndLimit does for normal ReadFromMergeTree steps?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Still seeing the same gap in the current tree. LazyFinalKeyAnalysisTransform::buildReadingStep now copies the cloned pre-FINAL filters into query_info at src/Processors/Transforms/LazyFinalKeyAnalysisTransform.cpp:150-151, but the synthetic read never mirrors the addFilter calls that ordinary reads get before applyFilters().

ReadFromMergeTree::applyFilters builds query_info.filter_actions_dag only from added_filter_nodes (src/Processors/QueryPlan/ReadFromMergeTree.cpp:2559-2568), so selectRangesToRead() still sees only the IN-set predicate and ignores the cloned row-policy / PREWHERE filter for PK pruning, skip indexes, and min_filtered_ratio_for_lazy_final. The extra wiring still needs to happen here, the same way optimizePrimaryKeyConditionAndLimit does it at src/Processors/QueryPlan/Optimizations/optimizePrimaryKeyConditionAndLimit.cpp:19-24.

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.

Verified, and the premise is right: applyFilters builds query_info.filter_actions_dag from added_filter_nodes alone (ReadFromMergeTree.cpp:2551-2568) and never reads query_info.row_level_filter / query_info.prewhere_info, selectRangesToRead then hands exactly that DAG to buildIndexes, and nothing mirrors optimizePrimaryKeyConditionAndLimit:19-24 for this read because it is constructed inside LazyFinalKeyAnalysisTransform::work and never enters plan optimization. So index analysis on the synthetic read sees the IN-set predicate only.

It is a lost optimization, not a correctness gap, and it is not a regression from this PR. The cloned filters are applied at read time (ReadFromMergeTree.cpp:1397-1403 and :1883-1894, plus the readFromPool/readInOrder sites), so under-pruning reads more marks but cannot drop a row. On origin/master the synthetic read carries no pre-FINAL filters at all (git show origin/master:src/Processors/Transforms/LazyFinalKeyAnalysisTransform.cpp | grep -c "row_level_filter\|prewhere_info" is 0), so master cannot prune on them either: this PR adds them for correctness and leaves the pruning upside unrealized.

I am keeping it out of this PR. This PR fixes wrong results, the wiring is a separate performance concern, and it needs its own EXPLAIN indexes = 1 pruning oracle plus a mutation test and a check that the lazy branch still fires rather than declining at the default min_filtered_ratio_for_lazy_final of 0.5. A fix task is created and I will post the fixing-PR link here when it opens.

One constraint for that work: deferFiltersAfterFinalIfNeeded runs inside applyFilters and deliberately keeps deferred filters out of index analysis so pruning cannot drop rows FINAL still needs, but the synthetic read is built with TableExpressionModifiers(false, {}, {}), so isQueryWithFinal() is false and that guard early-returns. Copying optimizePrimaryKeyConditionAndLimit verbatim here would add the predicates with no such safety net, which is why it wants its own change and its own tests.

@PedroTadim

Copy link
Copy Markdown
Member

@KochetovNicolai I am not sure if this is fixing an issue. Please close the PR if this is not needed.

With query_plan_optimize_lazy_final = 1, a filter that belongs before FINAL was
not applied to the winner-selection read, so the optimization selected a winner
from unfiltered rows and the post-merge filter then rejected it. The query
returned fewer rows than the ordinary FINAL read, or none at all. Both filter
channels are affected: an explicit PREWHERE, which is pre-FINAL by default, and
a row policy under apply_row_policy_after_final = 0.

Collect the pre-FINAL filters and apply them to the winner-selection read. A
filter is only pushed there when it is safe to evaluate on the extra rows that
read sees, so a nondeterministic or stateful predicate keeps the ordinary FINAL
read instead.

The part splitter's early declines needed separating as well. They reported
"leave the read alone", which is a different answer from "there was nothing to
split", and the single flag that carried both meanings made an unavailable lazy
branch also cost the all-non-intersecting fast path. They are now distinct
outcomes, so a key the splitter cannot analyse still keeps its fast path.

The regression test asserts each answer against the same query with the
optimization disabled, so it pins equality with the ordinary FINAL path rather
than a plan-dependent constant, and it also asserts that the lazy plan is still
built and still executes, which a result-only test cannot see.

The test is sent over HTTP rather than through clickhouse client. Its fixtures
are a few rows per table and no query does real work, so its runtime was almost
entirely the cost of starting a client process about 170 times; under a
sanitizer build that cost 0.539 s per spawn against 0.009 s for curl, which put
the test over the flaky check's 180 s limit. On one ASan server it now takes
16.4 s instead of 97.0 s, and on the same unfixed master the old and new
versions of the test print byte-identical output.
@groeneai
groeneai force-pushed the fix-lazy-final-pre-final-row-filter branch from 7203c67 to 39729dd Compare July 30, 2026 19:11
@groeneai

Copy link
Copy Markdown
Collaborator Author

It does fix a live defect. Everything below is measured on today's master (26.8.1.1).

The clearest evidence is already in the tree. 03915_row_policy_should_respect_final_by_default is a committed test whose committed reference asserts 1 1 1 0 1 for

select * from final_row_policy FINAL settings apply_row_policy_after_final = 0;

The test does not set query_plan_optimize_lazy_final itself, but once it is on and the ratio gate is disabled (min_filtered_ratio_for_lazy_final = 0, documented as "value 0 disables this check"), master returns no rows at all, and the count() form returns 0 instead of 1. Master contradicting a reference that is already in the tree is what makes this a bug rather than a preference.

Root cause: the winner selection aggregates argMax(..., version) over unfiltered rows, so a key whose highest-versioned row fails a non-deferred pre-FINAL filter is dropped entirely instead of falling back to the older row the filter does admit. It is silent, not an exception. On an 80k-row table the same shape returns 500 of 1000 keys.

It is also not row-policy specific: additional_table_filters reproduces it identically, so a fix keyed on row policies would be incomplete.

One more datum that may be why this looked unnecessary: in #106734 min_filtered_ratio_for_lazy_final is currently commented out with a pointer to #112332, and #112332 Bug A is exactly what this PR fixes. So merging this is what would let that setting be randomized again.

That said, the call is yours. If you would rather fix it differently, or fold it into other lazy FINAL work, I am fine closing this.

groeneai added 2 commits July 30, 2026 21:56
The flaky check kept failing this test with "Test runs too long (> 180s)"
on amd_asan_ubsan after the earlier curl transport rewrite had already
brought the other three sanitizers well under the limit (msan 229s -> 40s,
tsan 206s -> 36s, debug 219s -> 125s, asan 462s -> 169s median).

The residual cost is server CPU, not transport. Every fixture row was
inserted as `INSERT INTO t SELECT <constants>`, which builds a full query
pipeline sized by `max_threads` (InterpreterInsertQuery.cpp:135-139). A
single-row, 17-byte insert therefore fans out to one thread per core. On a
384-core host, measured over 27 runs per arm on one ASan server:

  form            server CPU/run   INSERT CPU/run   threads/INSERT
  SELECT          73.09 s          69.43 s          150.6
  VALUES           3.59 s           0.06 s            2.0

`INSERT ... VALUES` takes the inlined-data path and uses 2 threads. That
CPU is invisible in wall clock on an idle many-core box but not on a CI
runner (m7i.4xlarge, 16 vCPU) running 8 copies of the test concurrently.

The two forms are equivalent for this fixture: both write one level-0 part
per statement with `optimize_on_insert = 1`, verified identical part count,
part levels, stored rows and FINAL results. All 38 inserts are constant
tuples, so no query semantics change and the reference file is untouched.

Verified against the ASan snapshot of master and the PR build:
- fix binary, 3 runs, no randomization: 3/3 OK, 18.4 s -> 5.21 s per run
- fix binary, 50 runs, --jobs 8, full randomization: 50/50 OK, 0 TOO_LONG,
  slowest run 7.70 s
- mutation: the VALUES form still reddens on pristine master with the
  original wrong-results diff (25 DIFFERENT rows), so no assertion was
  weakened to buy the speedup
The previous commit's comment said both insert forms write a "level-0"
part. MergeTreeDataWriter.cpp:734 sets `new_part_level = optimize_on_insert
? 1 : 0`, and this test sets `optimize_on_insert = 1` deliberately, so the
parts are level 1. Level 0 would in fact break the test: PartsSplitter
treats a level-0 part as intersecting, which is what the comment above the
fixtures already explains. The measured equivalence of the two forms is
unaffected - both write one part per statement at level 1.
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.60% 78.60% +0.00%

Changed lines: Changed C/C++ lines covered: 152/157 (96.82%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - aed6b55

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
Stress test (arm_release) / Hung check failed, possible deadlock found chronic trunk hung-check family, 41 hits across 34 unrelated pull requests and 8 master runs in 30 days on this job alone. Both stacks in the artifact are AST-fuzzer threads inside executeASTFuzzerQueries resolving a query (arrayReduce.cpp:220 raising, and TreeRewriterResult::collectUsedColumns raising Code 47), that is, threads doing work rather than waiting on a lock. This PR touches only the lazy-FINAL plan optimization and cannot reach the fuzzer harness a fix task owns this (investigating at full effort, fixing-PR link to follow on this PR)

Session id: cron:our-pr-ci-monitor:20260731-155315

@groeneai

Copy link
Copy Markdown
Collaborator Author

Correcting the owner column of my ledger above for aed6b5529f200e2a2331b6437fa2c8f673c578eb.

I first read the truncated Hung check failed, possible deadlock found field, whose last 32 KiB
contain only two AST-fuzzer exception stacks, and wrongly concluded this was the generic chronic
hung-check family with no fixing PR. The full hung_check.log artifact contradicts that: there is
exactly one hung query, and it has a specific, already-fixed cause.

elapsed:      747.775818
is_cancelled: 1
read_rows:    2000000
query:        SELECT count(), sum(length(geohashesInBox(1.0, 1.0, 0.0, 0.0, materialize(toUInt8(12)))))
              FROM numbers(2000000) SETTINGS max_block_size = 2000000, max_threads = 1

The working thread sits at GeoHash.cpp:333, the geohashesInBox grid-expansion loop, reached from
FunctionGeohashesInBox::executeImpl. With max_block_size = 2000000 the whole block runs inside one
executeImpl call, so the pipeline's between-blocks cancellation check never gets a turn: the query is
cancelled at 60s (max_execution_time = 60, and is_cancelled: 1) yet keeps working to 747s. The
second thread is just the client waiting in CompletedPipelineExecutor::execute.

That is the bug my #112273 fixed
(merged 2026-07-30T10:26:41Z), which moved the function into src/Functions/geohashesInBox.cpp and
added a work-unit-throttled checkQueryTimeLimit inside the per-row loop. That fix is not in this
build: at aed6b5529f20 the file has zero occurrences of checkQueryTimeLimit, and the expansion loop
still had no checkpoint. So the failing build simply predates the fix.

Check / test Reason Owner / fixing PR
Stress test (arm_release) / Hung check failed, possible deadlock found cancelled geohashesInBox query kept expanding its grid for 747s inside a single executeImpl call; not reachable from this PR, which only touches the lazy-FINAL plan optimization #112273 (ours, merged 2026-07-30) - this build predates the merge, so a fresh run picks it up

The earlier "a fix task owns this" line is withdrawn; no fix task is owed for it.

Session id: cron:our-pr-ci-monitor:20260731-155315

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 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 4, 2026

This branch has not been deployed

No deployments
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-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants