Skip to content

Recursive CTE: experimental USING KEY (keyed recursion / semi-naive evaluation) - #107070

Open
ArctypeZach wants to merge 44 commits into
ClickHouse:masterfrom
ArctypeZach:keyed-recursive-cte
Open

ArctypeZach wants to merge 44 commits into
ClickHouse:masterfrom
ArctypeZach:keyed-recursive-cte

Conversation

@ArctypeZach

@ArctypeZach ArctypeZach commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #107067

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

Add experimental USING KEY clause for recursive CTEs: WITH RECURSIVE name USING KEY (cols) AS (...). The recursion accumulates one row per key (new rows replace same-key rows), only changed rows form the next iteration's working table, and the accumulated state is readable inside recursive members as <name>_settled. Enables efficient graph algorithms (shortest path, reachability, transitive closure) that terminate on cyclic inputs without path tracking. Behind allow_experimental_keyed_recursive_cte.


[DRAFT — hardening checklist below must be completed before review]

Implements keyed recursion (semi-naive evaluation), equivalent to DuckDB's USING KEY
(duckdb/duckdb#12430, v1.3; Hirn & Grust CIDR'23 / SIGMOD'25). Generalizes the in-tree
TODO: Support UNION DISTINCT recursive CTE mode (RecursiveCTE.h) — UNION DISTINCT is the
degenerate case where the key is all columns.

Semantics.

  • One accumulated row per key; a produced row with an existing key replaces it (within an iteration,
    last write wins; ORDER BY in the recursive member controls the survivor).
  • Rows identical to the accumulated row are no-ops and are not propagated → cycles terminate without
    path arrays.
  • Working table per iteration = changed rows only (the delta).
  • <cte_name>_settled is visible inside recursive members: the accumulated state (one row per key) as
    of the previous iteration, enabling strict-improvement refutation (label-correcting Dijkstra).
  • The CTE's result is the accumulated table at convergence (not the per-iteration concatenation).

Implementation. Parser (ParserWithElement/ASTWithElement.key_columns), analyzer
(resolveUnion: key validation, settled temp table + scope injection, integrated with the iterative
type-widening passes), UnionNode/RecursiveCTETable plumbing (clone/hash/equality/AST round-trip),
evaluator (RecursiveCTEChunkGenerator: SipHash128-keyed accumulated columns + index, upsert-replace,
delta extraction, dead-row compaction, settled snapshot rebuilt per step, results emitted at
convergence in DEFAULT_BLOCK_SIZE chunks).

Benchmarks (same binary/host; identical optimal results where both complete):

  • Synthetic 300-node cyclic weighted graph, SSSP: append-only + path guard = timeout (60 s);
    USING KEY = 0.038 s.
  • OpenStreetMap planet, contracted road graph (25M segments, in-RAM adjacency dictionary), production
    routing queries: 23 km: 2.68 s → 0.65 s (4.1×); 55 km: 17.2 s → 1.65 s (10.4×); 200 km:
    timeout (150 s) → 8.3 s.

Tests. 05059_recursive_cte_using_key: cycle termination without a path guard, shortest path with
settled refutation, multi-column keys, negative cases (non-recursive CTE with USING KEY, unknown key
column). Full recursive-CTE stateless suite passes (21/21).

Hardening checklist (pre-review):

  • Gate behind allow_experimental_keyed_recursive_cte setting
  • clickhouse-format and parseQueryToJSON/formatQueryFromJSON round-trip tests for the new syntax
  • Document + test within-iteration survivor rule (last-wins, ORDER BY control, single-thread determinism)
  • Replace std::unordered_map with HashMap; memory-account the accumulated state
  • Document <name>_settled shadowing (the final surface, _settled suffix vs recurring.<name>, is still open)
  • Document LIMIT interaction (keyed evaluation buffers to convergence; no partial early-stop)
  • Debug + ASan/UBSan builds with the test suite
  • Docs entry for the WITH statement (the page moved into its statement registration in ParserWithElement.cpp, which is now the source of truth)

Depends on PR 1 (squashing) and PR 2 (materialized CTEs in recursive WITH).
Tracked in #107067 (PR 3 of 3).


Workflow [PR]
Sync PR [sync-upstream/pr/107070]

ArctypeZach and others added 3 commits June 10, 2026 12:06
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]>
Previously any MATERIALIZED CTE inside WITH RECURSIVE was rejected. Only the
recursive CTE itself (union-shaped, speculatively marked recursive) cannot be
materialized; plain SELECT helper CTEs can never be recursive, so allow them.
They materialize once via the existing future-table machinery and every
recursive step reads the snapshot instead of re-evaluating the subquery per
step, which is the natural way to pre-filter a search space for a recursive
traversal (e.g. a road-graph corridor for a shortest-path search).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…tion)

