Skip to content

Fix wrong results from a direct join into a MergeTree table with plan-based parallel replicas - #119861

Merged
vdimir merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/119372-direct-join-lookup-no-parallel-replicas
Sep 14, 2026
Merged

vdimir merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/119372-direct-join-lookup-no-parallel-replicas

Conversation

@groeneai

@groeneai groeneai commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #119372
Related: #110518
Related: #119823

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 wrong results when join_algorithm = 'direct' reads the right-hand table of a join from a MergeTree table 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 a MergeTree right table, an INNER JOIN whose true count is 100000 came back between 10000 and 16384 in all ten runs under parallel_replicas_plan_based = 1 and parallel_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 with disableQueryConditionCache, and ReadFromMergeTree::serialize does 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. Clearing enable_parallel_replicas for 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 INSERT into the left table rather than by the reads, and use_query_condition_cache, which the defect needs. It also asserts from system.query_log that 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 stream logical error the linked issue reports does not reproduce on b314641144a26 in 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]

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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Sep 13, 2026
@groeneai

groeneai commented Sep 13, 2026 •

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

Pre-publication review by an independent model (engine: codex; 4 findings in the first pass,
0 in the delta recheck after one fix round) plus my own cold review of the resulting code.

# Sev Finding Verdict Evidence / action
1 ⚠️ The test's read-side max_block_size pin cannot control the number of lookup key batches, so the axis the test claims to pin was left to the runner AGREE, fixed @ 4102948 The batch count is the left table's stored block count: StorageMemory::read discards its max_block_size argument and emits one chunk per stored block, and StorageMemory::prefersLargeBlocks is false, so the stored size is the INSERT-time max_block_size. The pin moved onto the INSERT (10 batches); stored blocks are then ceil(100000/N) exactly for N in {100000, 50000, 20000, 10000, 5000, 2500}, and the session draw becomes inert (8000 / 12345 / 65409 / 100000 all reproduce). At one batch nothing is lost at all, which is what the old pin allowed
2 ⚠️ Nothing in the test witnessed that plan-based parallel replicas was actually active, so it would keep passing if the feature went inert AGREE, fixed @ 4102948 Two system.query_log rows: ParallelReplicasUsedCount = 0 on the affected join, and > 0 on an ordinary read of the same table in the same session and the same parallel_replicas_local_plan = 0 fragment path. Measured 0 post-fix and 1 or 2 pre-fix across 12 runs at max_threads 1/2/3/32. ParallelReplicasQueryCount was rejected by measurement: it counts coordinators constructed and is 1 either way. The control predicate had to be chosen too, since Attribute != '' is answered by optimize_trivial_count_with_sparsity_filter without reaching a replica
3 💡 The changelog entry carried planner and cache implementation detail instead of the user-visible effect AGREE, fixed Rewritten to name the symptom and the change; the mechanism stays in the description
4 💡 Method names in comments should be written without parentheses AGREE, fixed .claude/CLAUDE.md asks for f rather than f() when naming a function itself
5 💡 make_distributed_plan is inherited by the same settings object, on the same line as enable_parallel_replicas, and is not cleared DISAGREE The closest sibling, StorageMerge::getChildPlanOptimizationSettings, also clears enable_parallel_replicas unconditionally while treating make_distributed_plan differently. Re-measured with the stateless worker client enabled, so the lookup read really is dispatched (DistributedPlanRemoteTasks = 18): the count is the correct 100000 on both binaries, 5/5 unpatched and 3/3 patched, while the parallel replicas shape loses rows 5/5 on the same server. A distributed worker read turns the query condition cache off itself, so the serialization gap cannot reuse entries there. Details and the numbers: #119861 (comment). No silent wrong result, so I did not add a second assignment for a defect nobody has reproduced

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

Both directions were re-measured through the shipped test file after the fix round: 10/10 fail on
the pre-fix binary (local_plan 0 returning 10000 to 16384 instead of 100000, and the new witness
row returning 0), 10/10 pass on the fix binary, 50/50 pass under randomized settings, and 10/10 pass
again on a binary relinked from the committed tree.

Session id: cron:clickhouse-review-slot-8:20260913-212800

@clickhouse-gh clickhouse-gh Bot closed this Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4102948]

Summary: ✅


AI Review

Summary

