Skip to content

Derive the join order randomization seed from the initial query id - #112660

Merged
alexey-milovidov merged 15 commits into
ClickHouse:masterfrom
groeneai:fix-6117-68e9-coordination-mode-mismatch
Sep 27, 2026
Merged

alexey-milovidov merged 15 commits into
ClickHouse:masterfrom
groeneai:fix-6117-68e9-coordination-mode-mismatch

Conversation

@groeneai

@groeneai groeneai commented Jul 30, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Not for changelog: query_plan_optimize_join_order_randomize is intended for debugging only.

Description

Reported on #107567 as STID 6117-68e9, tracked by #106039: CI report.

query_plan_optimize_join_order_randomize = 1 means "derive a random seed", but the substitution happened in the QueryPlanOptimizationSettings constructor while the session value stayed 1. That constructor runs once per plan construction, and one query builds several plans: one per scalar subquery, and one per replica under parallel replicas, because a replica re-plans what it receives. Each plan therefore rolled its own seed.

The seed feeds getRandomizedStats, which replaces the relation statistics, so a different seed picks a different leftmost relation. findReadingStep descends only children.front(), so a different table gets requestReadingInOrder and announces a different CoordinationMode for one stream. stream_to_coordinator is keyed by table name alone, so the second announcement throws Coordination mode mismatch for stream; the abort dump carries both preconditions.

The fix derives the seed from initial_query_id, which is stable for one query and reaches remote replicas in ClientInfo. 0 (the default) and explicit seeds above 1 are untouched, and an empty initial_query_id, which an internal or background plan carries, keeps the old random seed. Measured on a three-replica cluster: one initial query id gave 3 distinct seeds before the fix and 1 after, with the join result unchanged.

This removes one carrier of the class, not all of them: per-replica real statistics and the process-global hash table statistics cache can also split the join order without this setting. Neither was active in the reported abort. The stateless test that shipped with the first revision is dropped at the reviewer's request, #112660 (comment).


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

Version info

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

groeneai and others added 10 commits July 29, 2026 18:53
`query_plan_optimize_join_order_randomize = 1` means "derive a random seed",
but the substitution happened in the `QueryPlanOptimizationSettings`
constructor while the session value stayed `1`. That constructor runs once per
query plan construction, and one query builds several plans: one per scalar
subquery, one per `Merge` child, and, under parallel replicas, one per replica,
because `serialize_query_plan` is off by default so every replica re-plans the
query text it receives. Each of them rolled its own seed.

The seed feeds `getRandomizedStats`, which replaces the relation statistics, so
a different seed picks a different leftmost relation. `findReadingStep` descends
only `children.front()`, so a different table then receives
`requestReadingInOrder` and announces a different `CoordinationMode` for the
same stream. Since `stream_to_coordinator` is keyed by the table name alone, the
second announcement throws `Coordination mode mismatch for stream` in
`ParallelReplicasReadingCoordinator::getOrCreateCoordinator`. This has been
firing across many unrelated PRs; the abort dump on the run reported in ClickHouse#107567
contains both preconditions (`query_plan_optimize_join_order_randomize = 1` and
`parallel_replicas_local_plan = false`).

Derive the seed from `initial_query_id` instead. It is stable for one query and
is propagated to remote replicas in `ClientInfo`, so every plan of one query
derives the same seed while different queries still explore different orderings.
The derived value is forced above 1 so it can never read back as the sentinel
(1) or as disabled (0). An empty initial query id keeps `randomSeed()`: an
internal or background plan has no query to be consistent with and no
parallel-replica fan-out to diverge from. `0` (the default) and explicit seeds
above 1 are untouched, so any query that does not opt into randomization is
bit-identical. As a side effect a `= 1` run becomes reproducible, which is what
the setting's own doc string asks for.

Measured against a three-replica cluster, counting seeds across all replica
query ids of one initial query id: 3 distinct seeds before, 1 after,
deterministic over repeated runs.

This removes one carrier of the failure class, not all of them. The
process-global hash-table statistics cache and per-replica real statistics can
still diverge join order for a query that does not set this setting; both were
inactive for the reported abort, and they are followed up separately.

Related: ClickHouse#106039
Review round 1 on the join-order-randomize seed fix.

