Skip to content

Keep a read with pinned block numbers local in plan-based parallel replicas - #114263

Merged
nickitat merged 3 commits into
ClickHouse:masterfrom
groeneai:fix/pr-plan-based-pinned-block-numbers
Aug 25, 2026
Merged

nickitat merged 3 commits into
ClickHouse:masterfrom
groeneai:fix/pr-plan-based-pinned-block-numbers

Conversation

@groeneai

@groeneai groeneai commented Aug 11, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112723

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):

Fix wrong results when plan-based parallel replicas shipped a read pinned by select_sequential_consistency. Follower replicas rebuilt the read without the pinned block-number boundary and returned rows the insert quorum never confirmed. Such a read is now executed locally.

Description

select_sequential_consistency clamps a ReplicatedMergeTree read to the parts the initiator saw confirmed by the insert quorum, via max_block_numbers_to_read. That pin is not serialized: ReadFromMergeTree::deserialize rebuilds a shipped read with max_block_numbers_to_read = nullptr. mergeTreeReadCanBeShipped did not consult it, so the read was split and each follower read its own unclamped part set.

The result is wrong results with no exception. On a two-replica quorum fixture whose correct answer is (45, 10), a remote-only plan-based execution returns (435, 30): the 20 unconfirmed rows leak in. A join whose broadcast side reads the pinned table returns 30 rows where the pinned truth is 10.

This adds hasPinnedBlockNumbers() to mergeTreeReadCanBeShipped, mirroring the existing rejection for the same property in make_distributed_plan (checkDistributedReadSupported). The predicate gates both collectReadsToDistribute (the coordinated read) and subtreeHasUnshippableRead (the broadcast side of a lifted join), so one check covers both carriers. Returning false rather than throwing matches how this path already keeps a refreshable-MV target read local: make_distributed_plan is an explicit opt-in, plan-based parallel replicas falls back to a local read.

The test asserts row sets and step order, not step presence, since refusing the lift leaves the split below the join. Reverting only this guard flips four of its seven assertions while the unpinned controls stay unchanged. 50/50 randomized runs pass.

The fix and its regression test are @ alexey-milovidov's, from commit b305123 on #112723. That PR was closed unmerged in favour of #114242, which does not carry this guard, so it was lost.

checkDistributedReadSupported has three further predicates with no counterpart here (input_order_info, isStream(), and the _part_index / _part_starting_offset virtual columns). I could not demonstrate any of them diverging, so I left them alone; isStream() is also unreachable here, because the planner disables parallel replicas for a STREAM table expression before these settings are built.


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

Version info

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

…plicas

select_sequential_consistency clamps a ReplicatedMergeTree read to the parts
the initiator saw confirmed by the insert quorum, via max_block_numbers_to_read.
The pin is not serialized: ReadFromMergeTree::deserialize rebuilds a shipped
read with max_block_numbers_to_read = nullptr. mergeTreeReadCanBeShipped did
not consult it, so the read was split for parallel replicas and each follower
silently read its own unclamped part set, returning rows the quorum never
confirmed with no exception.

Reject hasPinnedBlockNumbers in mergeTreeReadCanBeShipped, mirroring the
rejection for the same property in make_distributed_plan
(checkDistributedReadSupported, makeDistributed.cpp). The predicate gates both
collectReadsToDistribute (the coordinated read) and subtreeHasUnshippableRead
(the broadcast side of a lifted join), so one check covers both carriers.
Returning false rather than throwing matches how this path already keeps a
refreshable-MV target read local, and how the same file keeps FINAL reads and
IN (subquery) plans local: make_distributed_plan is an explicit opt-in,
plan-based parallel replicas falls back to a local read.

A/B on a two-replica quorum fixture (SYSTEM STOP FETCHES plus a timed-out
insert_quorum = 2, insert_quorum_parallel = 0 insert, so /quorum/status stays
set), remote-only, with the guard reverted and nothing else changed: the pinned
read is split and returns (435, 30) instead of the quorum-consistent (45, 10),
and a join reading the pinned table on its broadcast side returns 30 rows where
the truth is 10. The fixture is asserted armed before measuring, since SYSTEM
STOP FETCHES is in-memory only and a restart evaporates the pin.

