Skip to content

Materialize a reused MATERIALIZED CTE before a parallel replicas read with a local plan sends it to the replicas - #123121

Merged
fm4v merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-materialized-cte-parallel-replicas-local-plan
Oct 13, 2026
Merged

fm4v merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-materialized-cte-parallel-replicas-local-plan

Conversation

@groeneai

@groeneai groeneai commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #112642
Related: #120022
Related: #120179

Changelog category (leave one):

  • Improvement

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

A query that reads a MATERIALIZED CTE more than once, for example inside an IN subquery, now works with parallel replicas when the initiator also reads locally (parallel_replicas_local_plan = 1). The other replicas no longer fail with UNKNOWN_TABLE on the CTE's temporary table. Closes #112642.

Description

05182_lightweight_update_materialized_cte_in_subquery and 05230_materialized_cte_shared_by_two_ctes_in_set_subquery fail with Code: 60 Unknown table expression identifier '_materialized_cte_c_...' in the ParallelReplicas lanes: FAIL on the arm_binary lane of #122853, and hidden as OK on master by the coverage flaky rule (example). With a 1M-row table the query from #112642 fails in 39 of 40 runs on master (the replicas fail in all 40).

The query sent to the replicas reads the CTE by its temporary table name, so the CTE must be written before it is sent. The initiator's local plan is built by its own planner and optimized first, so it claims the CTE's writer and gates only the local read. The remote read starts at once, sendExternalTables skips the unbuilt CTE, and the replicas throw.

The fix strips those CTEs from the local plan, so the outer plan's gate owns the writer and orders both reads. This is what ReadFromMerge already does for its child plans (#113558); the helper moves next to removeDelayedMaterializingCTEsStepFor so both callers share it.

Validation: the new test fails on master in all six shapes (two references, chain/diamond, UNION ALL, serialize_query_plan, subquery in FROM, parallel read inside another CTE) and passes 50/50 with randomized settings in the default and ParallelReplicas configurations. Removing the change or stripping only the directly named CTEs makes it fail again.

Not fixed here: #120022 (parallel_distributed_insert_select = 2 does not send external tables) and #120179.


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

Version info

  • Merged into: 26.10.1.2331-master (included in 26.10 and later)

groeneai and others added 2 commits September 30, 2026 17:19
…the replicas

A MATERIALIZED CTE read more than once is an external table of the query
context, and the query sent to the other replicas names its temporary
table, so `RemoteQueryExecutor::sendExternalTables` must find it built.
It skips a CTE that is not built yet.

`executeQueryWithParallelReplicas` builds the initiator's local plan with
its own (non-subquery) planner over a clone of the shipped query tree, so
the local plan plants its own `DelayedMaterializingCTEsStep`. That plan is
hidden in `ReadFromLocalParallelReplicaStep` and optimized before the
outer plan's `resolveMaterializingCTEs`, so it claims the writer and gates
only the local read. The remote read is the other input of the `Union`,
starts immediately, the CTE is skipped and every other replica fails with
`Unknown table expression identifier '_materialized_cte_...'`. The query
only survives when the local replica finishes first and the unused
replicas are cancelled, which is why `05182` and `05230` fail on ~1-2% of
ParallelReplicas-lane runs and the query from ClickHouse#112642 fails every time on
a 1M-row table.

Strip the delayed steps of every CTE of the shipped tree from the local
plan, the same fix `ReadFromMerge` applies to its child plans (ClickHouse#113558),
so the outer plan's gate owns the writer and orders both reads. The set is
transitive: a CTE read only inside another CTE's body must be stripped
too, otherwise that CTE's writer, now under the outer gate, reads a CTE
whose writer stays in the local branch. The collector moves from
`StorageMerge.cpp` to `MaterializingCTEStep` so both callers share it.

Closes ClickHouse#112642

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the call-site line that narrated why the local plan would claim the CTE writer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test could pass without reaching the local-plan parallel replicas path if path-selecting settings decline it DISAGREE The runner randomizes only parallel_replicas_local_plan and automatic_parallel_replicas_mode, both pinned by the test; parallel_replicas_plan_based, parallel_replicas_allow_in_with_subquery and parallel_replicas_min_number_of_rows_per_replica keep their path-taking defaults in every CI config. Master fails all six shapes, and removing the one-line fix fails the test 5/5.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-10:20260930-172300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The query from #112642 on a 1M-row table fails in 39 of 40 runs on master (the replicas fail in all 40); each shape of the new test fails 10/10 on master (the CTE body sleeps, so the other replicas always start first).
b Root cause explained? The local plan of a parallel replicas read is optimized before the outer plan, claims the CTE writer and gates only the local read; the remote read starts at once and sendExternalTables skips the unbuilt CTE, so the replicas fail with UNKNOWN_TABLE.
c Fix matches root cause? Yes. The local plan no longer owns the writer of any CTE the replicas read, so the outer gate orders both reads. Same pattern as ReadFromMerge (#113558).
d Test intent preserved / new tests added? New 05296 (six shapes + a query_log check for discarded replica errors). 05182 and 05230 unchanged.
e Both directions demonstrated? Yes: master fails every shape, the fix passes 50/50 in the default and ParallelReplicas configurations. Removing the change, or stripping only the directly named CTEs, makes the test fail again.
f Fix is general across code paths? One helper shared with ReadFromMerge. Covers the join-tree path, a subquery in FROM, serialize_query_plan, INSERT SELECT and a parallel read inside another CTE. Not covered: #120022, #120179.
g Fix generalizes across inputs (params/datatypes/wrappers)? Direct references, chain, diamond, UNION ALL; 5 rows and 1M rows; parallel_replicas_local_plan 1 and 0; randomized settings.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change.
i Invariants and contracts preserved? Only the delayed steps for CTEs of the shipped query tree are removed; other CTEs stay with the local plan. No missing-gate error in a 288-test parallel replicas / materialized CTE sweep.

Session id: cron:clickhouse-impl-slot-7:20260930-153900

@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [eb9385e]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: Reading from materialized CTE 'A' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan (STID: 2467-34d3) FAIL cidb IGNORED
Integration tests (arm_binary, 1/4) FAIL
test_storage_delta/test.py::test_writes_timestamp_ntz_annotation_nested FAIL cidb, issue ISSUE EXISTS
test_storage_delta/test_writes_interop.py::test_write_to_table_with_unsupported_writer_feature_is_rejected FAIL cidb IGNORED

AI Review

Summary

This PR fixes the parallel-replicas/local-plan race for MATERIALIZED CTEs by stripping the relevant delayed CTE steps from the initiator-local plan so the outer gate owns materialization for both the local and remote branches. The implementation matches the existing ReadFromMerge pattern, but the new regression test’s query_log assertion is not scoped to this test run, so it can fail on unrelated earlier UNKNOWN_TABLE rows from the same database.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/05296_parallel_replicas_materialized_cte_in_set_subquery.sql:60] The final query_log check scans every initial query in currentDatabase() for the whole event_date >= yesterday() window, so an unrelated follower-side UNKNOWN_TABLE from an earlier stateless query can make this test fail spuriously.
    Suggested fix: fence the assertion to this test’s own queries with a per-run marker such as event_time >= run_start, a dedicated log_comment, or captured query_ids.
Final Verdict
  • Status: ⚠️ Request changes
  • Scope the final query_log assertion to this test run; after that, this looks ready.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). labels Sep 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit eb9385ea5c2c171fc306ef3a63c87e1397b10baa was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - abc4f98

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, parallel) / 05255_filter_output_evaluated_before_its_filter flaky, randomized MergeTree settings (index_granularity 1493, min_bytes_for_wide_part 0, optimize_on_insert False; 208 of 208 reruns fail with them, 232 of 232 pass without). The final RuntimeFilterRowsChecked >= 2000 check misses the rows the runtime filter skips once it disables itself. The test has no parallel replicas and no materialized CTE, so the code this PR changes is not on its path #123135 (mine, open)
Mergeable Check, PR rollups, red only because of the row above #123135 (mine, open)

146 of 146 check runs completed (104 passed, 41 not selected, 1 red: the shard above), Finish Workflow is green and CH Inc sync passed. CIDB has one FAIL test row on this head, the one above.

Session id: cron:our-pr-ci-monitor:20260930-223102

superdiaodiao pushed a commit to superdiaodiao/ClickHouse that referenced this pull request Oct 1, 2026
The last assertion checked `RuntimeFilterRowsChecked >= 2000` to prove the
runtime filter was applied to the t1 side (2001 rows) rather than to t2
(5 rows). Every t1 row passes the filter, so after a block whose pass ratio
exceeds join_runtime_filter_pass_ratio_threshold_for_disabling (0.7) the
filter skips later blocks within its budget (rows checked times
join_runtime_filter_blocks_to_skip_before_reenabling) and books them in
RuntimeFilterRowsSkipped, not in RuntimeFilterRowsChecked.

With the default layout t1 arrives in one block, so at most one row is
skipped. With optimize_on_insert = 0 the part has level 0 and FINAL reads it
through the merging path; with a wide part and index_granularity = 1493 that
read yields a 1493-row and a 507-row block, and RowsChecked is 1494. This is
what failed in Stateless tests (arm_binary, parallel) on PR ClickHouse#123121, where
the runner's diagnosis narrowed it to these three settings (208/208 failing).

In the failing job's query_log, Checked + Skipped was 2001 on all 470
executions of the probe, across every layout the runner tried. Sum the two
counters. The threshold still separates t1 from the reversed join
orientation (5) and from a filter that is planted but never applied (0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merged via the queue into ClickHouse:master with commit 74ed031 Oct 13, 2026
174 of 177 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 13, 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-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-improvement Pull request with some product 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.

Materialized CTE referenced twice + parallel replicas: replica gets the initiator's _materialized_cte_* temp table name and throws UNKNOWN_TABLE

4 participants