WITH RECURSIVE name USING KEY (a, b) AS (...) evaluates the recursion over a
keyed accumulated table instead of an append-only one: a row produced with an
existing key replaces the accumulated row (last write wins within a step), and
only changed rows form the next step's working table. The CTE's result is the
accumulated table at convergence. The accumulated state is also visible inside
recursive members as the <cte_name>_settled table, so queries can refute
non-improving rows.

This gives recursive queries a settled set: cyclic graphs terminate without
explicit path tracking, and label-correcting shortest path (Dijkstra-style
relaxation joined against <name>_settled) converges without the exponential
re-expansion of append-only evaluation. Equivalent to DuckDB's USING KEY
(SIGMOD'25 'A Fix for the Fixation on Fixpoints' lineage) and a generalization
of the UNION DISTINCT TODO in RecursiveCTE.h (DISTINCT = key over all columns).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7e2a8f9]

Summary: ❌

job_name test_name status info comment
Stress test (arm_asan_ubsan) FAIL
UndefinedBehaviorSanitizer: undefined behavior (STID: 0993-9a84) FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Adds experimental USING KEY recursive CTEs with one accumulated row per key, changed-row propagation, and a settled-state table. One correctness blocker remains: mutation set caching can reuse an earlier iteration's state and persist an incorrect result.

Findings

❌ Blockers

  • src/Processors/Sources/RecursiveCTESource.cpp:359: Recursion-dependent IN sets survive across iterations in background mutations. MutatePlainMergeTreeTask::prepare installs a PreparedSetsCache with the default enable_sharing_sets_for_mutations = 1. Copied recursive contexts inherit it. CollectSets uses the subquery tree hash as the cache key, and TableNode::updateTreeHashImpl hashes the unchanged temporary table name. Refreshing the settled table and rebuilding the executor therefore leaves the cache key unchanged; CreatingSetsTransform::startSubquery reuses the first set.

    For a seed k = 1 and recursive member SELECT k + 1 FROM t WHERE k < 3 AND k IN (SELECT k FROM t_settled), the first iteration caches {1} and produces 2. The next iteration rejects 2 against the stale set and terminates. Using SELECT max(k) FROM t as an ALTER TABLE ... UPDATE assignment can consequently persist 2, although the fixed point requires 3.

    Prevent cross-iteration reuse of sets depending on the working or settled table, including nested query contexts. The inline finding contains a complete mutation reproduction.

Missing context / blind spots
  • ⚠️ No ClickHouse executable is available in this CI job. The new reproduction is based on the source trace above and has not been executed. The fetched Praktika reports report 15,392 passed tests, 4,560 skipped tests, and no failures.
Tests
  • ⚠️ Add a focused stateless mutation regression using a recursion-dependent IN subquery with set sharing enabled and disabled; both must persist the same complete result. Cover dependencies on both the working and settled tables.
Final Verdict

Status: ❌ Block

Prevent stale set reuse across recursive iterations and validate the mutation regression.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature 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.

Resolve the conflict in `RecursiveCTESource.cpp`: keep the keyed (`USING KEY`)
evaluation path and the squashing transform from this branch, and take master's
hoisting of the metadata snapshot into a named variable before `IStorage::write`
and `IStorage::truncate`, applying it to the keyed `pushBlockIntoStorage` helper
as well. Master's removal of the
`merge_tree_enable_remove_parts_from_snapshot_optimization` select query option
is kept.
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 3, 2026
`04327`/`04328` were taken by tests that landed on master since this branch
was created.
The renumbering commit additionally:

- enables `enable_materialized_cte` in the materialized-CTE test, so it
  exercises the materialized path instead of the inlining hint;
- adds cases for `USING KEY` on a non-`UNION` CTE and for the formatting and
  AST JSON round-trips of the key column list.

This commit only records that; there is nothing left to change.
… JSON

Master gained a size guard in `ASTWithElement::updateTreeHashImpl` and a
designated initializer for `CommonTableExpressionData`, so the new members had
to be reconciled with both:

- bump the expected `ASTWithElement` size to 88 and hash `key_columns`, which is
  semantically significant and, like `aliases`, is not an AST child;
- write and read `key_columns` in `writeJSON`/`readJSON`, validating that the
  list contains identifiers, so `parseQueryToJSON`/`formatQueryFromJSON`
  round-trips a keyed recursive CTE losslessly;
- give `CommonTableExpressionData::key_columns` a default initializer for
  `-Wmissing-designated-field-initializers`.
The `WITH` reference page is generated from the statement registration in
`ParserWithElement.cpp`, so the documentation is added there: a
`Keyed recursion` section describing keyed (semi-naive) evaluation, the
`<cte_name>_settled` table, the key column restrictions, and the two worked
examples from the test; the syntax block; and a correction of the materialized
CTE restriction, which no longer forbids `MATERIALIZED` on non-recursive CTEs
of a `WITH RECURSIVE` clause.

The `feature_docs` workflow hook only recognized documentation embedded in a
few source trees. Since the SQL statement pages moved into the statement
registrations next to the parsers, `src/Parsers/` has to be recognized too -
otherwise a feature that documents itself there can only pass the hook by
editing the generated region of the page, which the autogenerated-region check
rejects.
Comment thread src/Analyzer/QueryTreeBuilder.cpp Resolved
Comment thread src/Analyzer/QueryTreeBuilder.cpp Resolved
The changelog entry already promised the feature would be experimental and
opt-in, but the syntax was accepted unconditionally. Add the setting, reject
`USING KEY` with `SUPPORT_IS_DISABLED` when it is not enabled, enable it in
`enableAllExperimentalSettings` so replica recovery can still recreate a view
that uses it, record it in `SettingsChangesHistory`, and cover the rejection
with a test.

This ticks the first item of the hardening checklist in the pull request
description. The documentation also now states the two remaining surface
caveats: `<cte_name>_settled` shadows a same-named table inside the recursive
members, and keyed evaluation produces no rows before convergence, so an outer
`LIMIT` cannot stop the recursion early.
@ArctypeZach
ArctypeZach marked this pull request as ready for review September 3, 2026 12:30
ArctypeZach and others added 2 commits September 3, 2026 10:11
`Block::cloneWithColumns` takes an immutable `Columns` by const reference,
so the `std::move` had no effect and clang-tidy rejects it
(`performance-move-const-arg`).
Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107070&sha=ab0859a504a3167ae0594b9f70a579d666dfffe1&name_0=PR&name_1=Build%20%28arm_tidy%29
PR: ClickHouse#107070

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The keyed evaluation upserted every produced row into the accumulated
state eagerly and appended every row that won at that moment to the next
step's working table. A key that changed and returned to its accumulated
value within one step therefore left the accumulated state unchanged but
the frontier non-empty, so the recursion never converged and failed with
`TOO_DEEP_RECURSION`. The frontier could also contain rows superseded
within the same step, which the recursive members then derived from.

Buffer the rows produced by a step and keep the last produced row per key
as the candidate for that key. At the end of the step compare each
candidate against the accumulated state: identical candidates are dropped,
the others replace the accumulated row and form the frontier. The frontier
is now exactly the difference between the accumulated state before and
after the step, and `<cte_name>_settled` stays consistent with it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@ArctypeZach

Copy link
Copy Markdown
Contributor Author

Pushed two follow-ups for the review comments and the arm_tidy failure:

  • 96802c3: cloneWithColumns takes Columns by const reference, so the std::move was a no-op flagged by performance-move-const-arg.
  • 472e816: the frontier issue is real and the repro above is right. The upsert compared each produced row against the latest row for its key within the same step and appended every momentary winner to the frontier, so a key that returned to its accumulated value within a step left the frontier non-empty, and the frontier could contain rows superseded within the step. The step output is now buffered with last-wins per key and diffed against the accumulated state at the end of the step, so the frontier is exactly the change of the accumulated state and <cte_name>_settled stays consistent with it. Regression cases: the arrayJoin([v + 1, v]) repro, a two-member case where a superseded row must not be derived from, and the last-wins rule, which is now also documented in the WITH reference.

The other review item, rejecting union-shaped non-recursive helpers marked MATERIALIZED, is fixed in #107069 (the check moved into resolveUnion), together with the materialization of helpers referenced only from the recursive member. This branch carries copies of the #107068 and #107069 commits without today's fixes; rather than duplicating them here I will merge master into this branch once those two land, and extend the working-table guard to <cte_name>_settled at that point.

@novikd novikd self-assigned this Sep 3, 2026
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
Buffering every row a step produces until the step ends made the per-step
memory proportional to the produced rows, while re-derived unchanged rows
are the common case in semi-naive evaluation. Compare each produced row
against the accumulated state while collecting, and only store the rows
that differ; a key whose last produced row is unchanged is remembered
without storing the row.

Also state in the `WITH` reference that the last produced row for a key
is only well-defined when the recursive member orders its result.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7e2a8f9a4 with master d31a6eff9 (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.

Object file sizes

73 object files changed (+128.46 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Sources/RecursiveCTESource.cpp.o 206.14 KiB 267.36 KiB +61.21 KiB (+29.69%)
src/CMakeFiles/dbms.dir/Analyzer/Resolve/QueryAnalyzer.cpp.o 1.78 MiB 1.81 MiB +31.80 KiB (+1.75%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +36.7 s (+6%) in total before that adjustment.

Job report

@ArctypeZach

ArctypeZach commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Two CI failures on this head are unrelated to the change:

Re-running individual jobs needs admin rights on the repository, so, as the CI documentation suggests, I pushed an empty commit to restart the checks.

After the restart (fd729de) every check passes except that last stress-test flake, so the remaining red mark is the known issue above.

@rschu1ze
rschu1ze removed their request for review September 3, 2026 20:29
Three checks failed on the previous head for reasons unrelated to this
change (an integration shard timeout, the Upgrade check mutation-log
error of ClickHouse#115416, and the
stress-test fuzzer failure of
ClickHouse#107619).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@abashkeev abashkeev added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Sep 4, 2026
ArctypeZach and others added 2 commits September 14, 2026 13:51
# Conflicts:
#	src/Core/Settings.cpp
#	src/Processors/Sources/RecursiveCTESource.cpp
alexey-milovidov and others added 2 commits October 28, 2026 21:46
…veCTESource`

Every row produced by a keyed recursive step serialized its key into the step
arena, even when the key was already produced during the step, so a step that
re-derives the same row many times retained memory proportional to all produced
key bytes. Now the duplicate serialization is rolled back and the stored key is
reused.

Also add a test for competing same-step paths to one node in the shortest-path
query.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e of `USING KEY`

Without `ORDER BY cost DESC` a more expensive candidate for a newly reached node
can overwrite the cheapest one produced in the same step.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
alexey-milovidov and others added 4 commits November 5, 2026 05:20
…les of a `USING KEY` recursive CTE

A scalar subquery or `EXISTS` is evaluated once during analysis, while the
working table and `<cte_name>_settled` are still empty, so it silently folded
a wrong constant (e.g. `(SELECT count() FROM t_settled) > 0` was false and the
recursion stopped after the seed). Reject such reads with `UNSUPPORTED_METHOD`
instead; `IN` and `JOIN` keep reading the state of every iteration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…` step

Every changed row was appended to the step candidates, and a later row with
the same key only made the earlier copy unreachable, so the candidate storage
grew with all produced rows. Compact the candidates after each chunk once at
least half of the rows are superseded, preserving last-wins semantics; the
amortized cost stays linear in the produced rows.

Add a test for this and for the rejection of scalar subqueries and `EXISTS`
reading the tables of a `USING KEY` recursive CTE.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@CLAassistant

CLAassistant commented Nov 5, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Dear @novikd, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

ArctypeZach and others added 3 commits November 10, 2026 16:23
# Conflicts:
#	ci/jobs/scripts/workflow_hooks/feature_docs.py
…EY recursive CTE

A produced row of a keyed recursive CTE is propagated only when it differs
from the accumulated row of its key, and the comparison is
`IColumn::compareAt`, which cannot establish equality for every type:
`ColumnAggregateFunction::compareAt` reports every pair of states as equal,
so a row whose only change was an aggregate state was dropped and the
recursion stopped early with a wrong result.

Reject such column types once the CTE is confirmed recursive and the
column types are final, using `isComparableForEquality` (which follows the
nested types of the container types) and additionally the variants of a
`Variant`. Document the restriction and add a test with the shape from the
review, nested `Tuple` and `Array` variants, and a plain-value control.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…n test

CI randomizes `execute_exists_as_scalar_subquery`; when it is off, `EXISTS`
is not folded during analysis and the query that expects the rejection of a
scalar read of `<cte_name>_settled` legitimately succeeds.
Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107070&sha=463d70db281ee681bf11f6585946ce419c084b44&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29
PR: ClickHouse#107070

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@ArctypeZach

Copy link
Copy Markdown
Contributor Author

Merged master (one conflict in feature_docs.py: master already lists src/Parsers/ as source-owned docs, so I took master's version). Also pinned execute_exists_as_scalar_subquery = 1 in 05508: CI randomizes it, and when it is off the EXISTS case is not folded during analysis and legitimately succeeds, which is what failed in the ASan targeted job on 463d70d.

ArctypeZach and others added 2 commits November 10, 2026 16:57
…EY columns

`isComparableForEquality` of a container type short-circuits to the
unconditional `true` of a nested `Variant`, so `Tuple(Variant(...))` and
`Array(Variant(...))` carrying an aggregate state slipped through, and
`Dynamic` and `JSON` hold values of types that are only known at run time,
aggregate states included. Walk the declared type tree with `anyInTypeTree`
and reject `Dynamic`, `JSON` and every nested type that cannot be compared
for equality. Cover these carriers in the test and the docs.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…rows too

Each update of a key appends a new accumulated row and marks the previous
one dead, but the compaction only ran once 8192 rows were stored, so a
recursion with one live key retained every previous payload across all its
steps. Compact as soon as the dead rows are at least half of the rows; each
compaction halves the rows at least, so the amortized cost stays linear.
Add a memory-limited test with a 1 MiB payload updated on every step.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature and removed pr-feature Pull request with new product feature labels Nov 10, 2026
@ArctypeZach

Copy link
Copy Markdown
Contributor Author

CI on 8e09f59: 117 checks pass; the only failing job is Build profile diff, whose log-cluster endpoint "never became ready" (LogClusterNotReady), so no comparison ran. No test or build failure.

@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Nov 23, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (no conflicts) and fixed the two CI failures on a2c2760:

  • Build (arm_tidy, 1/4..4/4): modernize-use-nodiscard on UnionNode::hasRecursiveCTEKeyColumns and UnionNode::getRecursiveCTEKeyColumns — marked both [[nodiscard]] (3d4c505).
  • Style check / settings_changes_history: the current version is now 26.12, so the history record of allow_experimental_keyed_recursive_cte moved from 26.11 to 26.12 (7e2a8f9).

The merged tree builds locally and the seven *_recursive_cte_using_key* tests pass.

{
while (true)
{
buildStepExecutor();

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.

[Blocker] Keep recursion-dependent IN sets out of the mutation cache

Rebuilding the executor does not rebuild an IN set when the inherited context has a PreparedSetsCache. MutatePlainMergeTreeTask::prepare installs that cache by default (enable_sharing_sets_for_mutations = 1), and Context copies retain it. CollectSets keys the set by the subquery's tree hash; TableNode::updateTreeHashImpl hashes the temporary table name, which stays unchanged when the settled table is refreshed. CreatingSetsTransform::startSubquery can therefore reuse the first iteration's set in every subsequent iteration.

A focused case to exercise in a background mutation is:

SET allow_experimental_keyed_recursive_cte = 1;
CREATE TABLE keyed_mutation (id UInt64, v UInt64)
ENGINE = MergeTree ORDER BY id;
INSERT INTO keyed_mutation VALUES (1, 0);

ALTER TABLE keyed_mutation UPDATE v =
(
    WITH RECURSIVE t USING KEY (k) AS
    (
        SELECT toUInt64(1) AS k
        UNION ALL
        SELECT k + 1 FROM t
        WHERE k < 3 AND k IN (SELECT k FROM t_settled)
    )
    SELECT max(k) FROM t
)
WHERE id = 1
SETTINGS mutations_sync = 2, enable_sharing_sets_for_mutations = 1,
         mutations_execute_subqueries_on_initiator = 0;
SELECT v FROM keyed_mutation;

The correct value is 3. With the cache path above, the first step caches {1} and produces 2; the next step tests 2 against that cached {1}, terminates, and persists 2. This is a source trace; no ClickHouse executable is available in this review job to run the reproduction.

Please prevent cross-iteration cache reuse for sets depending on either the working table or the settled table (including their nested query contexts), and add a mutation regression comparing set sharing enabled and disabled.

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-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RFC: Keyed recursive CTEs (settled-set semantics for graph traversal in recursive queries)

5 participants