The join arm coordinates a plain MergeTree, which has no sequential-consistency
branch and therefore keeps its split marker, so the broadcast-side check is
reached rather than short-circuited by the coordinated read being rejected
first. It asserts step order rather than step presence: refusing the lift keeps
the split below the join, so ReadFromParallelReplicas appears either way and
only its position distinguishes a local join over a distributed read from a
fully shipped join.

The fix and its regression test are Alexey Milovidov's, from commit
b305123 on ClickHouse#112723, which was closed unmerged in favour of ClickHouse#114242. That
PR reworks text-index distributed reads and does not carry this guard.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two rounds. Round 1 raised two majors, both about the test rather than the
production hunk, which is unchanged since the first commit. Round 2: an
independent cold re-review found no blocker or major, and the second-model gate
returned zero findings.

Round 1, both fixed

❌ The join arm did not test the carrier it claimed to. Under
select_sequential_consistency = 1 every ReplicatedMergeTree read is pinned
(readLocalSequentialConsistencyImpl builds the pin unconditionally), so with
both join tables replicated the coordinated read was rejected first, no split
marker was planted, and liftSplitAboveJoin returned before ever calling the
broadcast-side check. The arm still reddened, so it looked like a real proof; it
was guarding the coordinated path twice. Fixed by making the coordinated side a
plain MergeTree, which has no sequential-consistency branch and therefore
keeps its split marker. Verified two independent ways: on a throwaway
instrumented build the broadcast check runs 0 times for the old shape, once and
rejects for the new one, and once and accepts for the unpinned control; and
structurally, the old shape loses ReadFromParallelReplicas entirely on the
fixed binary while the new shape keeps it with the join local above.

❌ The join arm's control could not discriminate. Refusing the lift keeps
the split below the join, so ReadFromParallelReplicas is in the plan either
way and a presence check passes in both cases. Both join arms now assert step
order instead, the form used by 04650_pr_plan_based_join_lookup and
04653_pr_plan_based_join_broadcast_side_local_table. The join-order and
join-swap randomizers are pinned, as those siblings do.

⚠️ A claim of "four other unshippable cases" in mergeTreeReadCanBeShipped was
wrong: the function has two return false, and the other four keep-local
mechanisms are file-level. Corrected.

Round 2 verification

Re-derived the mechanism from source rather than from the round-1 conclusion:
serialize contains no reference to max_block_numbers_to_read, deserialize
rebuilds with nullptr, and the pin is what makes the part scan skip parts above
the boundary, so losing it widens the read with no exception. The guard sits
before the supportsReplication() tail, which matters: a plain MergeTree can
also carry a pin through the query context, and a check placed after that tail
would have missed it. Every pin producer in the tree was enumerated; none
escapes the predicate, and the two projection rewrites that can introduce a pin
run after this pass. No existing test combines sequential consistency with
parallel replicas, so no coverage was lost.

💡 Two nits, not blocking. The test's ZooKeeper path is not namespaced by test
number the way the sibling quorum tests are; {database} already makes it
unique per run. And the changelog link line was duplicated in the description,
now removed.

