Skip to content

Recursive CTE: squash chunks before writing the intermediate table - #107068

Merged
rschu1ze merged 15 commits into
ClickHouse:masterfrom
ArctypeZach:recursive-cte-squashing
Sep 7, 2026
Merged

rschu1ze merged 15 commits into
ClickHouse:masterfrom
ArctypeZach:recursive-cte-squashing

Conversation

@ArctypeZach

@ArctypeZach ArctypeZach commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

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 Memory block per produced chunk, which degraded per-step reads of the working table.


Resolves the in-tree /// TODO: Support squashing transform in RecursiveCTESource.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 by
block. Recursions that produce many small chunks per step (e.g. graph searches whose frontier is built
from many granule-sized reads or ARRAY JOIN expansions) accumulate a large number of tiny blocks, and
every 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 INSERT into the same storage (InterpreterInsertQuery): the intermediate
table is a Memory table and StorageMemory::prefersLargeBlocks is false, so the squashing is bounded
by max_block_size rows with no byte threshold, rather than by min_insert_block_size_rows /
min_insert_block_size_bytes. This keeps the working table's block layout the same as what a plain
INSERT into a Memory table would produce, while removing the tiny blocks.

Notes for reviewers.

  • Output to the parent query is unaffected in content; chunks are delivered coarser. The recursion's
    result is identical.
  • No new settings.
  • Covered by the existing recursive CTE stateless suite (03033–03041, 03154, 03755, etc.) and by
    the new test 05059_recursive_cte_squash_intermediate_table, which observes the working table's block
    layout through blockSize in 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

  • Merged into: 26.9.1.929 (included in 26.9 and later)

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)
@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a7368c8]

Summary: ✅


AI Review

Summary

This PR adds squashing before writing each recursive CTE step into the intermediate Memory table and adds a benchmark for the fragmented-frontier workload. The pipeline change itself looks consistent with the established insert squashing path once it is reduced to one stream, but the final tip deleted the small query-level regression tests and now leaves only a benchmark for behavior that already regressed once in auxiliary-stream and strict-limit code paths.

Missing context / blind spots
  • ⚠️ The 2026-09-06 CI rerun is still in progress, so I could not use the final stateless, AST fuzzer, or sanitizer jobs as evidence for commit a7368c8b50bfadc0ec24f145072bc0354a2d75fb. Green runs of those jobs on the final tip would close this gap.
Findings

⚠️ Majors

  • [tests/performance/recursive_cte_squash_intermediate_table.xml:7] The net PR now keeps only a performance benchmark, but the review already found regressions in modes this file never exercises: the non-Main auxiliary streams (WITH TOTALS / extremes) and the use_strict_insert_block_limits path. After deleting 05059_recursive_cte_squash_intermediate_table, there is no focused query-level proof left that those modes still work, so a refactor can reintroduce them without any result change in this benchmark.
    Suggested fix: keep a small stateless recursive CTE test that covers one auxiliary-stream shape and one strict-limit split shape alongside this benchmark.
Tests
  • ⚠️ Keep at least one focused stateless regression for WITH TOTALS / extremes and one for max_insert_block_size with use_strict_insert_block_limits = 1; the benchmark only covers the main-stream happy path.
Final Verdict

Request 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

⚠️ No coverage measurement for commit a7368c8: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_7.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

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.

@alexey-milovidov

Copy link
Copy Markdown
Member

@rschu1ze, please review.

alexey-milovidov and others added 2 commits September 3, 2026 09:07
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]>
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 3, 2026
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]>
@ArctypeZach
ArctypeZach marked this pull request as ready for review September 3, 2026 12:29
ArctypeZach and others added 2 commits September 3, 2026 10:11
…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]>
@ArctypeZach

Copy link
Copy Markdown
Contributor Author

Pushed two follow-ups:

  • cf530fb: max_block_size is declared as NonZeroUInt64, so the new extern has to be SettingsNonZeroUInt64. This was the failing cpp style sub-check.
  • a4de14f: as far as I can tell from ArrayJoinAction, the cases added in 8674fdf pass without squashing too. It emits the whole expansion of a block as one chunk unless it exceeds max_block_size, and with max_block_size = 10 each input row becomes a 20-row chunk that passes through the squashing unsplit. I added a case where the anchor produces chunks of 2, 2 and 1 rows: without squashing the first recursive step reads them as three blocks, with squashing as one block of 5 rows. Also SET enable_analyzer = 1 like the other WITH RECURSIVE tests, and a comment fix: the working table is truncated and swapped every step, so blocks do not accumulate across steps, only within one.

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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 39 queries analysed

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.

clickbench

⚠️ 5 inconclusive

Flagged queries (5 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 614 538 -12.4% <0.0001 Baseline is intrinsically noisy (cv_base 11.2%, history noisy) and this PR only touches recursive-CTE squashing, which ClickBench Q16 never exercises, so the -12.4% is run-to-run variance.
⚠️ 18 not_sure 1082 858 -20.7% <0.0001 Q18 does not use recursive CTEs, the only path this PR changes, and the baseline is flaky (noisy history, cv_base 16.2%); the -20.7% is not attributable to this change.
⚠️ 32 not_sure 1362 717 -47.4% <0.0001 Q32 has a very noisy baseline (cv_base 28%) and does not exercise recursive CTEs; the -47.4% swing is baseline variance, not a PR effect.
⚠️ 33 not_sure 1232 1143 -7.2% <0.0001 This PR only adds squashing to recursive-CTE intermediate tables; ClickBench Q33 runs no recursive CTE, so the -7.2% cannot come from this diff and is run-to-run variance.
⚠️ 34 not_sure 1254 1142 -9.0% <0.0001 Same as Q33: the recursive-CTE squashing change does not touch Q34's execution path, so the flagged -9.0% improvement is unrelated to this PR and likely variance.

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

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 524709da-4281-4de7-9fde-ad874d351bfc
  • MIRAI run: 7ae59e6c-3d57-4a7a-8f2d-c3f5a05ed227
  • PR check IDs:
    • clickbench_1446543_1788737433
    • clickbench_1446549_1788737433
    • clickbench_1446555_1788737433
    • tpch_adapted_1_official_1446565_1788737433
    • tpch_adapted_1_official_1446577_1788737433
    • tpch_adapted_1_official_1446613_1788737433

@rschu1ze rschu1ze self-assigned this Sep 3, 2026
`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]>
@ArctypeZach

Copy link
Copy Markdown
Contributor Author

The two targeted AST fuzzer failures on 0efee65 were real and caused by the switch to SquashingTransform: it was attached to every stream of the recursive step, including the totals stream of a member with WITH TOTALS. The sink drops the totals and extremes streams, which finishes their ports, and ExceptionKeepingTransform treats a finished output port as a logical error (SimpleSquashingChunksTransform tolerated it). Reproduced locally on a debug build with the fuzzer query; fixed in 511c7b3 by attaching the squashing to the main stream only, with a terminating variant of the fuzzer query as a test. The exact fuzzer query itself now ends with the expected division by zero at the second step.

@rschu1ze rschu1ze left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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 rschu1ze left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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::addChain already does pipe.resize(1) at exactly that point, so the explicit resize(1) is parallelism-neutral and only moves the resize one transform earlier.
  • The StreamType::Main guard is the right fix for the fuzzer failure: Pipe::addChains calls dropTotalsAndExtremes(), and ExceptionKeepingTransform::prepare throws LOGICAL_ERROR on a finished output port.
  • SquashingTransform is a faithful combined equivalent of the PlanSquashingTransform + ApplySquashingTransform pair used by INSERT — same Squashing object, same flush on 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 check and Code Review have 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_change verdict says nothing about this change.

Findings

Majors

  1. src/Processors/Sources/RecursiveCTESource.cpp (the new squashing block) — the Performance Improvement contract is unproven for the shape the PR is written for. The existing tests/performance/recursive_cte_aggregation.xml has a recursive term that is an ARRAY JOIN-free filter over the working table, and by your own analysis in the comment on a4de14f, ArrayJoinAction already 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_size chunks per step (the granule-sized-read / selective-filter frontier described in the PR body), or post the recursive_cte_aggregation before/after from the perf job. Without one of those, the changelog category asserts a benefit that nothing measures.

  2. The guard is stream_type != StreamType::Main, i.e. it covers totals and extremes, but only the totals half has a test. Pipe::dropStreams finishes the extremes port the same way it finishes the totals port, so SET extremes = 1 over a recursive CTE hits the identical Output port is finished for SquashingTransform logical 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

  1. prefers_large_blocks is a compile-time-constant false on this path: TemporaryTableHolder always constructs a StorageMemory (DatabaseCatalog.cpp:187) and StorageMemory::prefersLargeBlocks returns false (StorageMemory.h:73). So both ternaries' true branches and the min_insert_block_size_rows / min_insert_block_size_bytes externs are dead. Keeping them as future-proofing is defensible, but then the comment two lines above ("the intermediate table is a Memory table") 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 being Memory.

  2. "squashing must not coalesce beyond max_block_size rows" describes a maximum, but the value is passed as min_block_size_rows. In non-strict mode (the default, use_strict_insert_block_limits = false) Squashing appends whole chunks and emits once the accumulated size reaches the minimum, so a resulting block can exceed max_block_size. Suggest "so squashing accumulates only up to max_block_size rows 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:

  1. Provide before/after numbers for the targeted regime, or add a perf test that produces many small chunks per recursive step.
  2. Add the SET extremes = 1 case to 05059_recursive_cte_squash_intermediate_table.sql.
  3. 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.

@novikd novikd self-assigned this Sep 3, 2026
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]>
@ArctypeZach

Copy link
Copy Markdown
Contributor Author

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

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a7368c8b5 with master 8201c8238 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 10 s compile time in total, 7 of them have a recent master baseline.

Job report

@abashkeev abashkeev added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
…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]>
@ArctypeZach

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review, @rschu1ze. Sorry for the delay, I missed your comments yesterday. Addressing the three items:

  1. Evidence for the many-tiny-chunks regime. Added tests/performance/recursive_cte_squash_intermediate_table.xml: the anchor is a selective filter over a wide numbers_mt scan, which produces the frontier as thousands of chunks of a couple of rows each, and without squashing that fragmentation persists on every one of the 20 recursive steps (one block per chunk written, one chunk per block read). The Performance Comparison job will report before/after on release builds; in the meantime, on a local debug build (so absolute numbers are inflated, but both sides equally):
query (debug build, 21 recursive steps unless noted) master this PR
perf test query, 21 steps 0.44 s 0.03 s
same with 2 steps 0.054 s 0.025 s
anchor scan alone 0.015 s 0.015 s
blocks of the frontier seen by step 1 about 1600 blocks of 14 to 16 rows 1 block of 24415 rows

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.

  1. extremes = 1. Added as a test case next to the totals one.

  2. Green CI. The head after the totals fix, 2a8d192, passed the full matrix (159 checks) including both targeted AST fuzzer jobs.

Nits: the comment now says the squashing accumulates only up to max_block_size rows before flushing (in the code and in the test), and states explicitly that the prefersLargeBlocks branch is there in case the intermediate storage ever stops being Memory. The two ARRAY JOIN cases are labelled as invariance checks.

@ArctypeZach
ArctypeZach requested a review from rschu1ze September 4, 2026 14:05
@rschu1ze

rschu1ze commented Sep 6, 2026

Copy link
Copy Markdown
Member
image

</settings>

<query>
WITH RECURSIVE t AS

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

@rschu1ze
rschu1ze added this pull request to the merge queue Sep 7, 2026
Merged via the queue into ClickHouse:master with commit 1407a43 Sep 7, 2026
175 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
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-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants