Skip to content

Size parallel replicas mark_segment_size by active replica count - #109377

Closed
groeneai wants to merge 64 commits into
ClickHouse:masterfrom
groeneai:groeneai/parallel-replicas-active-total-nodes-count
Closed

groeneai wants to merge 64 commits into
ClickHouse:masterfrom
groeneai:groeneai/parallel-replicas-active-total-nodes-count

Conversation

@groeneai

@groeneai groeneai commented Jul 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #107805

Changelog category (leave one):

  • Improvement

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

Parallel replicas now size the automatic parallel_replicas_mark_segment_size by the number of active replicas, consistent with the reading coordinator, so registered-but-inactive replicas no longer skew segment sizing.

Description

Follow-up to #107805 (the optional total_nodes_count / mark_segment_size alignment noted in review).

#107805 made the parallel replicas reading coordinator size itself by the number of active replicas (excluding registered-but-inactive ones), so mark segments are not assigned to replicas that never participate. The automatic mark_segment_size heuristic in ReadFromMergeTree, however, still derived its work-distribution denominator from getAllNodeCount() (the registered count via ParallelReadingExtension::total_nodes_count). When a replica was registered but inactive the two sizings disagreed.

This sources ParallelReadingExtension::total_nodes_count from the active replica count through a shared ClusterProxy::getActiveReplicasCountForParallelReplicas helper that mirrors the coordinator's sizing exactly: the active count when liveness is known, the registered count when it is not (or when it does not line up with the cluster definition), and a zero-active safety net that falls back to the registered count. total_nodes_count feeds only chooseSegmentSize, whose result is clamped to {128, 1024, 16384} and is never used for indexing, so this cannot go out of range (replica numbering stays bounded by the registered count) and can only make segments smaller, which balances work no worse.

The existing integration test test_parallel_replicas_skip_inactive_replicas is extended to assert the segment-sizing heuristic sees the active replica count (2), not the registered count (3), when one of three replicas is stopped. Verified the added assertion fails before this change and passes after; the all_groups sibling test is unaffected.


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

PR ClickHouse#107805 sized the parallel replicas reading coordinator by the number of
active replicas (excluding registered-but-inactive ones) so mark segments are
not assigned to replicas that never participate. The mark_segment_size
heuristic in ReadFromMergeTree still derived its work-distribution denominator
from getAllNodeCount() (the registered count), so the two sizings disagreed
when a replica was registered but inactive.

Source ParallelReadingExtension::total_nodes_count from the active replica
count via a shared ClusterProxy::getActiveReplicasCountForParallelReplicas
helper that mirrors the coordinator sizing (active count when liveness is
known, registered count otherwise, with a zero-active safety net). This keeps
the segment-size denominator consistent with the coordinator. It cannot go out
of range and only makes segments smaller, which balances work no worse.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. test_parallel_replicas_skip_inactive_replicas: 3-node Replicated DB, stop node3, run SELECT sum(key) with parallel replicas. Deterministic (not timing-based).
b Root cause explained? #107805 sizes the reading coordinator by the active replica count; ReadFromMergeTree still sized ParallelReadingExtension::total_nodes_count from getAllNodeCount() (registered count). total_nodes_count feeds chooseSegmentSize's denominator, so with a registered-but-inactive replica the segment-size heuristic used a larger count than the coordinator.
c Fix matches root cause? Yes. Sources total_nodes_count from a shared ClusterProxy::getActiveReplicasCountForParallelReplicas that mirrors the coordinator sizing (active when liveness known, registered otherwise, zero-active safety net).
d Test intent preserved / new tests added? Preserved. Extended the existing #107805 test with an assertion that the segment-sizing heuristic sees the active count (2), not the registered count (3).
e Both directions demonstrated? Yes. WITH fix: test PASSES (number_of_replicas=2, in log). WITHOUT fix (revert the two sites to getAllNodeCount()): test FAILS (assert contains_in_log("number_of_replicas=2,") -> False; log shows =3,). Build IDs distinct (d7111ae7 vs c074ad2e).
f Fix is general across code paths? Yes. Both ParallelReadingExtension sites that CONSUME total_nodes_count are fixed (readFromPoolParallelReplicas, getParallelReadingExtension). The InOrder and empty-parts sites pass an explicit mark_segment_size (0/1) and never read total_nodes_count. total_nodes_count has exactly one functional consumer: chooseSegmentSize.
g Fix generalizes across inputs? Yes. Helper handles: liveness unknown (empty), liveness/cluster size mismatch, and zero active replicas -> all fall back to the registered count, matching prepareConnectionPoolsForParallelReplicas.
h Backward compatible? Yes. No setting/format/wire change. Segment size is a runtime heuristic clamped to {128,1024,16384}; effect is equal or smaller segments (per reviewer: cannot reintroduce skew).
i Invariants and contracts preserved? Yes. total_nodes_count is only a work-distribution denominator, never used for indexing/replica numbering; the coordinator takes mark_segment_size from the first announcement. Replica numbering stays bounded by the registered count, so no out-of-range is possible.

