Repository navigation
Fix wrong results from a direct join into a MergeTree table with plan-based parallel replicas - #119861
Conversation
With join_algorithm = 'direct' and a MergeTree right table the planner moves that read out of the query plan into a lookup plan owned by DirectJoinMergeTreeEntity, which the join transform rebuilds and executes once per key batch. The entity captured the outer query's QueryPlanOptimizationSettings, so under parallel_replicas_plan_based every batch shipped its point read to the cluster. That read is correct only where it is planned. Each batch appends a hand-built in(<key>, __set) filter whose query-condition-cache identity is the same every time, so the planner stamps the read disableQueryConditionCache and says why in PlannerJoinTree.cpp: "Hand-constructed filter dag has same hash key each time, so disable cache". That stamp is a step-local member of ReadFromMergeTree which ReadFromMergeTree::serialize does not write, so a shipped batch is rebuilt with the cache enabled. All batches then share a single cache entry, and every batch after the first reuses the first batch's granule verdicts and skips granules that hold its own keys. A 100000-row left side split into ten lookup batches returned 10000 of 100000 matching rows, and the loss grows with the batch count: two batches lose 43% of the matches, forty lose 95%. Nothing is thrown. Clearing enable_parallel_replicas for the lookup plan removes the mechanism and also removes an initiator-only asymmetry: a replica executing a shipped fragment already runs the lookup locally, because canUseParallelReplicasOnInitiator is false there. The new test pins the two axes whose randomization would otherwise weaken or remove the loss. The number of lookup batches is the left table's stored block count, and that count is fixed by the INSERT rather than by the read: StorageMemory does not prefer large blocks, so InterpreterInsertQuery squashes to max_block_size, and the runner's session draw of 8000 to 100000 leaves 1 to 13 batches. The other is use_query_condition_cache, which the runner turns off half the time. index_granularity is pinned only to fix the granule count the mechanism is described in terms of; the loss was measured at every granularity the runner can draw, because 100000 rows never fit in one granule. The test also asserts from system.query_log that no replica served any part of the affected join while one served an ordinary read of the same table, so it cannot pass in an environment where plan-based parallel replicas declined for every query. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 4 findings in the first pass,
Severity: ❌ blocker / Both directions were re-measured through the shipped test file after the fix round: 10/10 fail on Session id: cron:clickhouse-review-slot-8:20260913-212800 |
|
Workflow [PR], commit [4102948] Summary: ✅
AI ReviewSummaryThis PR disables plan-based parallel replicas for the per-key Findings❌ Blockers
Tests
Final Verdict
LLVM Coverage Report |
|
|
||
| /// The per-key-batch lookup read is stamped `disableQueryConditionCache` at plan time because its | ||
| /// hand-built filter has one identity for every batch, and that stamp is not part of a serialized read. | ||
| plan_optimization_settings.enable_parallel_replicas = false; |
There was a problem hiding this comment.
The lookup plan still inherits make_distributed_plan = 1 from the outer query context, so this only closes the applyParallelReplicas path. The outer query's fallback on JoinStepLogicalLookup mutates only its temporary QueryPlanOptimizationSettings; it does not clear the cached plan_optimization_settings stored on DirectJoinMergeTreeEntity. When executePlan later calls buildQueryPipeline, this per-key read can still be distributed and serialized on its own, and ReadFromMergeTree::serialize still does not carry allow_query_condition_cache. That re-enables the same cross-batch query-condition-cache reuse described in the PR, so silent row loss should still be reachable with make_distributed_plan = 1 (for example together with distributed_plan_execute_locally = 1).
This needs to disable make_distributed_plan for the lookup plan as well, or serialize the cache-disable bit, and the regression coverage should exercise that distributed-plan path.
There was a problem hiding this comment.
I measured this with the stateless worker client enabled, which is how CI runs stateless tests (tests/config/config.d/distributed_query.xml, worker cluster test_cluster_one_shard_two_replicas), so make_distributed_plan = 1 really does dispatch tasks. My earlier answer was measured on a config tree that lacked that file, so every distributing arm refused with Stateless worker client is not enabled in configuration, which said nothing about the code.
You are right that the lookup plan inherits the flag and is distributed: on the shape the new test uses, the query reports DistributedPlanRemoteTasks = 18 and 18 secondary queries. The row loss does not follow, on either binary:
make_distributed_plan = 1: 100000, i.e. correct, 5/5 unpatched and 3/3 patched.make_distributed_plan = 1, distributed_plan_execute_locally = 1, the combination suggested above: 100000,DistributedPlanRemoteTasks = 0.make_distributed_plan = 1, distributed_plan_fallback_to_local_execution = 0:Code: 344 ... make_distributed_plan cannot distribute this query: it contains the step JoinStepLogicalLookup which could not execute remotely.- Control on the same server and tables: the parallel replicas shape this PR fixes returns 10000, 20000, 10000, 10000, 15424 on the unpatched binary, so the environment does expose the loss.
The reason the cache reuse cannot follow the read there is that a distributed worker read pins its ranges per bucket and turns the query condition cache off itself, independently of the step member serialize omits: in ReadFromMergeTree::initializePipeline, under if (distributed_read_bucket_count > 0 && settings.parameter_lookup), reader_settings.use_query_condition_cache = false, commented "Cannot cache PREWHERE results when ranges are pinned per bucket". Measured: system.query_condition_cache holds 0 entries after those reads and 1 entry after the same read at make_distributed_plan = 0.
So I am leaving the second flag alone, which is also what the closest sibling does deliberately: StorageMerge::getChildPlanOptimizationSettings clears enable_parallel_replicas unconditionally and keeps make_distributed_plan, clearing it only for the one shape that cannot carry it. A regression arm on that path would pass on the unpatched binary too, so it would not witness this change.
The missing allow_query_condition_cache bit in ReadFromMergeTree::serialize is real. The parallel replicas leg fixed here is the only place I can measure it producing wrong rows.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 10 s compile time in total, 7 of them have a recent master baseline. |
b9c399b
ReproducerResults:
Backport the fix to CC component owner: @vdimir @m-selmi Analysis metadata
Introducing change: not identified
|
Related: #119372
Related: #110518
Related: #119823
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results when
join_algorithm = 'direct'reads the right-hand table of a join from aMergeTreetable and plan-based parallel replicas (parallel_replicas_plan_based = 1) are enabled. Such a join could silently return only part of the rows that should have matched, with no error reported. The lookup read that the join performs is no longer distributed across replicas.Description
With
join_algorithm = 'direct'and aMergeTreeright table, anINNER JOINwhose true count is 100000 came back between 10000 and 16384 in all ten runs underparallel_replicas_plan_based = 1andparallel_replicas_local_plan = 0, with no exception, while three oracles (no parallel replicas,join_algorithm = 'hash', classic parallel replicas) all return 100000.The planner moves that read into a lookup plan that the join transform rebuilds and executes once per key batch, and the entity captured the outer query's optimization settings, so each batch shipped its point read to the cluster. That read is correct only where it is planned: its hand-built
in(<key>, __set)filter has one query-condition-cache identity for every batch, so the planner stamps the read withdisableQueryConditionCache, andReadFromMergeTree::serializedoes not carry that stamp, so a shipped batch consults the cache again under that shared identity, and every batch after the first inherits the first batch's granule verdicts and skips granules holding its own keys. Clearingenable_parallel_replicasfor the lookup plan keeps it on the initiator, which is what a replica executing a shipped fragment already does.The new test pins the two axes the runner would otherwise randomize away: the number of lookup batches, fixed by the
INSERTinto the left table rather than by the reads, anduse_query_condition_cache, which the defect needs. It also asserts fromsystem.query_logthat no replica served the affected join while one served an ordinary read of the same table, so it cannot pass where parallel replicas declined for every query.The
Got read request from replica N for unknown streamlogical error the linked issue reports does not reproduce onb314641144a26in any shape the issue lists, while the same code path silently drops rows, which this PR fixes, so I left the issue open for its assignee.Workflow [PR]
Sync PR [sync-upstream/pr/119861]