This PR disables plan-based parallel replicas for the per-key DirectJoinMergeTreeEntity lookup plan and adds a focused stateless regression test for the reported silent row loss. That closes the specific parallel_replicas_plan_based path, but the same serialized-read cache bug is still reachable when the lookup plan is rebuilt under make_distributed_plan, so I would not merge it yet.

Findings

❌ Blockers

  • [src/Interpreters/DirectJoinMergeTreeEntity.cpp:64] The lookup plan still inherits make_distributed_plan = 1 from the outer query context. The outer query's fallback on JoinStepLogicalLookup only mutates 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, and ReadFromMergeTree::serialize still does not carry allow_query_condition_cache. That re-enables the same cross-batch query-condition-cache reuse the PR description explains, so silent row loss remains reachable with make_distributed_plan = 1 (for example with distributed_plan_execute_locally = 1).
    Suggested fix: also clear plan_optimization_settings.make_distributed_plan here, or propagate the cache-disable flag through ReadFromMergeTree serialization, and add a regression that exercises the distributed-plan path.
Tests
  • ⚠️ Add a focused variant of this regression with make_distributed_plan = 1 and distributed_plan_execute_locally = 1. That is the smallest proof that the serialized lookup plan no longer re-enables query-condition-cache use after the outer plan falls back to local execution.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: disable distributed-plan execution for the per-key lookup plan (or serialize the allow_query_condition_cache decision), and cover that path with a regression test.

LLVM Coverage Report

⚠️ No coverage measurement for commit 4102948: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_7.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 13, 2026
@groeneai
groeneai requested review from nickitat and vdimir September 13, 2026 22:03
@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 13, 2026

/// 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;

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.

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.

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 410294890 with master 0c3b387da (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

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

Job report

@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
-- Needs a server whose cluster below has 3 replicas pointing at itself (as in the stateless-test config).
-- parallel_replicas_plan_based = 1 and parallel_replicas_local_plan = 0 are both non-default.
CREATE TABLE dj_l (Id UInt64) ENGINE = Memory;
CREATE TABLE dj_r (EventId UInt64, Attribute String) ENGINE = MergeTree ORDER BY EventId SETTINGS index_granularity = 8192;
INSERT INTO dj_l SELECT number FROM numbers(100000) SETTINGS max_block_size = 10000;
INSERT INTO dj_r SELECT number, toString(number) FROM numbers(100000);

SELECT count() FROM dj_l AS t0 INNER JOIN dj_r AS t1 ON t1.EventId = t0.Id
SETTINGS enable_analyzer = 1, join_algorithm = 'direct', query_plan_join_swap_table = 0,
    enable_parallel_replicas = 1, max_parallel_replicas = 3,
    cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost',
    parallel_replicas_for_non_replicated_merge_tree = 1, parallel_replicas_plan_based = 1,
    automatic_parallel_replicas_mode = 0, parallel_replicas_local_plan = 0,
    use_query_condition_cache = 1;
-- Expected 100000 (same query with enable_parallel_replicas = 0).
-- 26.8.11.7: 10000 on the first run, 0 on repeats; 26.8.10.6: 30000, then 0. 26.7.14.3, 26.9.2.8, master: 100000.

Results:

  • Reproduces on: 26.8
  • Does not reproduce on: master, 26.9, 26.7
  • Tested versions: master, 26.9, 26.8, 26.7
  • Measured on the public release build (no private branch build published): 26.9, 26.8, 26.7
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.8.

CC component owner: @vdimir @m-selmi

Analysis metadata

comp-joins · Severity P2 · Finding phase_d_pr119861

  • Verified against master build d43d606767f0 (aarch64)
  • Feature not present (repro inconclusive — the affected code path postdates these releases): 26.6, 26.5, 26.4, 26.3
Introducing change: not identified
  • The introducing change was not identified (untested merges with no prebuilt binary in the boundary range).
  • Release-level boundary (official release binaries): first reproduces at v26.8.3.105-lts.
  • Candidate range: the introducing PR is one of those merged between Syncing #111319 and Return retryable HTTP 503 on remote-write async insert flush timeout #117632.
  • A source-build bisect over the range was attempted but could not produce a verdict; the range above is the most precise information available.
  • Secondary components: comp-testing

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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... groeneai-origin-issue PR origin: picked up an external GitHub issue 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.

4 participants