Session id: cron:clickhouse-worker-slot-1:20260703-215400

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @tiandiwonder @nickitat — this is the optional total_nodes_count follow-up to #107805: it sources the automatic mark_segment_size denominator from the active replica count (via a shared getActiveReplicasCountForParallelReplicas helper mirroring the coordinator sizing) instead of getAllNodeCount(), so segment sizing matches the coordinator. Non-blocking, can't go out of range.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5d6927b]

Summary: ✅


AI Review

Summary

Reviewed #109377 at 5d6927b7b7884a50baebf1da0e631d5ccbc928a4, including all changed files and all 21 prior review threads and their replies. Parallel-replica segment sizing and remote-disk task sizing now consume the coordinator's active, capped replica count through scoped Context state and the existing ClientInfo field. No new or outstanding findings. Consumers of the expanded local _shard_num block were traced: FunctionGetSpecialScalar::createScalar and FunctionGetScalarOverloadResolver consume column zero; getShardScopeForCluster checks provenance; getShippedShardNum consumes the number without resolving a cluster; Context copies retain the complete block. The classic, plan-based, serialized-plan, projection, ordered-read, and INSERT SELECT paths were followed through their count consumers.

Missing context / blind spots
  • ⚠️ On 2026-11-20, current-head CI is still running, with integration and unit-test jobs pending. The report helper's green indicators include pending jobs. Relevant inactive-replica, cap, S3, asymmetric-shard, local/alien-scope, and plan-based regression cases passed on the previous head. No local build or tests were run because this checkout has no build directory or installed binary. Completion of current-head CI closes this validation gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 3, 2026
…through it

Addresses two parity gaps in the mark-segment-size heuristic raised in review.

1. getActiveReplicasCountForParallelReplicas recomputed only a partial copy of the
   coordinator's sizing: it excluded inactive replicas but did not force the initiator's
   own replica active, nor cap by max_parallel_replicas. So total_nodes_count could still
   diverge from the coordinator (3 active + max_parallel_replicas=2: coordinator 2, helper
   3; transient-missing local znode + 1 peer: coordinator forces local back in = 2, helper
   1). The coordinator sizing (initiator-force + count + cap) is now factored into two
   shared free functions (findLocalReplicaIndexForLiveness, countAndCapReplicas) used by
   both prepareConnectionPoolsForParallelReplicas and the heuristic, so they size by the
   same count. The two test-only failpoints stay coordinator-only.

2. Both PoolSettings.total_query_nodes populators in ReadFromMergeTree still used
   min(getAllNodeCount(), max_parallel_replicas), the registered-and-capped count. On
   remote-disk reads that value drives calculateMinMarksPerTask
   (sum_marks / (threads * total_query_nodes) / 2), the other half of chooseSegmentSize, so
   fixing only total_nodes_count left the heuristic partly keyed off the registered count
   and could be a no-op when that term dominates. Both now use the active-and-capped helper.

Tests: extend the local-disk skip-inactive test with a max_parallel_replicas cap case and a
total_query_nodes assertion; add an S3-backed test that exercises the remote-disk task-size
path (a local-disk test cannot reach it). Verified each new assertion fails before and passes
after.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

Both addressed in 500fb8a.