The regression test asserted that one query gets one seed, but not that the
seed is the value derived from the initial query id. A compile-time constant
seed satisfies uniqueness within a query and across replicas, so it would have
passed every assertion while silently removing the cross-query randomization
the setting exists for. Each of the two affected cells now also compares the
logged seed against greatest(sipHash64(<initial query id>), 2), reusing that
cell's existing query_id subquery so the two rows cannot drift apart. SQL
sipHash64 over a String hashes the same bytes as the C++ overload, with no
terminator, and greatest(..., 2) is UInt64, so the comparison reproduces the
clamp exactly; this was measured before being asserted. A mutation replacing
the hash with a constant now reddens exactly those two rows and nothing else.

The setting description claimed the change "keeps a run reproducible". That is
false as a user-facing statement: rerunning the same query text mints a new
initial query id and therefore a new seed, so reproducibility requires an
explicit query id. The description is published through system.settings, so it
now states only what holds, and also covers the empty initial query id case
that falls back to a random seed.

The comment at the fix site kept the incident narrative that belongs in the
commit message and the pull request description, so it is reduced to the
invariant and the reason for the clamp. The code lines are unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
… guarantee

The description claimed that rerunning the same query text "still explores a
different ordering". The change only guarantees a new seed: the chosen order is
a hash of (seed, relation index, table name) over a finite set of orderings, so
two distinct seeds can legitimately select the same order. The regression test
added by this branch records a measured instance of exactly that, naming seeds
12345 and 54321 as colliding for its table names, so the published text
contradicted the diff's own test comment.

The text now promises a new seed and says the ordering may differ, and points
at an explicit query id as the way to keep the seed stable. The other four
claims are unchanged: derivation from the initial query id, sharing with remote
replicas, the empty-id fallback to a random seed, and the verbatim use of a
value above 1.

The description reaches users through system.settings.description and the
generated settings page, which is why the wording is corrected rather than left
to the PR body.

Co-Authored-By: Claude Fable 5 <[email protected]>
…sertion

The guard read `uniqExact(query_id) > 1` under the label "cell C fanned out to
several replicas". The predicate is correct for what it can observe, but the
label promised more than it delivers: the initiator's own row is always one of
the counted ones, so the check cannot distinguish "initiator plus one remote"
from "initiator plus two remotes". Measured directly, it stays green with
`max_parallel_replicas = 2`, so it does not notice a degraded fan-out.

The predicate is kept verbatim and relabelled to the property it does pin, the
same wording cell A already uses for the same fact: the query really did
construct more than one plan. That is what protects the two substantive cell C
rows from passing vacuously on a single matching row.

The fan-out itself is now asserted separately from
`ProfileEvents['ParallelReplicasAvailableCount']` on the initiator's own
`query_log` row. That counter is incremented once per replica that actually
joined the query, and it is accumulated in the initiator's own process, so it
does not depend on when the replicas' `query_log` rows become visible. An
earlier attempt to count the remote rows themselves was 35% flaky for exactly
that reason: `SYSTEM FLUSH LOGS` flushes the local queues only and has no
cross-replica barrier, so at the moment the initiator flushes some replica rows
may not be enqueued yet. The similarly named `ParallelReplicasUsedCount` counts
per replica that requested ranges and reads 1 here, so it is not the right
event.

The observing statement pins `enable_parallel_replicas = 0` because cell C sets
it at session level, matching what `02950_parallel_replicas_used_count` does for
its own observers.
…re-planning comment

Round 4 of review. Two test-only changes, no behaviour change.

The cell C fan-out row read `ProfileEvents['ParallelReplicasAvailableCount'] = 3`. That counter is
incremented in the connection-establishment loop of RemoteQueryExecutor, before `sendQuery`, so it
counts compatible connections rather than plan constructions that agreed on the seed. Replace it
with a row that counts distinct plan constructions carrying this query's derived seed. The scope is
the seed value computed from the initiator's own `query_log` row, which is always locally visible;
joining the replicas' rows instead races their `query_log` flush, because `SYSTEM FLUSH LOGS` has
no cross-replica barrier.

The header comment claimed a replica re-plans because `serialize_query_plan` is off by default.
That reason does not hold on the `distributed plan` functional jobs, which enable the setting in
the default profile. The mechanism that holds on both paths is that `JoinStepLogical::serialize`
does not encode the `optimized` flag, so the join-order rewrite runs again on the replica whether
it receives the query text or a serialized plan. State that instead; the setting is deliberately
left unpinned so the serialized-plan path keeps its coverage.

