Skip to content

Fix unknown-stream logical error when a replica re-orders a shipped join - #118084

Merged
alexey-milovidov merged 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/join-step-logical-optimizer-state-over-the-wire
Sep 11, 2026
Merged

alexey-milovidov merged 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/join-step-logical-optimizer-state-over-the-wire

Conversation

@groeneai

@groeneai groeneai commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a LOGICAL_ERROR (Got read request from replica N for unknown stream <table>) when parallel_replicas_plan_based is enabled and a join is distributed across replicas. A replica planned its part of the join differently from the initiator and read the coordinated table in a way the initiator had not registered.

Description

Related: #110518
Related: #117731
Closes #118093

With parallel_replicas_plan_based = 1 a distributed join can fail with a LOGICAL_ERROR in ParallelReplicasReadingCoordinator::handleRequest, aborting a debug build:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115702&sha=7e5309e6c513d335a722af6a869b2945818a27a7&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29

Root cause. The initiator registers the coordinated side's stream with the coordinator up front, and that stream's identity encodes the read type: #split_i is appended only on the in-order path. The read type follows from the join algorithm, and the join planner takes two of its decisions from a row estimate:

  • the join order - optimizeJoinLogicalImpl reorders the join graph, and the randomized cost model keys a relation's estimate on its position in that graph;
  • whether to add a runtime filter - tryAddJoinRuntimeFilter declines a probe side estimated at no more than join_runtime_filter_min_probe_rows rows, and adding a filter erases every non-hash algorithm from join_algorithms, which takes the sorting step with it.

Estimates are deliberately not part of the plan format, so a replica that took either decision again took it from an empty estimate. The initiator keeps its fragment as a clone, which carries both decisions; a replica got a serialized copy, which carried neither. It then chose a different algorithm, hence a different read type for the coordinated side, and the coordinator rejected its read request.

The change. serialize and deserialize carry one flags byte holding those two decisions, so a receiver is told what was already decided rather than deciding again. It is payload, not a spare bit a reader may ignore, so it needs plan serialization version 16; a replica speaking 15 then drops out of plan-based parallel replicas until a rolling upgrade finishes.

Estimates themselves stay off the wire, at a reviewer's request - only the decisions taken from them travel. Nothing regresses against master, which serializes neither.

The reverse direction never diverged, which is why one bit per decision is enough: when the initiator does add a runtime filter, its pruned join_algorithms is itself a serialized plan setting, so both sides already agreed. Only initiator-declines plus replica-adds could disagree.

Validation. The divergence measures out on a pristine 26.9.1.1 binary, single node, EXPLAIN actions = 1, 500-row probe against a 100k build side, join_algorithm = 'full_sorting_merge,hash', enable_join_runtime_filters = 1, query_plan_join_swap_table = false:

probe estimate join_runtime_filter_min_probe_rows plan
500, present 1000 Algorithm: FullSortingMergeJoin, Sorting above both reads, both Read type: InOrder, no BuildRuntimeFilter
guard bypassed, standing in for nullopt 0 Algorithm: SpillingHashJoin(HashJoin), BuildRuntimeFilter, both Read type: Default

A round-trip unit test pins each decision on its own, all four combinations of the shared byte, that a clone carries both, the empty payload at version 15 and full payload consumption.

05161_pr_plan_based_join_small_probe_runtime_filter covers a probe side below the threshold - the case the runtime-filter divergence needs, and one 04649_pr_plan_based_join_distributed never reaches - for all three coordinated-side placements, with and without the initiator's local plan, verified against a real three-replica run.

Worth being precise about what that test pins, because it passes on master. A replica on master re-runs the join order pass and derives an estimate of its own, so it declines the runtime filter for the same reason the initiator does and the two agree by accident. The divergence becomes reachable only once the join order decision travels and the replica's estimate is therefore always absent - that is, it is a failure mode this pull request would otherwise have introduced, deterministically, rather than one it inherits. The test throws only on the arm that ships the join order alone.


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

Version info

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

groeneai and others added 4 commits September 4, 2026 00:11
With `parallel_replicas_plan_based = 1` the initiator captures a logical fragment and keeps its own
copy as a `clone`, while every replica receives a serialized copy. `clone` deliberately preserves the
optimizer state, and its comment says the `optimized` flag is load-bearing; `serialize` and
`deserialize` preserved none of it, so a replica arrived with `optimized = false` and re-ran
`optimizeJoinLogical` on a join whose order the initiator had already fixed.

Join reordering is not a deterministic function of the fragment alone. `getRandomizedStats` hashes
the relation's position in the query-graph build order, and the initiator builds that graph from the
original query while a replica builds it from the already-swapped fragment, so the same seed yields
different cardinalities on the two sides. The replicas then chose a different join algorithm, hence a
different read type for the coordinated table. Stream identity encodes the read type (`#split_i` is
appended only on the in-order path), so the initiator registered `<db>.jd_r#split_0` with mode
`WithOrder` while a replica announced the bare `<db>.jd_r`, its announcement was dropped, and its read
request hit `Got read request from replica N for unknown stream <db>.jd_r` in
`ParallelReplicasReadingCoordinator::handleRequest`.

Serialization now carries exactly what `clone` preserves, behind query plan serialization version 12.
The block is omitted when a step is serialized to compute an Auto-PR plan cache key: one of the fields
is the output of that hashing, and the flag and the estimates differ between the single-node and the
distributed plan build, which is the hash matching that mode exists to keep intact.

Related: ClickHouse#110518

Co-Authored-By: Claude Opus 5 <[email protected]>
`result_column_stats` is an `unordered_map`, so serializing it in iteration order made the bytes of one
plan vary between runs. It is emitted sorted by column name now, which is also the order the Cascades
identity encoding of the same members uses.

The local in `deserialize` is renamed to `step`, matching the two other open pull requests that add a
field to that function, so resolving the overlap between them is a one-line pick.

The header comment above these members read "Runtime info, do not serialize", which stopped being true
for them. It now describes the group it still applies to, and the note in `serialize` states the
property the new block exists for.

That note also drops a claim from the previous commit's message: `right_hash_table_cache_key` is not the
output of the plan cache key hashing. A `JoinStepLogical`'s contribution to a cache key is computed by
`calculateJoinStepCacheKeyContribution`, never by its `serialize`. The block is still left out of a cache
key, for the other reason given there: `optimized` and the estimates differ between the single-node and
the parallel-replicas plan build, and those two builds have to hash alike.

Both tests pin the randomized settings their case depends on. Four settings each independently remove the
divergence and the test runner draws two of them half the time, so without the pins the new case in
`04649_pr_plan_based_join_distributed` would have been vacuous on roughly three CI runs in four.
`04511_cascades_replicated_subplan_join` pins `use_hash_table_stats_for_join_reordering`: it is a full
pinned-text `EXPLAIN PLAN` that pins every other plan-shaping randomized setting, and join reordering
otherwise takes a leaf row estimate from the process-global hash table statistics, which any join that ran
earlier in the same server fills in. That already fails it one run in five on master under concurrency;
with the pin it passes five of five on master and five of five with this change, and its reference file is
unchanged.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115702&sha=7e5309e6c513d335a722af6a869b2945818a27a7&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29
Seen on ClickHouse#115702
Related: ClickHouse#110518

Co-Authored-By: Claude Opus 5 <[email protected]>
The version-12 block carries nine values, and a SQL test can observe only
`optimized`: once that flag survives the wire the receiver stops re-ordering
the join, so a dropped estimate, cache key, relation or hint is invisible at
the query level. The new test round-trips a fully-populated step and an
all-defaults step, at the current version and at the one below it.

It uses two oracles because neither alone covers the block. Byte identity of
re-serialization pins that both sides agree on the layout, which is what
catches a field written but not read, a field read into the wrong member and a
reordered pair; it is blind to a write and its read removed together, since
both streams then match. The value assertions catch exactly that case. Three
of `RelationEstimateInfo`'s members have no getter and all three render
through `getReadableRelationName`, which shows one relation per side and lets
`composite` suppress the other two, so the case walks two relation pairs to
make each of them visible.

The new case in `04649_pr_plan_based_join_distributed` is now wrapped in the
failpoint the file already uses for its `INNER` case, so the initiator's local
read is slowed and a remote replica reaches the coordinator for the
coordinated side instead of finding the ranges already taken. The sleep sits
in the read-task callback rather than the announcement callback, so the
initiator still announces first as the snapshot replica, which is the ordering
the original failure showed. Measured, this leaves the reproduction intact:
pristine still fails 30 of 30 randomized runs on the `unknown stream` throw.

Its comment claimed every listed setting is pinned because the runner
randomizes it. That is false for `join_algorithm`, which the runner does not
randomize at all, so the comment now separates the settings that build the
disagreement from the four that hold off the runner.

The version-12 note in `ProtocolDefines.h` said a step from the wire is in the
same state as one produced by `clone`. One clone-preserved member is
deliberately not carried, so it now says the same join optimizer state.
`serialize` packs `optimized`, `imprecise_estimate` and the presence of
`result_rows_estimation` into one byte, and the round-trip test covered only
two of the five reachable patterns: all three bits set, and none of them. In
both of those the bits are equal to each other, so a reader that assigns a bit
to the wrong member passed every assertion, and byte identity held too because
re-serialization wrote the swapped members back into the swapped bits.

The pattern a swap would break is also the common one on the wire:
`setOptimized()` with no arguments sets the flag alone, which is what five of
its six call sites do. The new case walks the three uncovered patterns and
asserts all three observables separately, so each bit has to arrive in its own
member.

Measured with two mutants of `deserialize`, each reverted afterwards. Swapping
the `optimized` and `imprecise_estimate` bits leaves all three older cases
green and reddens the new one; swapping the imprecise bit with the estimate
presence bit reddens the new one as well. The first mutant is the one that
shows the gap was real rather than theoretical.

The helper's comment said `assert_cast` pins the type the registry returned.
Both halves were wrong: `assert_cast` compares typeid only in a debug or
sanitizer build and is a plain `static_cast` otherwise, and no registry is
involved, since `JoinStepLogical::deserialize` returns a `JoinStepLogical`
unconditionally. The comment is gone, and with it a call whose result was
discarded and which therefore had nothing left to explain it.

Three more comments said more than they could support. The version-12 note in
`serialize` now says the same join optimizer state as one produced by `clone`,
matching the wording already used in `ProtocolDefines.h`, because one
clone-preserved member is deliberately not carried. In
`04511_cascades_replicated_subplan_join` the hash table statistics are filled
in by an earlier hash join rather than by any join, since only `HashJoin` and
`ConcurrentHashJoin` write that cache. In
`04649_pr_plan_based_join_distributed` the two sides build the query graph in
opposite orders because the initiator swaps the fragment it ships and not its
local clone; the seed's part is that the row estimate keys on a relation's
position in that order, which is what turns the existing order difference into
a different plan.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Three rounds of independent reads of the resulting code plus cold second-model passes; the last round
found nothing. Two asks were declined on measurement, recorded here so they are not re-asked:

  • An in-test assertion that a non-local replica obtained work. ParallelReplicasUsedCount > 1 holds on
    3 runs of 30, because the coordinator counts only a replica it hands ranges to and this case's single
    thread lets the initiator drain them first. Remote execution of the deserialized fragment is
    established instead by the unfixed arm: 30 runs of 30 fail with the coordinator rejecting a remote
    replica's read request, which that replica can only issue after deserializing the fragment.
  • A mixed-version dispatch test. It needs two server binaries, and no test covers this gate for any
    earlier version of the format. The version-11 layout half is covered by the round-trip unit test.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6572af4]

Summary: ✅


AI Review

Summary

This PR bumps query-plan serialization to carry the two JoinStepLogical decisions that can diverge on a deserialized fragment under plan-based parallel replicas: whether join order was already chosen, and whether the runtime-filter pass already declined a small probe side. The current tree preserves those bits through clone, serialize, and deserialize, gates plan-based parallel replicas on the new serialization version, and adds focused unit and stateless coverage for the runtime-filter path. I did not find a remaining correctness or compatibility issue in the updated implementation.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit 6572af4.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 125/127 (98.43%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @davenger @nickitat, could you review this? A plan fragment shipped to a replica lost the join optimizer state that the initiator's own clone keeps, so the replica re-ran join reordering and then read the coordinated table with a read type whose stream id the coordinator had never registered, since #split_i is appended only on the in-order path. It also pins one setting in 04511_cascades_replicated_subplan_join, for the reason given in the description.

throw Exception(ErrorCodes::INCORRECT_DATA, "Unknown row estimate source {}", static_cast<UInt16>(source));
relation.source = static_cast<RowEstimateSource>(source);

relation.imprecise_estimate = bool(flags & 2);

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 that serialized query plan should contain contain estimates

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.

Agreed, cutting them.

The only field this fix needs is the optimized bit: the divergence is the receiver re-running join reordering (plan.optimize, executeQuery.cpp:3205), and optimizeJoin.cpp:489 gates that on isOptimized(). clone says as much itself, marking that flag as the load-bearing one; it copies the estimates because a clone is a copy of a node inside one process, which is not a reason to put them on the wire.

So the version 12 block shrinks to that one bit, and the row and column estimates, both RelationEstimateInfo payloads, table_stats_hint, the two hash table cache keys and both serialize helpers go. Nothing regresses against master, which serializes none of them.

That also drops the SET use_hash_table_stats_for_join_reordering = 0 this PR added to 04511_cascades_replicated_subplan_join. The pin was needed only because the cache keys crossed the wire: with them the test failed all 5 runs, without them it passed 5 of 5 (it is separately flaky on master for an unrelated reason, the cached row count at optimizeJoin.cpp:787-795).

The version bump stays: RemoteQueryExecutor.cpp:185 uses it to leave a replica speaking 11 out of plan based parallel replicas, so the error cannot be reached mid upgrade.

It also settles the bot comment below, which points the opposite way (the wire state omits disjunctions_optimization_applied). Both objections came from my "same state as clone" wording. The contract is that a receiver is told the order was already chosen, not clone parity; that bit is #117731's.

I will push the reduced form once the acceptance run is repeated on both arms.

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.

Pushed as e001efb.

The version 12 block is one bit now, the flag that says an order was already chosen. The row and column estimates, both relation payloads, the statistics hint, the two hash table cache keys and both serialize helpers are gone, and 04511_cascades_replicated_subplan_join is back to its merge base content.

Two things worth stating rather than leaving for you to find.

A receiver of a shipped fragment now builds its physical join with no estimates at all, where before this change it derived its own during the re-ordering that the fix removes. Inside the chosen algorithm family that means ConcurrentHashJoin where the initiator picked HashJoin (PlannerJoins.cpp:1268, which treats a missing rhs_size_estimation the same as one above parallel_hash_join_threshold), and the row store hint is off (:1199-1209). The family loop itself never reads an estimate, so none of this can insert or remove a SortingStep, hence none of it can change the stream identity the coordinator registers. If you would rather a receiver re-derived its own estimates without re-ordering, that is a separate change and I am glad to take it.

Correcting a number from my earlier comment: unpinned, 04511 passes 3 of 5 with this build, not 5 of 5. That is master's own behaviour (it failed 1 of 5 and 2 of 5 there in two earlier rounds), so this PR neither fixes nor worsens it.

30 of 30 runs of the regression test pass with the pushed binary under full CI randomization, and 5 of 5 fail on the same harness with a pristine one.

…ed it

A reviewer asked for the estimates to be kept out of the serialized query
plan, and they are not needed to fix the error this pull request is about.
The receiver diverges because it orders the join a second time, and the
only thing that stops it is the flag that says an order was already
chosen: `optimizeJoin.cpp` gates the join order pass on `isOptimized()`,
and the receiver reaches it through `plan.optimize` in `executeQuery.cpp`.
`clone` carries the estimates because it copies a node inside one process,
which is not a reason to put them on the wire.

So version 12 now carries one bit. The row and column estimates, the two
input relations, the table statistics hint and the two hash table cache
keys are gone, along with the two helpers that wrote and read the relation
payload. None of them can insert or remove a `SortingStep`, so none of them
can change the read type that the coordinator identifies a stream by, and
nothing regresses against master, which serializes none of them.

The version bump stays. `RemoteQueryExecutor` leaves a replica that speaks
version 11 out of plan based parallel replicas, so the error is out of
reach while a rolling upgrade is in progress.

`04511_cascades_replicated_subplan_join` no longer needs the
`use_hash_table_stats_for_join_reordering` pin this pull request added to
it: the pin was needed only because the two cache keys crossed the wire.
Without them that test is back to how it behaves on master, which is 2
failures in 5 runs from a cached row count replacing a leaf estimate,
neither fixed nor worsened here.

The round trip unit test shrinks with the payload. It now pins that the bit
survives a round trip at version 12 and that a sender writes nothing for a
receiver at version 11, which is the compatibility half that no SQL test
can reach.

Measured, all with the identity of the running server asserted per run:
30 of 30 runs of `04649_pr_plan_based_join_distributed` pass with this
change under full CI randomization, and 5 of 5 fail on the same harness
with a pristine binary. 165 query plan serialization unit tests pass. The
style job reports 14 of 15 legs clean, the exception being the
settings history leg, which refuses to run outside CI.
…omment

The comment said a replica and the initiator's clone have to arrive in the
same optimizer state, which was true of the earlier nine field payload and
is not true of the one bit that is shipped now. Only the queries below it
are executed, so this changes nothing about what the test measures.
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

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

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

Compile time of recompiled translation units

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

Job report

Comparing two serializers against each other left one writer unexcluded:
one that appends the same byte at every version passes both assertions of
the pre-version test, because the two byte strings stay equal to each other
and a reader below version 12 returns an unoptimized step while leaving
that byte unread. In a whole plan the unread byte would be taken for the
next node. Asserting that the buffer is at end of file after a step is
deserialized excludes it.

Verified by removing the version condition from the write side alone, which
is exactly that writer: the pre-version test then fails on `in.eof()` and
passes again once the condition is restored.
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 4, 2026
Comment on lines +218 to +221
/// Whether the join order was already chosen. A copy of this step, whether made by `clone` or taken
/// over the wire, carries it, so that whoever receives the copy does not choose an order again.
bool optimized = false;

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'm not sure if parallel replicas should do join order optimization at all at replicas. Distributed Query Execution v2 (aka make_distributed_plan=1) chooses join order at initiator, maybe parallel replicas should do the same

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.

Agreed, and I would rather ship your mechanism than mine.

What this PR does today is already "the initiator decides": the fragment carries the initiator's order structurally (applyParallelReplicas clones the subtree at optimizeTree.cpp:412, after the order pass at :314, with the joins still logical on purpose, :322-324). The failure is the replica deciding a second time on top of that. Its deserialized step came back with the flag clear, so optimizeJoinLogical ran again (optimizeJoin.cpp:1545) and swapped the sides back, because the randomized stats key on a relation's position in the build order and the two sides build in opposite orders. The bit only makes that pass return early.

Your way is what DQE v2 does at its receive site: DistributedPlanExecutor.cpp:821-833 zeroes query_plan_optimize_join_order_limit and ..._randomize and pins join_swap_table to false before optimizing a deserialized fragment, with the comment "per-worker stats can diverge and produce incompatible plans across workers (e.g. one swaps the join sides while the others don't)". That is this bug, one layer over. With the limit at 0, optimizeJoinLogicalImpl marks the step optimized and returns (optimizeJoin.cpp:1567-1576), so both shapes end in the same state. The plan-based parallel-replicas receive site (executeQuery.cpp:3200-3214) has no such override, which is the real gap.

Two differences to decide on:

  • Your shape is broader, and I think that is right. It also switches off the other receiver-side rewrites listed there (convert_join_to_in, convert_outer_join_to_inner_join, convert_any_join_to_semi_or_anti_join, merge_filter_into_join_condition, top_k_through_join), so the whole family goes, not just the order. The bit fixes one member of it.
  • It loses the rolling-upgrade guarantee, because the guard then lives in the receiver, so an older replica keeps re-deciding. The bit came with a plan serialization version, so RemoteQueryExecutor.cpp:185 drops such a replica out of plan-based parallel replicas and the error is unreachable mid upgrade. If you want that window kept, DBMS_PARALLEL_REPLICAS_PROTOCOL_VERSION (checked one line above, :184) carries "this replica does not re-decide" with no plan format change.

Tell me which you prefer and I will push it: the receiver-side override alone, or the override plus that version gate. I will re-run the 30-run randomized check on 04649 and the pristine-binary control on whichever it is before pushing.

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.

One update that bears on the choice I asked you to make, so that you are not deciding on a stale picture.

An automated review round found, and I confirmed by measurement, that the join order bit alone is not sufficient. The runtime filter pass skips a small probe only when the input row estimate is present (joinRuntimeFilter.cpp:257-260), and it pins the algorithm list to the hash family as soon as it adds a filter (:587-588), which removes the sorting step and turns Read type: InOrder into Default. That is the same stream identity divergence, reached without any join reordering. Since this PR stops a replica from deriving estimates of its own, a probe below join_runtime_filter_min_probe_rows now diverges deterministically rather than by chance.

The worker-side override you pointed at does not close that by itself: DistributedPlanExecutor.cpp:827 sets query_plan_optimize_join_order_limit = 0, which reaches setOptimized() with no estimates, and the list does not include enable_join_runtime_filters. So whichever shape you prefer, the runtime filter decision has to come from serialized state as well. The measurement and a third option that keeps estimates off the wire are in the JoinStepLogical.cpp thread.

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.

🕵 Rebased onto master - version 15 went to the LimitRange step meanwhile, so this is plan serialization version 16 now - and, while your answer was outstanding, I closed the one thing that blocks regardless of which shape you pick.

The serialized state is now the whole family of decisions this step takes from a row estimate, not just the order: the join order, and whether the runtime filter pass declined the join for a small probe side. Both are decisions, not estimates, so your objection in the JoinStepLogical.cpp thread still holds - nothing derived travels, only the verdict taken from it. Measurement and reasoning are in that thread.

On your question itself I still prefer your answer, and this does not foreclose it. One correction to the picture, though, in case it changes which shape you want: the worker-side override as make_distributed_plan = 1 does it today would not have closed the second half. DistributedPlanExecutor.cpp:827 sets query_plan_optimize_join_order_limit = 0, which lands on setOptimized() with no estimates, and that override list does not include enable_join_runtime_filters, so a worker would still add a filter the initiator declined. Whichever shape you prefer, the runtime filter decision has to come from serialized state as well.

So the two are orthogonal, not alternatives:

  • These bits make a receiver of a shipped fragment honour the sender's decisions, and keep the rolling-upgrade guarantee: RemoteQueryExecutor.cpp:185 drops a replica speaking 15 out of plan-based parallel replicas, so the error is unreachable mid upgrade.
  • Your override would additionally switch off the other receiver-side rewrites listed there (convert_join_to_in, convert_outer_join_to_inner_join, convert_any_join_to_semi_or_anti_join, merge_filter_into_join_condition, top_k_through_join), which is broader and I think right.

Happy to push the override on top as a follow-up, or in this PR if you would rather have both at once - say which and I will.

@rschu1ze rschu1ze added comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). and removed comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... labels Sep 6, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - eb7516a

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
Build profile diff infra: the job exits 1 before any comparison, on Code: 497 ACCESS_DENIED for default.binary_sizes in the CI logs cluster (has_pr_data, build_profile_diff_job.py:721); reproduced on unrelated PRs by other authors a fix task is created (investigating at full effort, fixing PR link to follow here)

Coverage, so the ledger is not certifying an untested head: 154 of 174 checks passed, 18 skipped,
0 dropped. Config Workflow, Fast test, Style check (0/15), Finish Workflow,
Mergeable Check and CH Inc sync are all green. The PR check is the workflow rollup and is
red only because of the row above.

Session id: cron:our-pr-ci-monitor:20260907-213102

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing-PR link-back for the Build profile diff row in the CI finish ledger above: #118685 fixes the repo-side defect that failure exposed, namely that a failing first cluster read left an earlier commit's comparison pinned to the pull request, presenting an older revision as the current one.

The logs-cluster user switch that addresses the ACCESS_DENIED trigger itself is linked from that PR's description. CIDB still shows Build profile diff as error on all 7 runs started after that switch merged, with no success rows in the window, so this row's check may stay red until the cluster side is provisioned.

…-over-the-wire

`master` took query plan serialization version 15 for the `LimitRange` step, so the join order
decision this branch adds moves to 16.
`tryAddJoinRuntimeFilter` declines a join whose probe side is estimated at no more than
`join_runtime_filter_min_probe_rows` rows, because the planning and pipeline overhead outweighs the
saving. That comparison is the second decision in the join planner taken from a row estimate, and
row estimates are deliberately not part of the plan format, so on a step taken over the wire
`getInputRowsEstimation` is always empty.

A replica therefore re-decided from an empty estimate and added the filter its initiator had
declined. Adding one erases every non-hash algorithm from `join_algorithms`, which takes the sorting
step with it, so the coordinated side's read turned from `InOrder` into `Default` - a stream identity
the initiator never registered with the coordinator, which then rejected the replica's read request
with `Got read request from replica N for unknown stream`. That is the same exception the join order
bit of this branch removes, reached without any join reordering, and shipping the join order made it
deterministic rather than occasional: the replica now returns from `optimizeJoinLogicalImpl` before
`setInputRelations`, so its estimate is always absent.

The decision travels as a second bit of the same flags byte, so nothing new goes on the wire beyond
what version 16 already introduced, and estimates stay off it. The reverse direction never diverged:
when the initiator does add a filter, its pruned `join_algorithms` is itself serialized, so both
sides already agreed.
The existing `04649_pr_plan_based_join_distributed` keeps both sides far above
`join_runtime_filter_min_probe_rows`, so it exercises only the case where the initiator itself adds
the runtime filter and ships the pruned algorithm list. The divergence is the other case: the
initiator declines a small probe and a replica does not.

The new test pins the probe side below the threshold and the build side far above it, and covers
both placements of the coordinated read relative to the filter (`INNER` and `LEFT` coordinate the
probe side, `RIGHT` the build side), with and without the initiator's local plan so that a
deserialized fragment is what runs. It asserts up front that the join is really shipped, so it
cannot pass by not distributing.
`DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_JOIN_ORDER_DECIDED` and the round-trip test were
named when the flags byte held only the join order. Both now cover the runtime filter's small-probe
decision as well.
Verified against a real three-replica run: the test passes on a `26.9.1.1` server, which ships
neither decision, because a replica there re-runs the join order pass and derives an estimate of its
own, so it declines the runtime filter for the same reason the initiator does and the two agree by
accident. The divergence appears only once the join order decision travels and the replica's
estimate is therefore always absent, which is what the rest of this branch does.

So the test is a guard on the second decision specifically, and its reference is the same on all
three arms; only the arm that ships the join order alone throws. Worth saying in the file, or a
reader checks it against master, sees it pass, and concludes it pins nothing.
… transitive include

The clone assertion is the only `typeid_cast` in the file, and it reads better on a mutable pointer:
`clone` hands back a `QueryPlanStepPtr`, so there is nothing const about it to preserve.
@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Sep 9, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks clean to me. While it changes the serialization version, the change is minimal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release 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-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default 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.

Logical error: Got read request from replica A for unknown stream B. (STID: 5217-505b)

5 participants