Two flagged asymmetries were deliberately left alone rather than gated
speculatively: checkDistributedReadSupported also rejects input_order_info
(old-interpreter only) and the _part_index / _part_starting_offset virtual
columns, and neither was shown to diverge here. The classic non-plan-based path
has a separate wrong-results hole with a different mechanism, confirmed in the
original thread as pre-existing and out of scope.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Gate Answer
a Deterministic repro? Yes. The mutation reddens identically on every run under clickhouse-test; the oracles are exact integers and exact step strings, not a timing window. Remote-only (parallel_replicas_local_plan = 0, parallel_replicas_prefer_local_replica = 0) makes it deterministic.
b Root cause explained? Yes. select_sequential_consistency clamps the read via max_block_numbers_to_read; serialize does not ship the pin and deserialize rebuilds with nullptr (ReadFromMergeTree.cpp:5894), while mergeTreeReadCanBeShipped never consulted it, so the read was split and each follower read its own unclamped part set.
c Fix matches root cause? Yes. The predicate that decides shippability now tests the property that makes the read unshippable. No widened bound, no reduced dataset, no no-random-* tag, no guard at a crash site.
d Test intent preserved / new tests added? Yes. New test with 4 discriminating assertions plus 3 controls. No existing test weakened or removed. The join arm asserts step ORDER, not step presence: refusing the lift keeps the split below the join, so ReadFromParallelReplicas is in the plan either way and only its position separates the two shapes.
e Both directions demonstrated? Yes. With the guard: 7/7 assertions pass. Guard reverted, nothing else changed: 4 flip (0 -> 1, 45 10 -> 435 30, the join's step order, 10 -> 30) while all 3 controls hold. Both arms run under clickhouse-test, Build IDs asserted against SELECT lower(buildId()) on the running server.
f General across code paths? Yes. mergeTreeReadCanBeShipped has exactly two callers, collectReadsToDistribute (coordinated read) and subtreeHasUnshippableRead (broadcast side of a lifted join); one rejection covers both and the test exercises both. The join arm's coordinated side is a plain MergeTree, which has no sequential-consistency branch and so stays unpinned, keeping its split marker and genuinely reaching the broadcast-side check. The sibling make_distributed_plan path already rejects the same property and is the precedent. Two other checkDistributedReadSupported predicates have no counterpart here; neither was shown to diverge, so neither is speculatively gated.
g Generalizes across inputs? The guard is a boolean over one read property (max_block_numbers_to_read != nullptr), so it is type-wrapper agnostic and there is no value matrix to sweep. The input dimension that matters is plan shape, and both shapes are covered (bare coordinated read, and a join carrying the pin on the broadcast side), in both polarities of the trigger.
h Backward compatible? Yes. No setting, no default change, no serialization format change, so no SettingsChangesHistory.cpp entry is required. The only behavior change is that a query which silently returned unconfirmed rows now runs locally and returns the correct ones.
i Invariants and contracts preserved? Yes. Pure predicate over a const ReadFromMergeTree &; the new branch is an early return false with no allocation, lock, I/O or state mutation, so there is no error path, lifetime or concurrency surface. It can only turn true into false, and only for a pinned read; the false result routes to the keep-local path the function already uses for a refreshable-MV target read.

Both carriers were confirmed reached, not assumed: on a throwaway instrumented build the
broadcast-side check runs exactly once and rejects for the join arm, zero times for a shape where
both tables are pinned, and once-and-accepts for the unpinned control.

Fixture vacuity was checked explicitly, since SYSTEM STOP FETCHES is in-memory only and a
restart evaporates the pin: on the guard-absent arm, active parts = 2, /quorum/status = 1,
unpinned local = 435 30, pinned local = 45 10. The last two differing is the direct proof the
pin clamps. Regression suite passes on the fix arm; 50 randomized runs of the new test all pass,
so no tag and no per-setting clamp were needed.

@groeneai

groeneai commented Aug 11, 2026 •

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @novikd, could you review this? It re-lands a shippability guard that was lost when #112723 closed unmerged: plan-based parallel replicas shipped a read pinned by select_sequential_consistency, and since the pin is not serialized the followers rebuilt it with max_block_numbers_to_read = nullptr and returned rows the insert quorum never confirmed.

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7e6cb4c]

Summary: ✅


AI Review

Summary

This PR keeps select_sequential_consistency reads local in plan-based parallel replicas by refusing to ship ReadFromMergeTree steps with pinned block numbers. The targeted wrong-results hole looks fixed, but the same shippability helper still misses one silent-divergence guard already discussed on the PR and one additional keep-local guard for STREAM, so I cannot treat the change as complete yet.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/Optimizations/applyParallelReplicas.cpp:104] [dismissed by author -- https://github.com/Keep a read with pinned block numbers local in plan-based parallel replicas #114263#discussion_r3762728334] Reads exposing _part_index / _part_starting_offset are still shippable even though a remote replica rebuilds those values from its own part_index_in_query / part_starting_offset_in_query. The coordinator protocol serializes only part identity and ranges (RangesInDataPartDescription), not the initiator's numbering, so a replica with a different visible part set or order can return different virtual-column values for the same query. Suggested fix: reject those columns in mergeTreeReadCanBeShipped, mirroring checkDistributedReadSupported.

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/applyParallelReplicas.cpp:104] STREAM reads still pass mergeTreeReadCanBeShipped, so parallel_replicas_plan_based can turn a locally executable query into a late SUPPORT_IS_DISABLED exception when ReadFromMergeTree::serialize discovers query_info.isStream(). This path is supposed to fall back to a local read, not ship an unexecutable fragment. Suggested fix: keep read.getQueryInfo().isStream() local here as well.
Tests
  • ⚠️ Add a focused regression for a STREAM query with parallel_replicas_plan_based = 1 that proves the read stays local instead of failing during fragment serialization.
