Repository navigation
Conversation
Internal second-model review: 10 rounds, 52 findings, all resolved before publicationBefore opening this PR I ran it through an independent internal review harness: each round is a cold Findings that changed the fix itself
Findings that changed how the fix is tested
Not accepted, and noted
Final round: the cold review raised 4 items (test tagging, arm liveness, pin scope, comment accuracy) Session id: cron:clickhouse-review-slot-53:20260730-023800 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-42:20260730-004800 |
|
cc @KochetovNicolai @novikd, could you review this? |
|
Workflow [PR], commit [aed6b55] Summary: ❌
AI ReviewSummaryThis PR fixes wrong results in Final Verdict
|
| query_info.row_level_filter = pre_final_filters.row_level_filter; | ||
| query_info.prewhere_info = pre_final_filters.prewhere_info; |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
@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.
7203c67 to
39729dd
Compare
|
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. select * from final_row_policy FINAL settings apply_row_policy_after_final = 0;The test does not set Root cause: the winner selection aggregates It is also not row-policy specific: One more datum that may be why this looked unnecessary: in #106734 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. |
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 152/157 (96.82%) · Uncovered code |
CI finish ledger - aed6b55Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260731-155315 |
|
Correcting the owner column of my ledger above for I first read the truncated The working thread sits at That is the bug my #112273 fixed
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 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes wrong results (silently missing rows, including a
count()of0) for aReplacingMergeTreeFINALquery withquery_plan_optimize_lazy_final = 1and a row-level filter orPREWHEREapplied before theFINALmerge. 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 withapply_row_policy_after_final = 0, and with an explicitPREWHEREat default settings.Description
Related: #112332 (report), #106734 (exposed it)
ReadFromMergeTree::deferFiltersAfterFinalIfNeededdecides which side of theFINALmerge 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 explicitPREWHERE. Both orderings are valid.optimizeLazyFinalignored the distinction and re-applied both filters asFilterSteps aboveJoinLazyColumnsStep, i.e. always after the merge. TheAggregatingstep insideLazyReadReplacingFinalpicks each key's winner withargMax(..., 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
FINALmerge would. The optimization stays enabled rather than being switched off, which the new test asserts both throughEXPLAINand 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 inquery_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
ReplacingMergeTreeFINALwithquery_plan_optimize_lazy_final = 1and 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_filtersand lightweightDELETE(_row_exists) are not carriers, contrary to the report; the second carrier besides row policies isPREWHERE.query_plan_optimize_lazy_finalseems to be break partition pruning #106810 and04359_distributed_final_modifiersare distinct defects.getQueryInfo()shares them with the false branch'sFINALread.cloneFilterSubDAGexposes every predicate input as a pass-through output, so the DAG cannot erase the sorting-key,versionoris_deletedcolumns the aggregation reads. The test covers a filter onis_deleteditself and on a sorting-key column.hasNonDeterministic()/hasStatefulFunctions()); otherwise the query keeps the ordinaryFINALread. 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.query_plan_optimize_primary_key = false) untouched. That precondition is fail-closed, not a live path:supportsDataflowStatisticsCollection()is!isQueryWithFinal(), so aFINALread fails the statistics walk inconsiderEnablingParallelReplicasand the candidate is never built for a query this optimization applies to.FilterStepis kept: it recomputes the predicate from columns re-read byLazilyReadFromMergeTree, andoptimizePrewhereretains a derived predicate column when a residualWHEREconsumes it, which04493_lazy_final_prewhere_derived_filter_columnexercises. The twolazy_final_*performance tests carry neither filter and take the unchanged path.