1. Exact coordinator parity. The coordinator's sizing (initiator-force + count + max_parallel_replicas cap) is now factored into two shared free functions, findLocalReplicaIndexForLiveness and countAndCapReplicas, called by both prepareConnectionPoolsForParallelReplicas and getActiveReplicasCountForParallelReplicas, so the heuristic and the coordinator size by the same count instead of a partial recompute. The helper now validates liveness against the cluster definition, forces the local (initiator) replica active, then caps by max_parallel_replicas. Both divergences you listed are gone:

  • 3 active + max_parallel_replicas=2: coordinator 2, helper now 2 (was 3).
  • transient-missing local active znode + 1 healthy peer: coordinator forces the local replica back in = 2, helper now 2 (was 1).

The two test-only failpoints stay coordinator-only (not applied in the heuristic; the ONCE insert-select-drop failpoint is not double-consumed).

2. Remote-disk total_query_nodes. Both populators (ReadFromMergeTree::read and spreadMarkRangesAmongStreamsWithOrder) now source total_query_nodes from the same getActiveReplicasCountForParallelReplicas helper instead of min(getAllNodeCount(), max_parallel_replicas), so the calculateMinMarksPerTask term (sum_marks / (threads * total_query_nodes) / 2) uses the active-and-capped count on remote-disk reads.

Tests. The local-disk test cannot reach the remote-disk branch, as you noted, so I added test_parallel_replicas_skip_inactive_replicas_s3 (MinIO, S3 storage policy, merge_tree_min_bytes_per_task_for_remote_reading=0 to force the remote task-size path) asserting total_query_nodes=2 when one of three replicas is stopped. I also added a max_parallel_replicas cap case to the local-disk test (3 active, max_parallel_replicas=2, so the coordinator caps to 2), which exercises the cap divergence without any inactive replica. Each new assertion was verified to fail before this commit and pass after; the coordinator failpoint regression tests (test_parallel_replicas_local_replica_forced_inactive, test_parallel_replicas_insert_select_coordinator_reuse) still pass, confirming the shared-helper refactor preserved the coordinator behavior.

@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Cap gap: 3 active replicas + max_parallel_replicas=2 deterministically logs number_of_replicas=3 / total_query_nodes=3 before the fix. Remote-disk gap: stop 1 of 3 replicas, max_parallel_replicas=3, S3 storage, merge_tree_min_bytes_per_task_for_remote_reading=0 deterministically logs total_query_nodes=3 before the fix.
b Root cause explained? Yes. getActiveReplicasCountForParallelReplicas recomputed a partial copy of the coordinator sizing: it excluded inactive replicas but skipped the initiator-force and the max_parallel_replicas cap, so total_nodes_count diverged. Separately, both total_query_nodes populators used min(getAllNodeCount(), max_parallel_replicas) (registered count), which on remote disks drives calculateMinMarksPerTask = the other half of chooseSegmentSize, so the heuristic stayed keyed off the registered count there.
c Fix matches root cause? Yes. Coordinator sizing (initiator-force + count + cap) is factored into two shared functions used by both the coordinator and the heuristic, so they compute the identical count; and both total_query_nodes sites now call the same helper. No band-aids.
d Test intent preserved / new tests added? Yes. Existing assertions unchanged; added a max_parallel_replicas cap case + total_query_nodes assertion to the local-disk test, and a new S3 test for the remote-disk path a local test cannot reach. Coordinator failpoint regression tests still pass.
e Both directions demonstrated? Yes. Cap test: FAIL (number_of_replicas=3) before, PASS (=2) after. S3 test: FAIL (total_query_nodes=3) before, PASS (=2) after. Pre-fix binary built by reverting only the two production edits.
f Fix is general across code paths? Yes. All four total_nodes_count / total_query_nodes consuming sites for parallel replicas now route through the one helper; the coordinator and heuristic share the same two functions, so a future divergence cannot reappear in only one of them.
g Fix generalizes across inputs? Yes. The helper is replica-count logic, independent of column datatypes / type wrappers. Covered input axes: liveness known vs unknown vs size-mismatch (fall back to registered), zero-active safety net, max_parallel_replicas above vs below the active count, and the initiator-inactive transient (forced active).
h Backward compatible? Yes. No settings, on-disk, wire, or replication format changed. Only the internal segment-size / task-size heuristic denominators change, and only toward the value the coordinator already uses; segment size stays clamped to {128,1024,16384}. No SettingsChangesHistory.cpp change needed.
i Invariants and contracts preserved? Yes. getActiveReplicasCountForParallelReplicas returns >= 1 (zero-active fallback to the registered count), so no division by zero in chooseSegmentSize / calculateMinMarksPerTask. prepareConnectionPoolsForParallelReplicas still returns {pools, max_replicas_to_use} with the same is_active-clearing semantics; the two test-only failpoints remain coordinator-only and the ONCE failpoint is consumed exactly once.