Final Verdict

Request changes.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 6/6 (100.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 Aug 12, 2026
/// The pinned block-number boundary is not serialized: a follower rebuilds the read with
/// max_block_numbers_to_read = nullptr and would read past the initiator's snapshot boundary.
if (read.hasPinnedBlockNumbers())
return 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 same non-serialized-contract problem still exists for _part_index / _part_starting_offset. This helper now keeps pinned block numbers local, but it still ships reads exposing the part-order virtual columns even though the remote fragment is rebuilt from each replica's own snapshot_data.parts, and those virtuals are populated from replica-local part_index_in_query / part_starting_offset_in_query. Their documented meaning is relative to the full query result, so a follower with a different part split or merge history can surface different values for the same query. checkDistributedReadSupported already treats these columns as unshippable; please mirror that check here as well, or we keep a second correctness hole in plan-based parallel replicas.

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 flagged this asymmetry in the PR description rather than gating it, and re-measured it this round on a wider fixture without finding a divergence.

Three parts of 400k rows each with disjoint value ranges, so a replica-local renumbering would show. arraySort(groupUniqArray(_part_index)) is [0,1,2] for the ground truth, for plan-based PR with parallel_replicas_local_plan = 1, and for local_plan = 0. _part_starting_offset is [0,400000,800000] in every arm, and grouping by _part_index gives identical count(), min(a), max(a) in all three.

Since no divergence is demonstrated, adding the rejection would be speculative defensive plumbing, which I have been asked not to do (#105675, #106024). If you have a part layout that does produce different values for the same query, that is the thing to post and I will gate it.

The flaky check caught 04853 failing 1 of 50 runs on amd_debug with
"Expected server error code: 319 but got: 286": the deliberately
unsatisfiable quorum insert raised UNSATISFIED_QUORUM_FOR_PREVIOUS_WRITE
instead of UNKNOWN_STATUS_OF_INSERT.

Both are legitimate outcomes of that insert and both leave `/quorum/status`
set, which is the only state the rest of the test depends on. 319 comes from
waitForQuorum timing out on its own insert_quorum_timeout; 286 comes from
checkQuorumPrecondition finding a status node already present when the
insert starts, which a keeper retry of the same insert can produce (the CI
test config installs insert_keeper_fault_injection_probability = 0.01).

Measured on a local 3-replica cluster: with that fault injection and
max_insert_threads = 4, 40 attempts gave 37x 319 and 3x 286, no other code
and never a silent success, and every 286 left the pin canonical
(select_sequential_consistency = 1 -> (45, 10), = 0 -> (435, 30)).

The assertion is the only thing widened, so the test keeps its full
strength: on a binary without the shippability guard it still fails on all
four discriminating lines (split marker, the (45, 10) row set, the join step
order and the join count), while the two unpinned lines stay fixed and act
as an arming oracle -- a fixture that failed to leave the boundary set
prints 10 instead of 30 there and fails loudly instead of passing vacuously.

Same fix and wording as the sibling 04283, which accepts both codes on the
identically shaped insert.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7e6cb4c58 with master 55e5ac561 (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
Binary Master PR Δ
programs/clickhouse-stripped 704.51 MiB 701.48 MiB -3.03 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

7 translation units recompiled, 17 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 - ec11d7f

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
Stress test (arm_debug) / Logical error: Coordination mode mismatch for stream A: got B, expected C (STID: 6117-726a) pre-existing trunk signature carried by another test, not this diff #114279 (mine, open)
CH Inc sync private sync CH Inc sync (private, not actionable by me)

176 check-runs, all completed: 1 failure, 173 skipped, 1 success, and the praktika report has 0
dropped jobs, so the single red is the whole failure set.

The row is not this PR's. The aborting query belongs to 04241_parameterized_view_used_twice:
the log reads Coordination mode mismatch for stream test_3.testing_105153, and
testing_105153 is that test's table, named after issue #105153, appearing 8 times in it and
nowhere else. My own test 04853_pr_plan_based_pinned_block_numbers produced no verdict in this
job at all, and the run has exactly two Fail lines: the job itself and this one.

04241 carries -- Tags: no-parallel-replicas. The stress runner appends
enable_parallel_replicas=1 to --client-option for a random subset of its workers regardless
of tags, and that injection appears 15 times in this job's log, so the tagged test ran with the
feature on and hit the coordinator keyed on stream_id alone. That is the defect #114279 fixes,
and #114279 is absent from the tree that ran here: its head is not among the 50 entries in this
job's master_commits, so this build predates it. Rather than a commit-distance argument, the
attribution is the carrier name plus the tag plus the injection count.

Breadth confirms it is not mine: over 30 days STID 6117-726a has 15 hits across 15 distinct
pull requests and 0 on master, with the onset on 2026-08-07, well before this branch existed.
My diff is 3 files and touches applyParallelReplicas.cpp plus one new test, with no
coordinator or stream-keying path.

No Fast test, Style check, Bugfix validation or Config Workflow red, so nothing is
PR-caused.

Session id: cron:our-pr-ci-monitor:20260812-073000

…lan-based-pinned-block-numbers

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/applyParallelReplicas.cpp

/// The pinned block-number boundary is not serialized: a follower rebuilds the read with
/// max_block_numbers_to_read = nullptr and would read past the initiator's snapshot boundary.
if (read.hasPinnedBlockNumbers())

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.

hasPinnedBlockNumbers is not the only initiator-local read contract missing here. A STREAM read still passes mergeTreeReadCanBeShipped, so parallel_replicas_plan_based can take a query that would execute locally, insert a split, and then fail later when ReadFromMergeTree::serialize rejects query_info.isStream() because that modifier is not serializable. This path is supposed to keep unsupported reads local rather than turn them into an exception, so the same helper needs a read.getQueryInfo().isStream() rejection as well (which will also cover the broadcast side through subtreeHasUnshippableRead).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7e6cb4c

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

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, parallel) / 02805_distributed_queries_timeouts flaky, pre-existing (10 rows / 10 unrelated PRs / 1 master hit in 90d, first 2026-07-14) #112229 (mine, open)

Not caused by this PR: the diff is applyParallelReplicas.cpp plus one stateless test, and the
failure is a SOCKET_TIMEOUT (return code 209) on a distributed read, with the reproducibility
check reporting Failed 0 out of 3 reruns.

#112229 fixes the latched timer-readiness flag that turns one epoll wake reporting both the timer
and the socket as ready into a permanent timeout on the connection. Its own description already
cites the same carrier as this row, Stateless tests (arm_asan_ubsan, azure, parallel) on an
unrelated PR, so the attribution is not a same-area coincidence.

Session id: cron:our-pr-ci-monitor:20260821-203000

@nickitat
nickitat added this pull request to the merge queue Aug 25, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to no response for status checks Aug 25, 2026
@nickitat
nickitat added this pull request to the merge queue Aug 25, 2026
Merged via the queue into ClickHouse:master with commit b5409ab Aug 25, 2026
349 of 350 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 26, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer

Shell reproducer — set BIN to a ClickHouse binary path and run with bash; requires the referenced test fixtures from the repo.

#!/bin/bash
BIN="${BIN:-./clickhouse}"  # path to the ClickHouse binary under test
# ClickHouse PR #114263 — plan-based parallel replicas ships a read pinned by
# select_sequential_consistency; followers rebuild it without max_block_numbers_to_read
# and return rows the insert quorum never confirmed.
# Needs a real server + Keeper + a parallel-replicas cluster (clickhouse local cannot express it).
set -uo pipefail
PORT=$(( (RANDOM % 2000) + 28000 ))
KPORT=$(( PORT + 1 ))
RPORT=$(( PORT + 2 ))
IPORT=$(( PORT + 3 ))
WORK=$(mktemp -d /tmp/ch_pr114263.XXXXXX)
CFG="$WORK/config.xml"
trap 'kill %1 2>/dev/null; wait 2>/dev/null; rm -rf "$WORK"' EXIT

cat > "$CFG" <<EOF
<clickhouse>
    <logger><level>none</level><console>false</console></logger>
    <tcp_port>${PORT}</tcp_port>
    <listen_host>127.0.0.1</listen_host>
    <path>${WORK}/data/</path>
    <tmp_path>${WORK}/tmp/</tmp_path>
    <user_files_path>${WORK}/user_files/</user_files_path>
    <mark_cache_size>536870912</mark_cache_size>
    <interserver_http_port>${IPORT}</interserver_http_port>
    <interserver_http_host>127.0.0.1</interserver_http_host>
    <process_query_plan_packet>true</process_query_plan_packet>
    <users>
        <default>
            <password></password>
            <profile>default</profile>
            <quota>default</quota>
            <networks><ip>::/0</ip></networks>
        </default>
    </users>
    <profiles><default></default></profiles>
    <quotas><default/></quotas>
    <keeper_server>
        <tcp_port>${KPORT}</tcp_port>
        <server_id>1</server_id>
        <log_storage_path>${WORK}/coordination/log</log_storage_path>
        <snapshot_storage_path>${WORK}/coordination/snapshots</snapshot_storage_path>
        <coordination_settings><operation_timeout_ms>10000</operation_timeout_ms><session_timeout_ms>30000</session_timeout_ms></coordination_settings>
        <raft_configuration>
            <server><id>1</id><hostname>127.0.0.1</hostname><port>${RPORT}</port></server>
        </raft_configuration>
    </keeper_server>
    <zookeeper>
        <node><host>127.0.0.1</host><port>${KPORT}</port></node>
    </zookeeper>
    <remote_servers>
        <test_cluster_one_shard_three_replicas_localhost>
            <shard>
                <internal_replication>true</internal_replication>
                <replica><host>127.0.0.1</host><port>${PORT}</port></replica>
                <replica><host>127.0.0.1</host><port>${PORT}</port></replica>
                <replica><host>127.0.0.1</host><port>${PORT}</port></replica>
            </shard>
        </test_cluster_one_shard_three_replicas_localhost>
    </remote_servers>
</clickhouse>
EOF

"$BIN" server --config-file="$CFG" -- --max_server_memory_usage=8000000000 --memory_worker_use_cgroup=0 --memory_worker_dynamic_hard_limit=0 >"$WORK/server.log" 2>&1 &
for _ in $(seq 1 60); do
    "$BIN" client --port "$PORT" --query "SELECT 1" >/dev/null 2>&1 && break
    sleep 1
done
if ! "$BIN" client --port "$PORT" --query "SELECT 1" >/dev/null 2>&1; then
    echo "[repro] server failed to start (binary unusable) — inconclusive"
    exit 2
fi
CL() { timeout 60 "$BIN" client --port "$PORT" "$@"; }

# Keeper (embedded) must be serving before any ReplicatedMergeTree DDL.
for _ in $(seq 1 60); do
    CL --query "SELECT count() FROM system.zookeeper WHERE path = '/'" >/dev/null 2>&1 && break
    sleep 1
done

# The plan-based parallel-replicas path is what this bug lives in. If the build
# predates the settings, the feature is absent — inconclusive, never "clean".
probe=$(CL --query "SELECT 1 SETTINGS parallel_replicas_plan_based = 1, enable_parallel_replicas = 1" 2>&1)
if [ $? -ne 0 ]; then
    echo "[repro] parallel_replicas_plan_based unsupported — feature absent on this build: $probe"
    exit 2
fi

# Fixture: two replicas of one ReplicatedMergeTree, 10 confirmed rows, then a
# quorum insert of 20 rows that cannot be confirmed (second replica not fetching).
# /quorum/status stays set, so select_sequential_consistency pins the read below it.
setup=$(CL --multiquery --query "
DROP TABLE IF EXISTS quorum1_pr_pinned SYNC;
DROP TABLE IF EXISTS quorum2_pr_pinned SYNC;
CREATE TABLE quorum1_pr_pinned (n UInt64) ENGINE = ReplicatedMergeTree('/clickhouse/tables/pr_pinned_114263', 'r1') ORDER BY tuple();
CREATE TABLE quorum2_pr_pinned (n UInt64) ENGINE = ReplicatedMergeTree('/clickhouse/tables/pr_pinned_114263', 'r2') ORDER BY tuple();
SET insert_keeper_fault_injection_probability = 0;
INSERT INTO quorum1_pr_pinned SELECT number FROM numbers(10);
SYSTEM SYNC REPLICA quorum2_pr_pinned;
SYSTEM STOP FETCHES quorum2_pr_pinned;
" 2>&1)
if [ $? -ne 0 ]; then
    echo "[repro] fixture setup failed — inconclusive: $setup"
    exit 2
fi

# Expected to fail; the failure is what leaves the quorum boundary pinned.
CL --query "INSERT INTO quorum1_pr_pinned SELECT number + 10 FROM numbers(20)" \
   --insert_keeper_fault_injection_probability=0 \
   --insert_quorum=2 --insert_quorum_parallel=0 --insert_quorum_timeout=0 >/dev/null 2>&1

# The initiator's own pinned read must be (45, 10). If it is not, the fixture
# did not pin anything and nothing below is meaningful.
baseline=$(CL --query "SELECT sum(n), count() FROM quorum1_pr_pinned" \
    --select_sequential_consistency=1 --enable_parallel_replicas=0 2>&1)
if [ "$baseline" != "45	10" ]; then
    echo "[repro] fixture did not pin the read (local pinned read = '$baseline') — inconclusive"
    exit 2
fi

# The read under test: plan-based parallel replicas, executed remote-only. The pin
# is not serialized, so a shipped read returns the 20 unconfirmed rows.
out=$(CL --query "SELECT sum(n), count() FROM quorum1_pr_pinned" \
    --enable_analyzer=1 \
    --enable_parallel_replicas=1 --max_parallel_replicas=3 \
    --cluster_for_parallel_replicas=test_cluster_one_shard_three_replicas_localhost \
    --parallel_replicas_plan_based=1 \
    --automatic_parallel_replicas_mode=0 \
    --parallel_replicas_min_number_of_rows_per_replica=0 \
    --select_sequential_consistency=1 \
    --parallel_replicas_local_plan=0 \
    --parallel_replicas_prefer_local_replica=0 2>&1)
rc=$?
if [ "$rc" = "124" ]; then
    echo "[repro] pinned parallel-replicas read timed out"
    exit 2
fi
if [ $rc -ne 0 ]; then
    echo "[repro] pinned parallel-replicas read errored — inconclusive: $out"
    exit 2
fi

echo "[repro] pinned read via plan-based parallel replicas = '$out' (expected '45	10')"
if [ "$out" = "45	10" ]; then
    exit 0
fi
echo "[repro] WRONG RESULT: unconfirmed rows leaked past the quorum boundary"
exit 1

Results:

  • Culprit PR: Plan based parallel replicas. Part 1 (aggregation) Plan based parallel replicas. Part 1 (aggregation) #108504
  • Reproduces on: 26.7
  • Does not reproduce on: master
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 unknown
  • ✓ 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.7.

CC introducing PR author: @devcrafter
CC introducing PR reviewer: @KochetovNicolai @copilot-pull-request-reviewer

CC component owner: @nickitat

Analysis metadata

comp-parallel-replicas · Severity P2 · Finding phase_d_pr114263

  • Verified against master build 573230bfe668 (aarch64)
  • Feature not present (repro inconclusive — the affected code path postdates these releases): 26.6, 26.5, 26.3, 25.8
  • Caused by: Plan based parallel replicas. Part 1 (aggregation) #108504 (commit 7348f2f0bdae, found by bisecting in several steps)

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

One correction to that target list. I measured this just now.

26.8 is affected too, and it is not in the tested set above. It was cut 2026-08-24T08:20Z, one day before this PR merged (2026-08-25T23:54Z), so it inherited the culprit but not the fix: compare/26.8...7348f2f0bdae (the #108504 merge) is behind with ahead_by = 0, while compare/26.8...b5409abf6ddc is diverged. Its applyParallelReplicas.cpp is the same shape as master's and carries no hasPinnedBlockNumbers call, and 04853_pr_plan_based_pinned_block_numbers.sql is absent there.

26.7 gives the same two readings, which matches your reproducer. 26.6 and 26.3 are out of scope for the reason you inferred: compare/<branch>...7348f2f0bdae is diverged on both, so the plan-based path is genuinely not present (on 26.6 the file does not exist at all).

So the gap is exactly 26.7 and 26.8, and one label covers both: could a maintainer apply v26.7-must-backport? Per cherry_pick.py, a version-specific label marks the oldest release to reach and expands to it plus every newer active release branch, and 26.8 is the only newer active one.

One thing to expect from the cherry-pick: it should apply on 26.8, but not on 26.7. The whole change is a single hunk inside mergeTreeReadCanBeShipped, and that function does not exist on 26.7, where applyParallelReplicas.cpp is still at the #108504 Part 1 shape (7968 bytes against 30050 on 26.8). On 26.7 the guard needs placing by hand wherever read shipping is gated there.

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 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.

5 participants