Repository navigation
Recursive CTE: experimental USING KEY (keyed recursion / semi-naive evaluation) - #107070
ArctypeZach wants to merge 44 commits into
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]>
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]>
|
Workflow [PR], commit [7e2a8f9] Summary: ❌
AI ReviewSummaryAdds experimental Findings❌ Blockers
Missing context / blind spots
Tests
Final VerdictStatus: ❌ Block Prevent stale set reuse across recursive iterations and validate the mutation regression. |
|
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. |
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.
`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.
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.
`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]>
|
Pushed two follow-ups for the review comments and the
The other review item, rejecting union-shaped non-recursive helpers marked |
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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes73 object files changed (+128.46 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units124 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. |
|
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. |
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]>
# Conflicts: # src/Core/Settings.cpp # src/Processors/Sources/RecursiveCTESource.cpp
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…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]>
…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]>
…Y` recursive CTE Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
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. |
# 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]>
|
Merged master (one conflict in |
…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]>
`repeat` allows at most 1000000 repetitions. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107070&sha=6fc9650d81343d7563195c10808c3d3dfcada523&name_0=PR&name_1=Fast%20test PR: ClickHouse#107070 Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
CI on 8e09f59: 117 checks pass; the only failing job is |
`hasRecursiveCTEKeyColumns` and `getRecursiveCTEKeyColumns` failed the `arm_tidy` builds with `modernize-use-nodiscard`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107070&sha=a2c27600319652e882cb56dcd585bc5a46992621&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29 ClickHouse#107070 Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ttings history The current version is 26.12 after the merge of `master`, so the `settings_changes_history` style check rejected the `26.11` record of the new setting. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107070&sha=a2c27600319652e882cb56dcd585bc5a46992621&name_0=PR&name_1=Style%20check ClickHouse#107070 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged
The merged tree builds locally and the seven |
| { | ||
| while (true) | ||
| { | ||
| buildStepExecutor(); |
There was a problem hiding this comment.
[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.
Resolves #107067
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Add experimental
USING KEYclause 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. Behindallow_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 DISTINCTis thedegenerate case where the key is all columns.
Semantics.
last write wins;
ORDER BYin the recursive member controls the survivor).path arrays.
<cte_name>_settledis visible inside recursive members: the accumulated state (one row per key) asof the previous iteration, enabling strict-improvement refutation (label-correcting Dijkstra).
Implementation. Parser (
ParserWithElement/ASTWithElement.key_columns), analyzer(
resolveUnion: key validation, settled temp table + scope injection, integrated with the iterativetype-widening passes),
UnionNode/RecursiveCTETableplumbing (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_SIZEchunks).Benchmarks (same binary/host; identical optimal results where both complete):
USING KEY= 0.038 s.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 withsettled 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):
allow_experimental_keyed_recursive_ctesettingclickhouse-formatandparseQueryToJSON/formatQueryFromJSONround-trip tests for the new syntaxORDER BYcontrol, single-thread determinism)std::unordered_mapwithHashMap; memory-account the accumulated state<name>_settledshadowing (the final surface,_settledsuffix vsrecurring.<name>, is still open)LIMITinteraction (keyed evaluation buffers to convergence; no partial early-stop)WITHstatement (the page moved into its statement registration inParserWithElement.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]