Repository navigation
Keep a read with pinned block numbers local in plan-based parallel replicas - #114263
Conversation
…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]>
Internal second-model reviewTwo rounds. Round 1 raised two majors, both about the test rather than the Round 1, both fixed ❌ The join arm did not test the carrier it claimed to. Under ❌ The join arm's control could not discriminate. Refusing the lift keeps
Round 2 verification Re-derived the mechanism from source rather than from the round-1 conclusion: 💡 Two nits, not blocking. The test's ZooKeeper path is not namespaced by test Two flagged asymmetries were deliberately left alone rather than gated |
Pre-PR validation gate (a-i)
Both carriers were confirmed reached, not assumed: on a throwaway instrumented build the Fixture vacuity was checked explicitly, since |
|
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. |
|
Workflow [PR], commit [7e6cb4c] Summary: ✅
AI ReviewSummaryThis PR keeps Findings❌ Blockers
Tests
Final VerdictRequest changes. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code |
| /// 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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units7 translation units recompiled, 17 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - ec11d7fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
176 check-runs, all completed: 1 failure, 173 skipped, 1 success, and the praktika report has 0 The row is not this PR's. The aborting query belongs to 04241 carries Breadth confirms it is not mine: over 30 days STID 6117-726a has 15 hits across 15 distinct No 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()) |
There was a problem hiding this comment.
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).
CI finish ledger - 7e6cb4cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not caused by this PR: the diff is #112229 fixes the latched timer-readiness flag that turns one epoll wake reporting both the timer Session id: cron:our-pr-ci-monitor:20260821-203000 |
b5409ab
ReproducerShell reproducer — set #!/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 1Results:
Backport the fix to CC introducing PR author: @devcrafter CC component owner: @nickitat Analysis metadata
|
|
One correction to that target list. I measured this just now.
So the gap is exactly One thing to expect from the cherry-pick: it should apply on |
Related: #112723
Changelog category (leave one):
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_consistencyclamps aReplicatedMergeTreeread to the parts the initiator saw confirmed by the insert quorum, viamax_block_numbers_to_read. That pin is not serialized:ReadFromMergeTree::deserializerebuilds a shipped read withmax_block_numbers_to_read = nullptr.mergeTreeReadCanBeShippeddid 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()tomergeTreeReadCanBeShipped, mirroring the existing rejection for the same property inmake_distributed_plan(checkDistributedReadSupported). The predicate gates bothcollectReadsToDistribute(the coordinated read) andsubtreeHasUnshippableRead(the broadcast side of a lifted join), so one check covers both carriers. Returningfalserather than throwing matches how this path already keeps a refreshable-MV target read local:make_distributed_planis 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.
checkDistributedReadSupportedhas three further predicates with no counterpart here (input_order_info,isStream(), and the_part_index/_part_starting_offsetvirtual 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 aSTREAMtable expression before these settings are built.Workflow [PR]
Sync PR [sync-upstream/pr/114263]
Version info
26.9.1.126(included in26.9and later)