Co-Authored-By: Claude Fable 5 <[email protected]>
…e query_log lookups

Three test-only changes to the 04653 regression test, all requested by review.

Split the cell C non-vacuity assertion in two. It previously loaded two independent
properties onto one inequality: that several plan constructions agreed on the derived
seed, and that the fixture fanned out to the configured replica count. The population
that carries the derived seed is one initiator plan construction plus one per replica,
so over a population of max_parallel_replicas + 1 no single bound can express both, and
"secondary replica participation" cannot be expressed at all. Each property now has its
own row with a bound that means what its label says: a >= 2 seed-agreement bound, and an
exact = 4 fan-out bound deliberately coupled to max_parallel_replicas = 3. Reducing the
replica count to 2 reddens only the fan-out row, which is what the split is for.

Pin the join swap setting on both EXPLAIN statements of the cell B reorder oracle. That
oracle compares the read orderings produced by two different explicit seeds, and a forced
swap changes the read order independently of the seed, so the row failed for every forced
value of the setting. Both the functional runner and the stress runner randomize it, and
the existing no-random-settings tag does not protect against the stress runner, which
injects through a client option that wins over the randomized value. Statement-level
scope is used so cells C and B2 keep exercising the default.

Order the four expected-seed lookups over system.query_log by event time, descending.
That table is server-global and append-only, and a stress thread runs with a fixed
database, so an unordered single-row pick could hash a previous run's query id. The
ordered form is deterministic and selects the newest run's initiator.
The runner re-runs a failed test in the supplied database without cleaning it
(tests/clickhouse-test wraps every execution in a retry loop, and TestCase._cleanup
is gated on `not args.database`), and a stress thread supplies a fixed --database.
One database can therefore hold several attempts of this test.

The observed side of six assertions joined `system.text_log` through every initiator
of a `log_comment` in the database, so it saw one derived seed per attempt: the
`uniqExact(...) = 1` rows measured the attempt count and the `groupUniqArray`
comparisons compared a multi-element array against a single-element one. Both
reddened permanently on the second attempt, reporting a correct fix as broken.

Reuse the ordered newest-initiator lookup that the expected side already used, as
the `initial_query_id` filter rather than as a comparison operand. This keeps every
assertion non-circular and changes no row's value, only its scope.

The two cell B sites are left unscoped deliberately: an explicit constant seed
cannot gain a distinct element from accumulated history, and a `count() = 0`
population over `randomize = 0` stays empty however many attempts run.
Cell C sets `parallel_replicas_local_plan = 0`, and on that branch the replicas
receive query text rather than a serialized plan: `createRemotePlanForParallelReplicas`
is reached only inside the `canUseLocalPlanForParallelReplicas` branch and only under
`serialize_query_plan`, and the `else` branch passes no plan at all, so
`ReadFromRemote` selects the query-text stage. The test therefore covered only the
re-plan-from-text path, on every job.

Add a cell that ships a serialized plan. The receiver re-optimizes it, so the
join-order rewrite runs there too and must derive the same seed. `serialize_query_plan`
is pinned explicitly so the cell exercises the path on every job rather than only on
one whose profile enables it, and the settings are statement-level so the existing
cell C rows keep measuring the query-text path.
A population filtered by the seed value cannot observe a plan construction
that derived a different seed, because such rows are filtered out by
definition. Cell C2 was the only cell whose sole assertion was scoped that
way, so it could not fail on the seed disagreement this change is about.

Scope it by initial_query_id and compare the whole observed set against the
single derived value, mirroring the shape cell C already uses. One row then
asserts both halves: the constructions agreed, and they agreed on the
derived value.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Cell C2 asserted that every plan construction of a serialized-plan query derives
the same seed, but that held on the query-text fallback too: a replica that
re-plans the query text derives the SAME seed from the same propagated
initial_query_id, so removing the serialize_query_plan pin left the cell green
and the path it exists to cover was unwitnessed.

The discriminator is the number of plan constructions. A receiver that
deserializes a plan constructs QueryPlanOptimizationSettings twice
(executeQuery.cpp:1980 and :1987 - the second passes do_optimize = false, but the
object is built at the call site, so both log the seed), while a replica
re-planning the query text constructs it once
(InterpreterSelectQueryAnalyzer.cpp:403). The initiator is excluded from the
population because it constructs twice on both paths whenever
parallel_replicas_local_plan is set, which cell C2 must pin; the guard precedes
the construction (InterpreterSelectQueryAnalyzer.cpp:184 returns early for a
secondary query, the construction is at :192), so the initiator is exactly the
one participant that can double without deserializing.