Session id: cron:clickhouse-worker-slot-3:20260703-233900

merge_tree_min_bytes_per_task_for_remote_reading = 0 made the second term of
calculateMinMarksPerTask's min() zero, so heuristic_min_marks collapsed to 0
and total_query_nodes could not change min_marks_per_task or the segment size.
The test only proved the total_query_nodes trace line, not the remote-disk
outcome finding ClickHouse#2 is about.

Use a large positive merge_tree_min_bytes_per_task_for_remote_reading so the
marks term wins the min(), pin max_threads = 1, and use a small index
granularity so sum_marks / (threads * total_query_nodes) / 2 stays above the
floor for both replica counts. Read sum_marks from system.parts and assert the
resulting min_marks_per_task equals the active-count value (195) and not the
registered-count value (130). Segment size cannot isolate this because
number_of_replicas is already the active count; min_marks_per_task is the only
quantity total_query_nodes alone drives.

Verified: fails before the total_query_nodes fix (logs min_marks_per_task=130),
passes after (195).
getActiveReplicasCountForParallelReplicas reads live liveness state, and after
routing both total_query_nodes and the ParallelReadingExtension node count
through it, ReadFromMergeTree called it at several independent sites within a
single read. If a replica dropped or came back between two of those calls,
calculateMinMarksPerTask (via PoolSettings.total_query_nodes) and
chooseSegmentSize (via ParallelReadingExtension::total_nodes_count) could size
against different denominators on the same query.

Compute the count once per ReadFromMergeTree step (memoized) and reuse it at
every segment-sizing consumer, so both halves of chooseSegmentSize always see
the same active-and-capped replica count. Each node builds its own
ReadFromMergeTree, so the snapshot stays per-node-per-read.

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

clickhouse-gh Bot commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.60% 85.60% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.80% 77.80% +0.00%

