Repository navigation
Lazy materialization for ReplacingMergeTree with FINAL - #101647
Conversation
Optimize reading with FINAL from `ReplacingMergeTree` by building a set of sorting keys from pre-filtered data and using it for primary key index analysis to narrow down the ranges to read. The optimization works as follows: 1. Read sorting key columns (with same predicates) and build a `Set` 2. Use `LazyFinalKeyAnalysisTransform` to apply index analysis with the set 3. If the set fits within limits, use the optimized path: `LazyReadReplacingFinalSource` (aggregation-based FINAL via `argMax`) joined with `LazilyReadFromMergeTree` for remaining columns 4. If the set is too large (truncated), fall back to normal FINAL New components: - `InputSelectorTransform` / `InputSelectorStep`: selects one of two data pipelines based on a signal input - `QueryPipelineBuilder::selectPipeline`: merges three pipelines for the selector pattern - `LazyReadReplacingFinalStep` / `LazyFinalKeyAnalysisStep`: query plan steps wrapping the corresponding processors - `Set::isTruncated`: flag to detect when set building was stopped early due to overflow with `OverflowMode::BREAK` - `QueryPlan::replaceNodeWithPlan` overload accepting expected header New settings: - `query_plan_optimize_lazy_final` (default: false) - `max_rows_for_lazy_final` (default: 10M) - `max_bytes_for_lazy_final` (default: 256MB) Known limitations: - Row policy case has a header mismatch (WIP) - Test reference file is placeholder (needs updating once all cases pass) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- `InputSelectorStep::updatePipeline` now strips extra columns from pipelines that diverge from the plan header (e.g. when `ReadFromMergeTree` adds deferred row_level_filter columns to the pipeline output) - Remove all temporary debug logging from `optimizeLazyFinal` and `LazyReadReplacingFinalSource` - Update test reference file with correct expected output for all cases Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Add `query_plan_optimize_lazy_final`, `max_rows_for_lazy_final`, and `max_bytes_for_lazy_final` to the 26.2 settings changes history. Also revert accidental changes to `UnionStep.cpp`. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
When versions are equal, `ReplacingMergeTree` FINAL keeps the last inserted row. The `argMax` aggregate doesn't guarantee this, so we compute a tiebreaker that combines version and `__global_row_index`: - For unsigned integer types (≤64 bit): pack into UInt128 as `(version << 64) | row_index` - For signed integer types (≤64 bit): flip sign bit via `bitXor(reinterpretAsUInt64(toInt64(version)), 2^63)` to preserve order, then pack into UInt128 - For wider types (UInt128, Int128, etc.): use `tuple(version, row_index)` Also handle the no-version-column case: use `max(__global_row_index)` instead of `argMax`, since there's nothing to compare — just pick the last inserted row. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- `LazyFinalKeyAnalysisTransform` now takes a mutable `shared_ptr<RangesInDataParts>` so filtered ranges from index analysis are visible to `LazyReadReplacingFinalSource` which shares the same pointer. Previously the filtered ranges were written to a private copy and the optimization did not narrow read ranges as intended. - `QueryPipelineBuilder::selectPipeline` now transfers resources from `true_pipeline` and `false_pipeline` into the returned pipeline, preventing premature release of table locks and context holders. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- `LazyReadReplacingFinalSource` now builds an `IN` filter DAG from the `FutureSet` and applies it via `addFilter`/`applyFilters` on the internal `ReadFromMergeTree`. This allows index analysis to prune parts and granules based on the pre-filtered sorting key set. - `LazyFinalKeyAnalysisTransform` is simplified to just signaling: it checks if the set was built successfully (not truncated) and pushes a chunk to signal the optimized path, or finishes without pushing to signal fallback. No more index analysis or shared ranges. - `LazyFinalKeyAnalysisStep` simplified accordingly — takes only `FutureSetPtr`. - Verified: PK index now drops 78/80 granules in the test case, reading only 1 part instead of 5. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Primary key is a prefix of the sorting key. The remaining sorting key columns are useless for index analysis, so building a set from them wastes memory and doesn't improve pruning. Changed both the set-building plan in `optimizeLazyFinal` and the filter DAG in `LazyReadReplacingFinalSource` to use `getPrimaryKey` instead of `getSortingKey`. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Test that `LazyReadReplacingFinalSource` correctly prunes parts and granules via PK index analysis using the pre-built set: - Single-column PK: prunes to 1/5 parts, 2/80 marks - Tuple PK (category, key): prunes to 1/5 parts, 1/40 marks - PK as prefix of ORDER BY (`PRIMARY KEY category`): prunes to 1/5 parts, 8/40 marks (less precise since `key` is not in PK) Also fix SYSTEM STOP MERGES to run before inserts, not after. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The transform no longer does index analysis — it only checks if the set was built without truncation and signals accordingly. Rename to reflect the actual responsibility: - `LazyFinalKeyAnalysisTransform` → `SetReadinessSignalTransform` - `LazyFinalKeyAnalysisStep` → `SetReadinessSignalStep` Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Workflow [PR], commit [8b24d99] Summary: ❌
AI ReviewSummaryThis PR introduces lazy column materialization for Missing context
Findings
ClickHouse Rules
Performance & SafetyThe blocker is a correctness/safety issue in shared mutable state handoff between query-plan source construction and lazy materialization transform. It is not just a micro-optimization concern; it can invalidate result correctness when the optimized branch is selected. Final Verdict
|
| const auto & header = plan.getCurrentHeader(); | ||
| auto version_type = header->getByName(merging_params.version_column).type; | ||
| WhichDataType which(version_type); | ||
| bool use_packed = which.isNativeUInt() || which.isNativeInt() || which.isDate() || which.isDate32() || which.isDateTime(); |
There was a problem hiding this comment.
use_packed handles DateTime but misses DateTime64.
For ReplacingMergeTree(version) with a DateTime64 version column, this falls back to the tuple tiebreaker path even though DateTime64 is 64-bit and can use the packed UInt128 path. This makes the lazy-final path slower for this version type.
Please include which.isDateTime64() in this condition.
|
|
||
| DROP TABLE t_lazy_final_signed; | ||
|
|
||
| -- Test with Int32 version column. |
There was a problem hiding this comment.
Please add a dedicated DateTime64 version-column case here. The new LazyReadReplacingFinalSource tiebreaker has a type-based fast path, and this file currently covers UInt64/Int64/Int32/UInt128/Int128 but not DateTime64.
A ReplacingMergeTree(version DateTime64(...)) test with duplicate keys would catch regressions where the optimization path diverges from baseline FINAL semantics.
Internal `ReadFromMergeTree` steps created by `LazyReadReplacingFinalSource` and the set-building plan in `optimizeLazyFinal` should not pollute or use the query condition cache. The cache stores per-part mark matching results keyed by condition hash, and internal reads with `IN`-set filters wrote entries that interfered with subsequent queries on the same parts. Also add `SYSTEM STOP MERGES` for all sub-tables in the test to prevent background merges from changing insert order semantics. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
|
||
| dag.getOutputs().push_back(global_offset_node); | ||
|
|
||
| /// Remove virtual columns if they were not initially needed. |
There was a problem hiding this comment.
The comment appears inverted relative to the logic below.
added_part_starting_offset / added_part_offset are true when addStartingPartOffsetAndPartOffset had to add these virtual columns itself. In that case, they are not pushed to outputs. When the flags are false, the columns were already requested by the query and are preserved in outputs.
So this comment should say that we keep/include virtual columns when they were initially needed, not remove them.
Benchmark `ReplacingMergeTree` FINAL with a concentrated filter (`category = 1`, 50k out of 10M keys) and evenly distributed updates (every 100th key has version 2, defeating `split_intersecting`). Uses separate partitions to prevent merges from combining parts. Query reads full payload via `cityHash64(payload)`. Compares `query_plan_optimize_lazy_final = 0` (median 154ms) vs `= 1` (median 117ms) — 24% improvement. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Move `ReadFromMergeTree` creation and `IN`-set filter application from `LazyReadReplacingFinalSource` into `SetReadinessSignalTransform`. The transform now: 1. Creates the reading step with the `IN`-set filter 2. Runs index analysis (`applyFilters`) 3. Counts total vs selected marks to compute `filtered_ratio` 4. If `filtered_ratio < min_filtered_ratio_for_lazy_final`, signals fallback instead of proceeding with the optimization 5. Shares the pre-built reading step with `LazyReadReplacingFinalSource` via `LazyFinalSharedState` New setting: `min_filtered_ratio_for_lazy_final` (default 0.5) — minimum fraction of marks that must be filtered for the optimization to proceed. This prevents the optimization from applying when the set-based index analysis can't prune enough data, avoiding the overhead of triple I/O (set build + argMax + lazy read) in cases where standard FINAL is faster. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
| /// Remove columns from ReadFromMergeTree that are not needed by the steps above. | ||
| { | ||
| Optimization::ExtraSettings extra{}; | ||
| tryRemoveUnusedColumns(set_plan.getRootNode(), nodes, extra); |
There was a problem hiding this comment.
tryRemoveUnusedColumns is invoked on set_plan, but it receives nodes from the outer query plan.
That mixes node ownership across two different QueryPlan::Nodes lists: if the optimization inserts helper/discarding steps, those nodes are allocated in the outer list while being referenced from set_plan. This can break plan invariants and lead to invalid/dangling node references when set_plan is moved/united later.
Please pass set_plan's own node list instead (for example, expose/access the local set_plan nodes similarly to other in-plan rewrites) so all node allocations and pointers stay within the same plan.
There was a problem hiding this comment.
This does not matter; replaceNodeWithPlan moves all the nodes into the outer plan anyway.
The transform now does index analysis again (building the ReadFromMergeTree step, applying IN-set filter, checking filtered ratio), so the original name is appropriate. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Log the decision and reason when the optimization is enabled or disabled: - Set not available - Set truncated (with rows, bytes, and configured limits) - Filtered ratio below threshold (with ratio, threshold, marks, set rows) - Optimization enabled (with ratio, threshold, marks, set rows) All messages use TRACE level. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Fix garbage text on line 91 of `LazyFinalKeyAnalysisTransform.cpp`. Add test that triggers all 3 `LOG_TRACE` decision paths: - Set truncated (small `max_rows_for_lazy_final`) - Filtered ratio below threshold (scattered filter) - Optimization enabled (concentrated filter) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Set `min_filtered_ratio_for_lazy_final = 0` for all optimized queries in 03988 test to prevent the ratio check from causing fallback on small test data where index analysis may not filter enough marks. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Add `no-debug` tag and `SET enable_analyzer = 1` to 03988. Add `--enable_analyzer=1` via \$settings to all \$CLICKHOUSE_CLIENT calls in 03990 and 03991 shell tests. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Before building the set and running the aggregation-based FINAL, split parts into non-intersecting (unique key ranges) and intersecting (overlapping ranges needing dedup). Non-intersecting parts are read without FINAL via a separate ReadFromMergeTree, combined with the main result via UnionStep. - Expose `splitPartsRanges` and `isSafePrimaryKey` from `PartsSplitter` - Run early index analysis via `selectRangesToRead` before splitting - Update the original reading step with `setAnalyzedResult` to only contain intersecting parts (avoids redundant re-splitting in pipeline) - If all parts are non-intersecting, replace with non-FINAL read and return early (no set building needed) - UNION the non-intersecting read with the entire InputSelectorStep output (both true and false branches handle only intersecting parts) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Add `LazilyUnorderedReadFromMergeTree` step and `LazyUnorderedReadFromMergeTreeSource` for unordered lazy column materialization. Unlike the ordered variant, this creates a `ReadFromMergeTree` internally and passes through chunks without preserving row order. Used by lazy FINAL where row order doesn't matter. Add `lazy_materializing_rows` field to `ReadFromMergeTree` so the unordered source can propagate it to `MergeTreeSelectProcessor`. Add `skip_inverse_permutation` flag to `LazyMaterializingTransform` and `JoinLazyColumnsStep` to avoid the unnecessary inverse permutation in the lazy FINAL true branch. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…alizingTransform In pass-through mode, lazy chunks are forwarded directly to the output without buffering, squashing, or permuting. The main input is only used to compute row indices for `filterRangesAndFillRows`. Add validation in both `LazyMaterializingTransform::setPassThrough` and `JoinLazyColumnsStep::setPassThrough` that the lazy header matches the output header. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
In pass-through mode, skip permutation computation entirely and sort the UInt64 index array directly using `radixSortLSD`. This avoids `stableGetPermutation` + `permute` overhead when row order doesn't matter (lazy FINAL branch). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Current AI review is mostly not relevant. ❌ Blockers
That's not true, trailing columns pass through by DAG semantic.
It's impossible to make them fully consistent because the split happens on top ok PK-filtered ranges.
We unite these plan nodes anyway. It's safe.
It's safe. We build a proper pipeline and guard access by InputSelector.
We don't apply an optimization for empty PK.
I don't care, I don't believe anybody would use DateTime64 as a version.
That's an outdated comment; it's already been fixed.
Also outdated and fixed.
Already fixed.
Already fixed. |
| query_info.table_expression_modifiers = TableExpressionModifiers(false, {}, {}); | ||
|
|
||
| auto reading = std::make_unique<ReadFromMergeTree>( | ||
| std::make_shared<RangesInDataParts>(std::move(parts)), |
There was a problem hiding this comment.
This moves lazy_materializing_rows->ranges_in_data_parts into ReadFromMergeTree, but the same shared lazy_materializing_rows is also passed to setLazyMaterializingRows and later consumed by LazyMaterializingTransform::filterRangesAndFillRows for row mapping. After this move, that state is empty on the transform side, so lazy column materialization can become inconsistent (wrong/missing rows in the join path).
Please avoid moving from shared state here. Pass a copy to ReadFromMergeTree (or otherwise preserve ranges_in_data_parts for the transform).
LLVM Coverage Report
Changed lines: 93.65% (1018/1087) | lost baseline coverage: 1 line(s) · Uncovered code |
…::expandPipeline
`LazyUnorderedReadFromMergeTreeSource::expandPipeline` used to iterate over
every processor returned by its `buildReaders()` helper and call
`connect(processor->getOutputs().front(), new_input)` on each. That worked
only when `ReadFromMergeTree::initializePipeline` produced a pipe whose
processors were all independent sources.
In general, `initializePipeline` can add internal transforms (e.g. `Resize`,
`ConcatProcessor`, simple transforms for sampling/filtering/row-level
security), in which case some processors' first output is already connected
to the next internal step. `Pipe::detachProcessors` returns a flat list that
includes those internally-wired processors, so the old loop would trip over
those already-connected ports with:
Logical error: 'Port is already connected, (header: [...])'.
This reproduced in master `Stress test (arm_release)` on commit
`55a7ff843d71c95398f5b4defe5191a6f976df74` (STID 0996-3f3c) and is
reproducible locally against 26.4.1.1 with a plain
`SELECT count() FROM t FINAL WHERE category = 1`
using the lazy FINAL optimization: the server crashes within a few runs as
`max_threads` varies, because `initializePipeline` inserts a `Resize` when
the pool has more output ports than `output_streams_limit`.
Fix by matching the pattern already used by the sibling
`LazyReadReplacingFinalSource` (added in the same PR ClickHouse#101647): collect the
pipe's terminal output ports via `Pipe::getOutputPort(i)` before detaching
processors, then connect only those real outputs to the source's new input
ports.
Added regression test `04105_lazy_final_unordered_expand_pipeline` that
deterministically reproduces the crash on the unfixed binary and passes
with the fix (verified 50/50 with and without randomized settings).
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=55a7ff843d71c95398f5b4defe5191a6f976df74&name_0=MasterCI&name_1=Stress%20test%20%28arm_release%29
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Implement lazy column materialization for ReplacingMergeTree with FINAL in case the predicate is selective enough.
Added settings:
query_plan_optimize_lazy_finalis a feature flagmax_rows_for_lazy_finalandmax_bytes_for_lazy_finalare limits for a PK set in memory; for a non-selective predicate fallback is appliedmin_filtered_ratio_for_lazy_finalapplies a fallback if PK analysis by the set filters out less than this ratio of dataDocumentation entry for user-facing changes
Version info
26.4.1.1092