Both subqueries read the initiator's own always-visible query_log row, the same
row the seed subquery already reads, so the new row needs no join against the
replicas' query_log, whose flush this test cannot force.

Removing the cell C2 serialize_query_plan pin now reddens this row and only this
row. Measured 20 OK / 0 FAIL over 20 randomized runs and 3 OK / 0 FAIL in a
reused database; the population is 4 constructions across 2 replica ids on the
serialized-plan path and 2 across 2 on the query-text path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@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; 16 findings across 8 review
passes; 10 fix rounds, each pass re-reviewing the full scope). The final pass returned 0
findings. Cumulative verdicts over the whole PR: 30 AGREE, 4 DISAGREE, 1 DEFERRED.

The findings below are the substantive ones. Every AGREE was fixed and re-verified; every
DISAGREE carries a recorded citation or measurement.

# Sev Finding Verdict Evidence / action
1 ⚠️ The test asserted only that one seed was used, which a constant seed would also satisfy AGREE, fixed Added an oracle comparing the logged seed against the SQL reconstruction greatest(sipHash64(<initial query id>), 2), verified empirically before being written into the test
2 ⚠️ The setting doc string promised a stable join ordering, which the fix does not guarantee AGREE, fixed Weakened to a statement about the seed, and documented that rerunning the same text gets a new id
3 ⚠️ The parallel-replicas non-vacuity guard bounded two different properties with one assertion AGREE, fixed Split into a plan-count assertion and a fan-out assertion, each labelled with what it measures
4 ⚠️ The reorder control could be perturbed by the runner randomizing query_plan_join_swap_table AGREE, fixed Pinned the setting on that oracle only, so a forced swap cannot masquerade as a seed effect
5 ⚠️ An unordered query_log lookup could hash a previous attempt's query id after a retry AGREE, fixed Both sides of every seed assertion are now scoped to the newest initiator
6 ⚠️ The serialized-plan replica path was never exercised, only the query-text path AGREE, fixed Added a cell pinning serialize_query_plan = 1, plus a discriminator that fails on the query-text fallback
7 ⚠️ The seed-scoped population could not observe a construction that derived a different seed AGREE, fixed Rescoped that assertion to the query and compared the whole observed set against the single derived value
8 ⚠️ Three mutation counts stated in this description did not match the measurements AGREE, fixed Re-measured from the logs and corrected: the revert reddens 8 assertions, the constant hash 6
9 ⚠️ An assertion on ParallelReplicasUsedCount would be a per-replica counter, not a fan-out count DISAGREE Measured 1, not 3, on a three-replica run, so the proposed oracle would have been wrong; used distinct plan-construction query ids instead
10 💡 Removing the clamp that forces the derived seed above 1 reddens no assertion DISAGREE Correct but not fixable: it fires only when the hash is 0 or 1, probability 2/2^64. Disclosed in the description rather than hidden

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-51:20260730-200100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, three independent deterministic observables, no probabilistic claim anywhere. (1) One clickhouse local command, no server: one query with three scalar subqueries over the same 3-way join at query_plan_optimize_join_order_randomize = 1 logs 2 distinct seeds. (2) Against a server, counting seeds for a single query id: 2 distinct, 5 of 5 runs. (3) Against a three-replica cluster, seeds counted across all replica query ids of one initial query id: 3 distinct, 3 of 3 runs.
b Root cause explained? Yes. The = 1 sentinel was resolved with randomSeed() in the QueryPlanOptimizationSettings constructor while the session value stayed 1. That constructor runs once per query plan construction, and one query builds several plans (scalar subqueries, Merge children, and one per replica since serialize_query_plan is off by default so every replica re-plans the query text). Each rolled its own seed; the seed feeds getRandomizedStats, which replaces the relation statistics, so swap_on_sizes picks a different leftmost relation; findReadingStep descends only children.front(), so a different table receives requestReadingInOrder and announces a different CoordinationMode; stream_to_coordinator is keyed by the table name alone, so the second announcement throws in getOrCreateCoordinator. The abort dump on the reported run contains both preconditions (query_plan_optimize_join_order_randomize = 1, parallel_replicas_local_plan = false).
c Fix matches root cause? Yes. The defect is that the sentinel is resolved once per plan construction instead of once per query, so the fix changes what it resolves to at that exact point rather than moving it. No band-aid: no widened bound, no no-random-* tag on the carrier test, no downgraded assertion, no defensive check at the throw site. The alternative of pinning eight plan-shape settings off for parallel replicas was rejected because it would delete the randomization's coverage for exactly the configuration that wants it.
d Test intent preserved / new tests added? Yes. No existing test weakened, retagged or removed. New stateless test 04653_join_order_randomize_seed_stable with 13 assertion rows: 6 target assertions (per cell: the seed is unique for the query, and it EQUALS the derived value greatest(sipHash64(<initial query id>), 2); plus two serialized-plan cell C2 rows: one asserting the same derived seed, and one asserting that the replicas really received a serialized plan rather than query text, by counting plan constructions per replica id), 4 non-vacuity guards (per cell, that the query really constructed more than one plan; plus, for the parallel-replicas cell, that the configured fan-out really happened, uniqExact(query_id) = 4 over the population carrying the derived seed, which is scoped on the seed value computed from the initiator's own query_log row so it does not depend on when the replicas' own rows become visible) and 3 must-not-change controls (explicit seed used verbatim; two distinct explicit seeds still reorder; = 0 derives no seed at all). The two derivation assertions exist because uniqueness alone is also satisfied by a compile-time constant seed, which would silently delete the cross-query randomization the setting exists for. The SQL oracle was verified to reproduce the C++ derivation exactly before being asserted: sipHash64 on a String hashes the same bytes with no terminator (sipHash64('ab') = sipHash64(toFixedString('ab',2)) is 1, against toFixedString('ab',3) it is 0) and greatest(..., 2) is UInt64, matching the C++ clamp. The observed side of six assertions is scoped to the NEWEST initiator, because the runner re-runs a failed test in a supplied --database without cleaning it (tests/clickhouse-test:4619-4650; _cleanup is gated not args.database at :3818-3821; stress.py:161 supplies one), so an unscoped observed side would see one correctly-derived seed per attempt and redden permanently: measured 3 attempts -> uniqExact(seed) 3 unscoped vs 1 scoped, and a 3-run fixed-database arm goes from runs 2+3 FAIL to 3 OK / 0 FAIL.
e Both directions demonstrated? Yes, via clickhouse-test on Build-ID-verified binaries (pre-fix 2c3b80cd, an in-tree revert of the fix to the merge-base; fix 64d5c772). Pre-fix the test FAILS on all four seed assertions (both uniqueness rows and both derivation rows, 1 -> 0), with both non-vacuity rows and all three controls still green; with the fix it passes, and randomized runs pass at 50/50 and 20/20. Four discriminating mutations. Two on src/, each rebuilt with a moved Build ID and then restored bit-identically: reverting the derivation to randomSeed() (6936499e) re-reddens all four seed rows; replacing the hash with a constant seed (bf01949a) reddens exactly the two derivation rows and nothing else, the measurement showing those rows close a hole the uniqueness rows structurally cannot see. Two on the test: reverting the newest-initiator scoping reddens exactly the four run-sensitive rows on attempts 2 and 3 of a shared database; and removing the cell C2 serialize_query_plan pin reddens exactly one row and nothing else, the row that counts plan constructions per replica id (a receiver that deserializes a plan constructs QueryPlanOptimizationSettings twice, executeQuery.cpp:1980 and :1987, where a replica re-planning the query text constructs it once, InterpreterSelectQueryAnalyzer.cpp:403; the initiator is excluded because parallel_replicas_local_plan, which this cell must pin, doubles it on both paths). Measured 4 constructions across 2 replica ids on the serialized-plan path against 2 across 2 on the query-text path. On the final tree the two src/ mutations redden 8 rows (derivation -> randomSeed()) and 6 rows (hash -> a constant) respectively.
f Fix is general across code paths? Yes, fixed at the single source of the nondeterminism, so all five passes that can call requestReadingInOrder (read-in-order, aggregation-in-order, distinct-in-order, limit-by-in-order, window storage-ordering reuse) are covered uniformly with no per-pass change. Verified this run rather than assumed: tryReuseStorageOrderingForWindowFunctions only consumes the order and seeds nothing; ReadFromObjectStorageStep has zero InitialAllRangesAnnouncement references so it announces no stream; ReadFromMerge is unreachable under parallel replicas (StorageMerge is not isMergeTree). Sibling sentinels of the same shape: grep -rn "randomSeed()" src/Processors/QueryPlan/ src/Core/Settings*.cpp src/Interpreters/Context.cpp finds only this site plus a load-balancing priority function, which is not a plan-shaping setting, so there is nothing to fold in.
g Fix generalizes across inputs (params/datatypes/wrappers)? The input is one UInt64 setting, so the meaningful matrix is its value domain, and all four regions are covered by the test: 0 (disabled, control), 1 (the sentinel, now with both a uniqueness and a derivation assertion per cell), > 1 (explicit seed honoured verbatim, control), and the derived-value edge (the clamp forcing the value above 1). The second input axis is the plan multiplicity the seed must span, and both of its forms are covered: several plans within one process (three scalar subqueries, cell A) and several plans across processes (three replicas each re-planning, cell C, where the replicas carry distinct query_ids and must all hash the initial one). Type wrappers, NULL and container matrices do not apply to a scalar setting. Disclosed: the clamp fires only when the hash of the query id is 0 or 1 (probability 2/2^64), so no test can provoke it, and the mutation that removes it correctly reddens nothing.
h Backward compatible? (maintainer-approved exception only) Yes. No default changes: the default is 0 and the enclosing if only runs when the value is exactly 1, so every query that does not opt into randomization is bit-identical. No serialization change, no protocol change, therefore no new SettingsChangesHistory.cpp entry is required. Verified rather than assumed: the only existing entry for this setting is the 0, 0 line from when it was added, which needs no edit. The setting is EXPERIMENTAL and test-only by its own doc string; the behaviour change for = 1 users is that the seed becomes consistent across the plans of one query instead of being redrawn per plan construction. It does not make a rerun reproducible, because a rerun mints a new initial query id and therefore a new seed; the doc string says so explicitly rather than claiming reproducibility.
i Invariants and contracts preserved? Yes. The constructor's postcondition (the field is either 0 or a usable seed above 1) is strengthened, not weakened: the clamp makes the derived value provably outside {0, 1}. initial_query_id_ is a by-value String parameter and is hashed before the member assignment further down the constructor, so there is no lifetime or ordering question; the empty-id case is an explicit branch rather than an implicit hash of the empty string. No allocation, no lock, no new error path or early return is introduced, and nothing about abnormal-termination or restart re-entry applies because the value is RAM-only per-plan state. Downstream readers were enumerated: optimizeJoin.cpp (effective_randomize_seed) and DistributedPlanExecutor.cpp, which force-sets the field to 0 for its own reason and is unaffected.