Changed lines: Changed C/C++ lines covered: 64/84 (76.19%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ab625ac

CI fully finished: Finish Workflow and Mergeable Check both green, no queued/running jobs. There are no failed checks on this head, so no failure needs an owner. All five clickhouse-gh[bot] review findings on earlier commits were addressed in-thread; the non-local-plan cross-node parity residual is tracked as a separate follow-up. Advancing to review.

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

@nickitat nickitat self-assigned this Jul 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Dear @nickitat, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@alexey-milovidov alexey-milovidov self-assigned this Aug 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5d6927b7b with master 463f45f5f (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.

Object file sizes

492 object files changed (+72.69 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/ClusterProxy/executeQuery.cpp.o 629.29 KiB 646.32 KiB +17.03 KiB (+2.71%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5a733c6

Every failure below has an owner: a fixing PR (ours 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 (amd_asan_ubsan) logical error Equal values are not contiguous within the range assumed to be sorted, aborting in DistinctSortedStreamTransform::transform via getEqualRangeEndAssumeSorted #110778 (ours, open) - it fixes exactly this abort, and its description cites the same message

The abort is a DISTINCT-in-order sorted-range assumption in
src/Processors/Transforms/DistinctSortedStreamTransform.cpp:184 reached through
SortCursor.h:813 and ColumnVector.cpp:459. This PR changes parallel replicas
mark_segment_size sizing (ClusterProxy/executeQuery.cpp, ReadFromMergeTree.cpp,
MergeTreeReadPoolParallelReplicas.cpp) and does not touch DISTINCT, sorting-property
inference or column range logic, so it cannot reach that assertion.

Session id: cron:our-pr-ci-monitor:20260818-160000

@groeneai groeneai added the groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR label Aug 19, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into the branch (2adcb13). The merge was clean: master changed Context.cpp and ReadFromMergeTree.{h,cpp}, which this PR also edits, but there were no conflicts, clickhouse builds on the merged tree, and the PR diff against master is unchanged. Public CI was green on the previous head, and there are no unresolved review threads. The only red check was CH Inc sync, which failed in the private-only Iceberg compaction test described above, so the new sync run should show whether that test now passes.

# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into the branch (6c02271) to resolve the conflict in src/Processors/QueryPlan/ReadFromMergeTree.cpp: master (#119350) replaced the ParallelReadingExtension stream id data.getStorageID().getFullTableName() with getParallelReplicasStreamId, while this PR changed the replica count argument in the same constructor calls. The resolution keeps both: getActiveReplicasCountForSegmentSizing for the replica count and getParallelReplicasStreamId for the stream id. As before, the in-order pool and announceEmptyReadRangesToCoordinatorIfInitiator still use getAllNodeCount. clickhouse builds on the merged tree, and the PR diff against master is unchanged.

alexey-milovidov and others added 3 commits November 3, 2026 06:05
…of worker startup order

The coordinator can hand all ranges to the first replica that asks and cancel
the others before their queries start, so counting nodes with a secondary
query in `query_log` (`test_parallel_replicas_alien_shard_scope`) or requiring
a log line from `n2`/`n3` after a single query
(`test_parallel_replicas_plan_based_replica_count`) could fail on a correct
parallel-replicas execution.

- `test_parallel_replicas_alien_shard_scope`: prove engagement by the
  query-scoped `Creating parallel replicas coordinator with replicas_count=`
  line of shard 1's secondary query, and require a count of at least 2.
- `test_parallel_replicas_plan_based_replica_count`: use small granules so the
  read splits into many segments, and repeat the query (bounded) until `n2` or
  `n3` has sized its segments, keeping the assertions that the workers consume
  the propagated count.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…he plan-based replica count test

Retrying the query did not guarantee that `n2` or `n3` would ever size their
segments, because the coordinator could give all ranges to `n1` and cancel the
other workers on every attempt. The test now enables the one-shot
`parallel_replicas_wait_for_unused_replicas` failpoint on the initiator. Unused
workers are then not cancelled, so each of them builds its read pool and logs
`number_of_replicas`. The retry loop is removed, and the test now requires both
checked workers to log the propagated count.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into the branch (5ef0954). The merge was clean; master touched several files this PR also edits (executeQuery.cpp, Context.{h,cpp}, ReadFromMergeTree.{h,cpp}, ReadFromRemote.cpp, SelectQueryOptions.h, InterpreterSelectQueryAnalyzer.cpp), but clickhouse builds on the merged tree and the PR diff against master is unchanged. CI was green on the previous head, and there are no unresolved review threads.

# Conflicts:
#	src/Interpreters/ClusterProxy/executeQuery.cpp
@nickitat

Copy link
Copy Markdown
Member

🕵 Merged master into this branch and resolved the conflicts caused by #129617 (the switch to the -WithMemoryTracking containers). This update was made automatically.

alexey-milovidov and others added 2 commits November 15, 2026 01:56
…icas skip-inactive tests

`master` now answers `sum` without `GROUP BY` and filters from per-part
statistics (`use_statistics_for_sum_avg_aggregation`, enabled by default), so
`SELECT sum(key)` in these tests read no data and the parallel replicas read
pool never logged `number_of_replicas=` / `min_marks_per_task*threads=`.
Disable the optimization for these queries, the same way `master` did in
`test_parallel_replicas_protocol`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109377&sha=e11eb8bca0f283dc8ba6897ea9a095b5fa66504e&name_0=PR
PR: ClickHouse#109377

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (clean, no conflicts; the PR's translation units compile on the merged tree, and the PR diff against master is unchanged apart from the fix below) and pushed d722a77.

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 15, 2026
The new `Stateless tests (arm_asan_ubsan, azure, targeted)` job (ClickHouse#131576)
runs the test 50 times on one server with fixed settings. `query_23`
(`... WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10`) is a TopK
read: with the default `use_query_condition_cache = 1` every run stores
the granules the TopK filter dropped, and the next run starts from them.
The selection shrinks run over run (CI: 383, 26, 16, 9 marks),
`ReadCompressedBytes` falls more slowly than the estimate, and the ratio
crosses the test's 2x bound once it converges (2.005x / 2.022x on ClickHouse#109377
and ClickHouse#129198). Randomized jobs never converge because the cache and TopK
settings are re-drawn per run.

Pin `use_query_condition_cache=0` test-wide, as the sibling estimation
tests 03801 and 04102 already do; the cache with autopr stays covered by
03783_autopr_dataflow_cache_reuse_qcc.

Locally, unpatched at CI's thread count: red from run 4-5 (8-9 marks,
2.02-2.04x); patched: 10/10 with a constant 1084 marks, and 50/50 with
random settings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 18, 2026 15:41
Resolve the conflict in `SelectStreamFactory` with https://github.com/ClickHouse/ClickHouse/pull/ (`b50f2e6cdf7f`, "Plan a distributed query once for all remote shards"), which removed the AST overload of `createForShard` and caches the query AST per factory: take master's version, add the `shard_scope_identity` parameter back, and strip `cluster_for_parallel_replicas` from the cached AST when it is built.
ClickHouse#130655 and `fa76a947810d` ("Do not use inactive
replicas as `make_distributed_plan` workers") on `master` renamed the static
`getActiveReplicasForParallelReplicas(context, cluster)` to the exported
`getReplicasLiveness(cluster_name, cluster)`. The merge kept the new name, but the call in
`getActiveReplicasCountForParallelReplicas` added by this PR still used the old one. Pass the
`cluster_for_parallel_replicas` setting as the cluster name, which is what the old function read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and pushed 67718c1.

The only red check was AST fuzzer (amd_debug, targeted, old_compatibility): OOM in dmesg. It is unrelated to this PR. The last fuzzed query was SELECT DISTINCT toFixedString({fuzz_param_0:String}, 1048575) FROM remote('127.0.0.{2,3}:9000', ...), which does not use parallel replicas. The same failure appears on many other PRs in the last 30 days (131793, 130149, 131697, 131551, 131216, 130055, ...). The likely fix is #130682 (memory limit for FixedString single-value aggregate states).
@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109377&sha=d722a77dbdd0bfc02c722fa989562e49169caf5f&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The fix is #131870 (DISTINCT no longer copies a constant column to every row of a block), merged 2026-11-16 03:35 UTC. The red run is from 2026-11-15 05:11 UTC, so its tree did not have it. 67718c1 does.

  • In server.log, the server died in the innermost hop of the query: each remote('127.0.0.{2,3}') shard reads rem__fuzz_0, which is a Remote table over rem_outer on 127.0.0.1. Each of the two 127.0.0.1 queries reached about 192 GiB tracked within 6 ms of starting to read rem_leaf, in steps of 64 GiB. 64 GiB is one block of max_block_size = 65409 rows of FixedString(1048575).
  • I replayed the exact query with the run's settings (plus max_memory_usage = 4e9) on the CI release builds. On this PR's d722a77 build it fails with Code: 241 ... attempt to allocate chunk of 64.00 GiB, from ColumnFixedString::replicate <- ColumnConst::convertToFullColumn <- convertToFullIfConst <- DistinctTransform::deduplicate. When every DISTINCT key is constant, deduplicate materialized the chunk before cutting it to one row. On the Do not copy a constant column to every row of a block in DISTINCT #131870 build the same query reads all 784930 rows with a 10.4 MiB peak, also under max_memory_usage = 2e8.

#130682 does not cover this run: the query has no aggregate function.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and pushed 5d6927b. The merge was clean; master changed Context.{h,cpp} and ReadFromMergeTree.{h,cpp}, which this PR also edits, and both translation units compile on the merged tree. The PR diff against master covers the same files as before.

Public CI on 67718c1 had no failed tests; the only red was CH Inc sync ("Failed. Needs manual intervention"). The bot could not merge the PR head into the sync branch, because of the earlier manual adaptation of gtest_client_info_read.cpp to the private makeFullClientInfoWire signature. I put the new head onto private master by hand: the 4 files that differ in private merged cleanly, with exactly the PR changes, and the gtest file keeps its previous adaptation (no change on either side since then). No private-only code calls the changed SelectStreamFactory::createForShard. I pushed it as 931cb255c956 to the sync branch, and the sync PR is MERGEABLE now.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Public CI on 5d6927b is green apart from CH Inc sync ("tests failed (1 new, 7 known)"). The sync PR now merges and builds. The new failure is 05493_time_series_selector_id_ranges_index_hint in Stateless tests (amd_jemalloc_uaf, meta in keeper, s3 storage, parallel). Its text_log / query_log join returned no rows. It is a TimeSeries test that does not touch parallel replicas, and it fails occasionally on public CI too (PR 106734 on 2026-11-13 and 2026-11-16, PR 129064 on 2026-11-03). The other failures are the private-only test_distributed_cache integration tests. I reran the failed jobs of the private sync run. No code change was needed.

@nickitat

Copy link
Copy Markdown
Member

Parallel replicas now size the automatic parallel_replicas_mark_segment_size by the number of active replicas, consistent with the reading coordinator, so registered-but-inactive replicas no longer skew segment sizing.

@groeneai how this can possible take 1.5K lines of slop?

@groeneai

Copy link
Copy Markdown
Collaborator Author

You're right, the size is not justified for a heuristic.

  • My first commit (41b3168) was +31/-3: take the replica count for chooseSegmentSize from the active replicas instead of getAllNodeCount().
  • AI review then asked for exact parity with the coordinator (the forced local replica, the max_parallel_replicas cap, total_query_nodes on remote disks). I accepted that premise, and my 4 commits grew the PR to +347/-53, most of it an S3 test.
  • From 2026-08-17 @ alexey-milovidov's agent continued the branch on the same premise (28 code commits): propagating the coordinator's count to followers in ClientInfo, scoping it by cluster and shard, then fixing what the propagation itself introduced (a client-supplied count on an initial query, a division by zero from an oversized count). That is the other ~1000 lines: ~260 in src/, 137 in gtests, ~610 in four new integration tests.

The parity premise was not needed. DefaultCoordinator keeps the mark_segment_size of the announcement that initializes its state, and the count only selects 128, 1024 or 16384 granules, so a follower computing a different value does not affect correctness.

Two options:

  1. I close this PR and open a minimal one: the active count, capped by max_parallel_replicas, for total_nodes_count, with the existing test_parallel_replicas_skip_inactive_replicas extended. About the size of the first commit.
  2. Close it without a replacement, if you think the current heuristic is good enough.

Which one do you prefer?

@nickitat

Copy link
Copy Markdown
Member

You're right, the size is not justified for a heuristic.

* My first commit ([41b3168](https://github.com/ClickHouse/ClickHouse/commit/41b31682cb538b24cfa68cf110c9ff1e94d76420)) was +31/-3: take the replica count for `chooseSegmentSize` from the active replicas instead of `getAllNodeCount()`.

* AI review then asked for exact parity with the coordinator (the forced local replica, the `max_parallel_replicas` cap, `total_query_nodes` on remote disks). I accepted that premise, and my 4 commits grew the PR to +347/-53, most of it an S3 test.

* From 2026-08-17 @ alexey-milovidov's agent continued the branch on the same premise (28 code commits): propagating the coordinator's count to followers in `ClientInfo`, scoping it by cluster and shard, then fixing what the propagation itself introduced (a client-supplied count on an initial query, a division by zero from an oversized count). That is the other ~1000 lines: ~260 in `src/`, 137 in gtests, ~610 in four new integration tests.

The parity premise was not needed. DefaultCoordinator keeps the mark_segment_size of the announcement that initializes its state, and the count only selects 128, 1024 or 16384 granules, so a follower computing a different value does not affect correctness.

Two options:

1. I close this PR and open a minimal one: the active count, capped by `max_parallel_replicas`, for `total_nodes_count`, with the existing `test_parallel_replicas_skip_inactive_replicas` extended. About the size of the first commit.

2. Close it without a replacement, if you think the current heuristic is good enough.

Which one do you prefer?

do (1)

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I'll open the minimal PR from current master and close this one with a link to it once it is open.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The minimal PR is #133260 (+81/-8: 50 lines in src/, the rest extends the existing test); closing this one in favour of it.

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-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants