Repository navigation
Recursive CTE: squash chunks before writing the intermediate table - #107068
Conversation
Resolves the in-tree TODO. Each recursive step appended one StorageMemory block per produced chunk; deep recursions accumulated many tiny blocks and per-step reads of the working table degraded. Squash with the standard insert block size thresholds before the sink. Co-Authored-By: Claude Opus 4.8 <[email protected]> (cherry picked from commit b0100ad)
|
Workflow [PR], commit [a7368c8] Summary: ✅
AI ReviewSummaryThis PR adds squashing before writing each recursive CTE step into the intermediate Missing context / blind spots
Findings
Tests
Final VerdictRequest changes: the code path looks reasonable, but the final tip removed the only focused regression coverage for the tricky modes this change already broke during review. LLVM Coverage Report |
|
Dear @ArctypeZach, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message. |
|
@rschu1ze, please review. |
The working table block layout of the previous recursive step is visible through `blockSize` in the recursive term, so the test distinguishes the squashed case from the unsquashed one by lowering `min_insert_block_size_rows` and `min_insert_block_size_bytes`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The intermediate table of a recursive CTE is a `Memory` table, and `StorageMemory::prefersLargeBlocks` is false because smaller blocks are better for the CPU cache. Feeding the raw `min_insert_block_size_rows` / `min_insert_block_size_bytes` thresholds could coalesce a recursive frontier into blocks far larger than a regular `INSERT` into the same storage produces, which would trade a block-count win for a scan regression on the later steps. Use the same policy as `InterpreterInsertQuery`: `max_block_size` rows and no byte threshold for storages that do not prefer large blocks. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`max_block_size` is declared as `NonZeroUInt64`, and the settings style check rejects an `extern` declaration with a different type. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107068&sha=efdb61bca0cfdfc8f680856b9c960421722d3a62&name_0=PR&name_1=Style%20check PR: ClickHouse#107068 Co-Authored-By: Claude Fable 5.1 <[email protected]>
…licitly The existing cases pass without squashing too: `ARRAY JOIN` already emits the whole expansion of a block as a single chunk unless it exceeds `max_block_size`, and with `max_block_size = 10` every input row expands to a 20-row chunk that passes through the squashing unsplit. Add a case where the anchor produces several chunks smaller than `max_block_size`, which only squashing turns into a single block of the working table. `WITH RECURSIVE` is not supported by the old analyzer, so set `enable_analyzer = 1` like the other recursive CTE tests do. Also fix the comment: the working table is truncated and swapped on every step, so blocks do not accumulate across steps, only within one step. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Pushed two follow-ups:
|
The squashing transform was added per stream, and the pipeline was only collapsed to one stream afterwards for the sink. With a parallel read of the working table each stream squashed its own chunks and left its own under-filled tail block behind. Resize to one stream before squashing; the sink is single-stream anyway. Co-Authored-By: Claude Fable 5.1 <[email protected]>
`SimpleSquashingChunksTransform` only enforces the lower thresholds, so an oversized chunk was written as one block regardless of the settings. Use `SquashingTransform` with `max_insert_block_size`, `max_insert_block_size_bytes` and `use_strict_insert_block_limits`, the same parameters a regular `INSERT` uses, so the intermediate table gets the same block layout as an insert into it. Test the strict mode. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
📊 Cloud Performance Report
This PR adds a squashing transform to the intermediate table written between recursive-CTE steps, so its effect is confined to WITH RECURSIVE queries. None of the flagged ClickBench queries (Q16, Q18, Q32, Q33, Q34) use recursive CTEs, so no directional change here can be attributed to the diff. Q16/Q18/Q32 were already flagged not_sure on an unstable, noisy baseline, and the two "improvements" on Q33/Q34 are downgraded to not_sure because the changed code path is never executed by those queries. Net: no query touching the modified path was benchmarked, so this run shows no measurable PR-attributable effect. clickbenchFlagged queries (5 of 43)
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
|
`SquashingTransform` was attached to every output stream of the recursive step, including the totals stream of a member with `WITH TOTALS`. The intermediate table sink drops the totals and extremes streams, which finishes their ports, and `ExceptionKeepingTransform` reports a finished output port as a logical error. Attach the squashing to the main stream only, as the other transforms of that kind do, and add the shape found by the fuzzer as a test. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107068&sha=0efee657c912038bcaf4160f6a53afbac8239506&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 PR: ClickHouse#107068 Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
The two targeted AST fuzzer failures on 0efee65 were real and caused by the switch to |
rschu1ze
left a comment
There was a problem hiding this comment.
This doesn't look terrible (this is a compliment). I'll let my agent do a counter review and will probably shorten the comments, then we can merge.
rschu1ze
left a comment
There was a problem hiding this comment.
Summary
The PR resolves the /// TODO: Support squashing transform in RecursiveCTEChunkGenerator::buildStepExecutor by inserting a SquashingTransform on the main stream just before the intermediate-table sink chain, with thresholds copied from InterpreterInsertQuery's policy for the target storage.
The mechanics are sound:
Pipe::addChainalready doespipe.resize(1)at exactly that point, so the explicitresize(1)is parallelism-neutral and only moves the resize one transform earlier.- The
StreamType::Mainguard is the right fix for the fuzzer failure:Pipe::addChainscallsdropTotalsAndExtremes(), andExceptionKeepingTransform::preparethrowsLOGICAL_ERRORon a finished output port. SquashingTransformis a faithful combined equivalent of thePlanSquashingTransform+ApplySquashingTransformpair used byINSERT— sameSquashingobject, sameflushon finish.
I found no correctness defect. The gap is evidence.
I also checked the automatic review's sliceChunk blocker claim, and it does not hold: Squashing::squash(ChunksWithOffsetsAndLengths &&, Chunk::ChunkInfoCollection &&, SharedHeader) moves every input chunk's infos into result_info and calls data.chunk.setChunkInfos({}) before the private squash overload that reaches sliceChunk, so the "must have no additional information" throw is unreachable from SquashingTransform. Infos are re-attached to the output via result.setChunkInfos, and ChunkInfo::merge defaults to returning the right operand rather than throwing.
Blind spots
- CI on 511c7b3 (the commit that adds the totals/extremes guard) is still running — only
Fast test,Style checkandCode Reviewhave reported. The two targeted AST fuzzer failures on 0efee65 are exactly what this commit fixes, so the fuzzer and stateless jobs on 511c7b3 are the evidence that closes it. - No performance measurement for the motivating case. The only perf data on the PR is the Cloud report over ClickBench and TPC-H, neither of which contains a recursive CTE, so its
no_changeverdict says nothing about this change.
Findings
Majors
-
src/Processors/Sources/RecursiveCTESource.cpp(the new squashing block) — thePerformance Improvementcontract is unproven for the shape the PR is written for. The existingtests/performance/recursive_cte_aggregation.xmlhas a recursive term that is anARRAY JOIN-free filter over the working table, and by your own analysis in the comment on a4de14f,ArrayJoinActionalready emits whole expansions as one chunk — so neither that test nor tests 3 and 4 in the new file clearly exercise the "many tiny chunks per step" regime the description names as the problem. Please add a perf test whose recursive term genuinely produces many sub-max_block_sizechunks per step (the granule-sized-read / selective-filter frontier described in the PR body), or post therecursive_cte_aggregationbefore/after from the perf job. Without one of those, the changelog category asserts a benefit that nothing measures. -
The guard is
stream_type != StreamType::Main, i.e. it covers totals and extremes, but only the totals half has a test.Pipe::dropStreamsfinishes the extremes port the same way it finishes the totals port, soSET extremes = 1over a recursive CTE hits the identicalOutput port is finished for SquashingTransformlogical error if the guard is ever narrowed to totals only. One line in the existing test file:
SET extremes = 1;
WITH RECURSIVE t AS (SELECT 1 AS n UNION ALL SELECT n + 1 FROM t WHERE n < 5)
SELECT count() FROM t FORMAT Null;
SET extremes = DEFAULT;Nits
-
prefers_large_blocksis a compile-time-constantfalseon this path:TemporaryTableHolderalways constructs aStorageMemory(DatabaseCatalog.cpp:187) andStorageMemory::prefersLargeBlocksreturnsfalse(StorageMemory.h:73). So both ternaries' true branches and themin_insert_block_size_rows/min_insert_block_size_bytesexterns are dead. Keeping them as future-proofing is defensible, but then the comment two lines above ("the intermediate table is aMemorytable") reads as if the branch were live. Either drop the ternaries and the two externs, or say explicitly that the branch is there in case the intermediate storage ever stops beingMemory. -
"squashing must not coalesce beyond
max_block_sizerows" describes a maximum, but the value is passed asmin_block_size_rows. In non-strict mode (the default,use_strict_insert_block_limits = false)Squashingappends whole chunks and emits once the accumulated size reaches the minimum, so a resulting block can exceedmax_block_size. Suggest "so squashing accumulates only up tomax_block_sizerows before flushing" or similar. The same framing is repeated in the test comment above the fourth query.
Tests
Not a request, but worth noting for a future reader: tests 3 and 4 in 05059_recursive_cte_squash_intermediate_table.sql do not appear to discriminate the change — both assertions hold without squashing, per your own ArrayJoinAction reasoning. Tests 1 and 2 do. Either strengthen 3 and 4 or label them as invariance checks so they are not mistaken for regression coverage.
Verdict
Requesting changes, minimum actions:
- Provide before/after numbers for the targeted regime, or add a perf test that produces many small chunks per recursive step.
- Add the
SET extremes = 1case to05059_recursive_cte_squash_intermediate_table.sql. - Green CI on 511c7b3, in particular the AST fuzzer jobs that failed on 0efee65.
The nits are optional. The implementation itself I would approve as is.
Every recursive step re-plans and re-executes the recursive member, so the two 1000-step recursions exceeded the 180 s limit of the flaky check in the ASan build. 100 steps are enough to show that the result does not depend on the block layout. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107068&sha=511c7b3ff3c2c3d2a4b1e0b9d4b2f9d1e5c6a7b8&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29 PR: ClickHouse#107068 Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
The ASan flaky check on 511c7b3 failed with "Test runs too long (> 180s)": every recursive step re-plans and re-executes the recursive member, so the two 1000-step recursions in the test are slow in sanitizer builds. Reduced them to 100 steps in 2a8d192; they still show that the result does not depend on the block layout. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107068&sha=511c7b3ff3c24c11627876bd24da52c3be66fd3f&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29 (the link in the commit message has a wrong SHA suffix; this one is correct.) |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 10 s compile time in total, 7 of them have a recent master baseline. |
…omment wording Add a performance test whose anchor produces the frontier as thousands of tiny chunks (a selective filter over a wide scan); without squashing the fragmentation persists on every recursive step. On a local debug build the 21-step query takes 0.44 s on master and 0.03 s with squashing, while the anchor scan alone takes 0.015 s on both. Test the extremes stream next to the totals one, label the two `ARRAY JOIN` cases as invariance checks, and reword the comments: the squashing accumulates up to `max_block_size` rows before flushing, and the `prefersLargeBlocks` branch is there in case the intermediate storage ever stops being `Memory`. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Thanks for the thorough review, @rschu1ze. Sorry for the delay, I missed your comments yesterday. Addressing the three items:
The anchor scan is the same on both sides, so the difference is the per-block overhead of the fragmented working table on every step.
Nits: the comment now says the squashing accumulates only up to |
| </settings> | ||
|
|
||
| <query> | ||
| WITH RECURSIVE t AS |
There was a problem hiding this comment.
This benchmark proves the fragmented-frontier happy path, but it is now the only net-new coverage left in the PR. The review already hit regressions in two modes this file never exercises: the non-Main auxiliary streams (WITH TOTALS / extremes) and the strict max_insert_block_size* split path. After deleting 05059_recursive_cte_squash_intermediate_table, there is no focused query-level proof left for either, so a refactor can silently reintroduce them without changing this benchmark.
Can we keep a small stateless recursive CTE test for one auxiliary-stream shape and one strict-limit split shape alongside the benchmark?
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Squash small chunks before writing the intermediate table during recursive CTE evaluation. Deep recursions no longer accumulate one tiny
Memoryblock per produced chunk, which degraded per-step reads of the working table.Resolves the in-tree
/// TODO: Support squashing transforminRecursiveCTESource.cpp.Problem. Each recursive step writes its output into the intermediate temporary table
(
StorageMemory) one block per produced chunk. The next step then reads the working table block byblock. Recursions that produce many small chunks per step (e.g. graph searches whose frontier is built
from many granule-sized reads or
ARRAY JOINexpansions) accumulate a large number of tiny blocks, andevery subsequent step pays the per-block overhead when scanning the working table.
Change. Add a squashing transform in front of the intermediate-table sink. The thresholds follow the
same policy as a regular
INSERTinto the same storage (InterpreterInsertQuery): the intermediatetable is a
Memorytable andStorageMemory::prefersLargeBlocksis false, so the squashing is boundedby
max_block_sizerows with no byte threshold, rather than bymin_insert_block_size_rows/min_insert_block_size_bytes. This keeps the working table's block layout the same as what a plainINSERTinto aMemorytable would produce, while removing the tiny blocks.Notes for reviewers.
result is identical.
03033–03041,03154,03755, etc.) and bythe new test
05059_recursive_cte_squash_intermediate_table, which observes the working table's blocklayout through
blockSizein the recursive term.Part of the keyed-recursion work tracked in #107067 (PR 1 of 3).
Related: #107067
Workflow [PR]
Sync PR [sync-upstream/pr/107068]
Version info
26.9.1.929(included in26.9and later)