Session id: cron:clickhouse-impl-slot-7:20260729-180650

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin @devcrafter, could you review this? query_plan_optimize_join_order_randomize = 1 resolved its "derive a seed" sentinel inside the per-plan-construction QueryPlanOptimizationSettings constructor while the session value stayed 1, so every plan of one query rolled its own seed; since the seed replaces the relation statistics via getRandomizedStats, replicas picked different join orders and announced conflicting coordination modes for one stream. The seed is now derived from initial_query_id, which already reaches replicas in ClientInfo.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [69413a3]

Summary: ✅


AI Review

Summary

This PR changes query_plan_optimize_join_order_randomize = 1 to derive its seed from initial_query_id instead of calling randomSeed once per plan construction, which matches the bug report and looks correct in the touched code. I did not find a new correctness problem in the implementation, but the current tree still has no focused regression that would fail if this hunk reverted to per-plan seeding.

Findings
  • ⚠️ Major: [dismissed by author -- https://github.com/Derive the join order randomization seed from the initial query id #112660#discussion_r4093825350] [src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.cpp:226] The fix changes the contract of the = 1 sentinel, but there is still no committed test that distinguishes the new per-initial_query_id derivation from the old per-plan randomSeed behavior. 04050_join_order_randomize covers only explicit seeds, while the remaining = 1 tests (04277_join_reorder_constraints, 04337_cross_left_join_transitive_predicates, 04545_correlated_subquery_in_set_speculative_build) only assert result correctness and would stay green if this branch went back to fresh per-plan seeds. Because the original failure required one query to build several plans, the proof here still needs a minimal regression that forces multiple plan constructions within one initial query and asserts a single derived seed or an equivalent stable plan-shaping effect.
Final Verdict

The code change itself looks sound, but I would keep the PR open until there is a focused regression test for the query_plan_optimize_join_order_randomize = 1 behavior.

LLVM Coverage Report

Measured on commit 69413a3.

Metric Baseline Current Δ
Lines 88.10% 88.20% +0.10%
Functions 91.70% 91.80% +0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 6/8 (75.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.40% -0.10%
Functions 91.90% 91.80% -0.10%
Branches 78.70% 78.50% -0.20%

Changed lines: Changed C/C++ lines covered: 17/19 (89.47%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ca9bfd2

Every failure below has an owner: a fixing PR (ours 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 (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Logical error: Got read request from replica 2 for unknown stream ....inner_id.... (STID 5217-5b3d) + Server died (one abort, two rows) parallel-replicas coordinator defect on the projection short-circuit path. Not caused by this pull request: its diff is src/Core/Settings.cpp, QueryPlanOptimizationSettings.cpp and one new test, none of which touches the coordinator #111689 (merged). The tested build predates it: compare/f4f2c3388956...ca9bfd2950c2 reports behind_by: 1239, so this head was built before the fix landed and a master merge will clear it

Session id: cron:our-pr-ci-monitor:20260731-160000

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
@serxa serxa self-assigned this Sep 21, 2026
Comment thread src/Core/Settings.cpp Outdated
Comment on lines +2575 to +2579
When set to 1, the seed is derived from the initial query id, so every plan built for one query, including the plans
built by remote replicas, uses the same seed and therefore the same join order. Rerunning the same query text gets a new
id and therefore a new seed, which may select a different ordering; pass an explicit query id to keep the seed stable.
An empty initial query id, which is what an internal or background plan carries, falls back to a random seed.
When set to a value > 1, that value is used as the seed directly.

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.

I don't think we need such a detailed explanation. This PR basically fixes a bug; the "new" behavior was implicitly assumed, so there is no need to explain implementation details IMO.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reverted: the description is back to the wording master already had, so the diff no longer touches src/Core/Settings.cpp at all. I trimmed the in-code comment in the same spirit (3332e55).

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 test is disproportionally complicated for (1) such a small fix and (2) a debug-only setting. Consider simplification or even dropping the whole test. Marking the PR as "Not for changelog" because it fixes behavior intended for debug-only.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Dropped, both the .sql and the .reference, and the changelog category is now Not for changelog with your reason. What is left is the 9 line change in QueryPlanOptimizationSettings.cpp alone; I also removed the test claims from the description. If you would rather keep a guard, say so and I will add a minimal one.

I merged master in the same push, since the branch dated from July, so CI is running again (3332e55).

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.

I would keep a minimal guard here. After 3332e55, there is no remaining test that distinguishes the old per-plan randomSeed() behavior from the new per-query derivation: 04050_join_order_randomize only covers explicit seeds, and the surviving = 1 cases in 04277_join_reorder_constraints, 04337_cross_left_join_transitive_predicates, and 04545_correlated_subquery_in_set_speculative_build do not exercise multiple plan constructions or the parallel-replica path. A small regression that proves one initial query yields one seed across either scalar subqueries or replicas would close that gap.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Verified, and the gap is real: on this head the PR is a 9 line change in QueryPlanOptimizationSettings.cpp with no test of its own, 04050_join_order_randomize only uses explicit seeds (42, 0, 12345) and never the = 1 sentinel, and the surviving = 1 cases in 04277_join_reorder_constraints, 04337_cross_left_join_transitive_predicates and 04545_correlated_subquery_in_set_speculative_build all assert query results rather than seed stability, so none of them separates the old per-plan randomSeed() from the new per-query derivation. One correction: 04545 does build several plans inside one initial query (a scalar subquery plus a speculatively built IN set), but its count() output is seed invariant, so it still cannot tell the two behaviours apart.

I dropped that test at the reviewer's request in the comment above, and the test-free tree was approved afterwards, so I am not re-adding one on my own initiative. My earlier offer in this thread stands: if a minimal guard is wanted, say the word and I will add one that proves a single initial query yields a single seed across scalar subqueries and replicas.

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.

Yes, I would keep a minimal guard here. On the current head there is still no test that fails if this = 1 branch is changed back to randomSeed(): 04050_join_order_randomize only covers explicit seeds, and the surviving = 1 tests assert result correctness rather than cross-plan seed stability.

A small stateless regression that forces multiple plan constructions within one initial query and proves they all observe the same derived seed would be enough.

Review feedback on ClickHouse#112660: the setting description explained
implementation details that its previous wording already implied, and the
stateless test was 330 lines of system.text_log assertions for an 11 line
fix on a debug only setting. The description goes back to the text master
already had, the test is dropped, and the fix itself is unchanged.
@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3332e55

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
Integration tests (amd_msan, 6/8) / test_prometheus_protocols/test_compliance.py::test_promql_extended_support flaky, MSan-only: the per-statement forked client hits DEFAULT_QUERY_TIMEOUT in helpers/client.py:270 after 912s #121862 (ours, open)

Mergeable Check and PR are aggregator jobs and report only the row above. All other 127 completed checks passed.

Session id: cron:our-pr-ci-monitor:20260924-053042

@serxa

serxa commented Sep 24, 2026

Copy link
Copy Markdown
Member

@groeneai Approved, make sure CI is green and @-tag me when PR is ready to be merged or sync PR requires attention

@groeneai

Copy link
Copy Markdown
Collaborator Author

Not green yet, so not tagging you for the merge.

CI on 3332e55a finished with one real failure: Integration tests (amd_msan, 6/8) / test_prometheus_protocols/test_compliance.py::test_promql_extended_support. Its fix, #121862, merged this morning, so I merged master (326a33aa) to pick it up. Full CI is re-running on c0930af2.

The merge is content-preserving: the PR is still 1 file, +9/-1 in QueryPlanOptimizationSettings.cpp, byte-identical to the revision you approved, and your approval carried over. I will tag you here as soon as CI is green, or sooner if the Sync PR needs attention.

@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 69413a314 with master 51ce1e82f (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 92ac39e0a; 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, 7 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c0930af

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
Integration tests (arm_binary, distributed plan, 1/4) / test_replicated_database_active_node_taken::test_active_node_owned_by_another_server flaky: 74 failures across 66 unrelated PRs and true master in the last 30 days #121820 (mine, merged 2026-09-24 11:31Z), absent from the tree that ran: the failing job's confirmed checkout d6134f3bb2bb contains 0 occurrences of the anchor that fix introduces, against 2 at the fix commit itself. I merged master @ ae3248c6a83e to pick it up, so CI is re-running.

Mergeable Check and PR are aggregators of the row above, not separate failures. CH Inc sync passed at this head.

Session id: cron:our-pr-ci-monitor:20260924-163305

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ae3248c

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.

Both red jobs failed in the test-selection step before running a single test, so neither carries any
test result. That step's coverage-canary CIDB query was added by #118223 (merged 05:24Z today) and
removed again by its revert #122110 (merged 22:17:55Z today), which is why the revert is the owner.
This is rule 3c and not 3d: the revert merged hours after both jobs had finished (18:11:44Z and
19:43:53Z), so it was absent from the tree that ran, and I have merged master to pick it up.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, s3 storage, targeted) infra, 0 tests run: Failed to load test selection: CIDB query failed - read timeout after 60s against the public CI database #122110 (external, merged), merged master @ 69413a31 to pick it up
Stateless tests (arm_asan_ubsan, targeted) infra, 0 tests run: same step, CIDB answered HTTP 500 Code: 241 ... MEMORY_LIMIT_EXCEEDED for the shared reader #122110 (external, merged), merged master @ 69413a31 to pick it up
Mergeable Check, PR aggregators of the two rows above, not separate failures #122110 (external, merged), merged master @ 69413a31 to pick it up

My own merged #120928 (retry-on-busy for this same step) is already an ancestor of the tested tree,
so it is not the owner here: it cannot help once the query reaches the server and is refused there.

Session id: cron:our-pr-ci-monitor:20260924-223433

@groeneai

Copy link
Copy Markdown
Collaborator Author

@serxa CI is green on 69413a31 (every job finished, only the private CH Inc sync check is still pending) and your approval is live on this head with no conflicts.

Tagging you for the merge as you asked.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 27, 2026
Merged via the queue into ClickHouse:master with commit bea0788 Sep 27, 2026
176 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 27, 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-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-not-for-changelog This PR should not be mentioned in the changelog 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.

4 participants