Repository navigation
Fix a few cases when parallel replicas might return duplicate rows in the output - #112942
Conversation
…enabled `applyParallelReplicas` created the `MergingAggregatedStep` which merges the partially aggregated data of the replicas with a hardcoded `memory_efficient_aggregation = false`, while the path it replaced, `Planner::addMergingAggregatedStep`, obeys `distributed_aggregation_memory_efficient` and lists `parallel_replicas_from_merge_tree` among the cases where it applies. It is not only about the memory. The ordinary `MergingAggregatedTransform` reads all the buckets before it returns anything, and it returns them in the order produced by `Aggregator::convertToChunks`, where the buckets of a two level result are converted by a thread pool, every thread collects the buckets it took into its own list, and the lists are spliced together at the end. So the buckets come out in an arbitrary order. A shard of a `Distributed` table can read its local table with parallel replicas (`ClusterProxy::executeQuery` keeps them enabled for the shards of a cluster which has more than one replica per shard), and then it sends the merged result to the initiator, which merges it memory efficiently. Buckets arriving out of order there make the initiator merge and output the same bucket twice, and the result contains duplicated keys. The bug does not need the buckets to be produced out of order, so `enable_producing_buckets_out_of_order_in_aggregation` is disabled in the test. The thread pool in `Aggregator::prepareChunksAndFillTwoLevelImpl` is used only for more than 100000 keys, so the test has 200000 of them. Without the fix the test reports about 46000 duplicated keys and fails in every run. Memory efficient merging is not supported for grouping sets, so it stays disabled for them. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
…not applicable
`ReadFromRemote` establishes a connection per replica of a shard (`PoolMode::GET_MANY`)
unless parallel reading from replicas is used or the `enable_parallel_replicas`
setting is 0. But a replica executes the whole query unless it is given a part of
the data to read, and only the offset based modes (`SAMPLING_KEY`,
`CUSTOM_KEY_SAMPLING`, `CUSTOM_KEY_RANGE`) do that, by sending a filter along with
the query. `ParallelReplicasMode::READ_TASKS` does it with the coordinator, and for
that a single connection per shard is needed, which is why it is handled separately.
`Context::canUseTaskBasedParallelReplicas` returns false not only when the setting
is 0, but also because of `automatic_parallel_replicas_mode`,
`parallel_replicas_only_with_analyzer` and `max_parallel_replicas`. In those cases
the query was still sent to every replica of a shard, every one of them read all of
its data, and the result of the shard was multiplied by the number of the replicas.
SELECT count(), sum(y) FROM d SETTINGS enable_parallel_replicas = 1,
max_parallel_replicas = 3, automatic_parallel_replicas_mode = 2
returned 6000, 2997000 instead of 2000, 999000 for a cluster of 2 shards holding
1000 rows each. With `distributed_aggregation_memory_efficient` the duplicated
partially aggregated results also arrive at the initiator as several complete
sequences of two-level buckets on a single input port, which the memory efficient
merging cannot handle, so the keys were duplicated as well.
Now several connections to a shard are used only when they read different parts of
the data, i.e. only for the offset based modes.
`automatic_parallel_replicas_mode` no longer has to be pinned in
04606_parallel_replicas_merging_aggregated_bucket_order.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
|
Workflow [PR], commit [c054981] Summary: ✅
AI ReviewSummaryThis PR fixes two real parallel-replica problems: plan-based aggregation now respects Findings❌ Blockers
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 57/59 (96.61%) · Uncovered code |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 24/24 (100.00%) · Uncovered code |
distributed_aggregation_memory_efficient setting with plan-based parallel replicas
There was a problem hiding this comment.
Pull request overview
Fixes a correctness issue where query results could contain duplicated rows when using parallel replicas over Distributed tables, particularly in cases where memory-efficient aggregation merging is involved or when parallel replicas are effectively not applicable and multiple connections per shard would multiply results.
Changes:
- In
ReadFromRemote, switch shard connection pool mode to use a single connection per shard (PoolMode::GET_ONE) unless offset-based parallel replicas are actually applicable, preventing result multiplication. - In plan-based parallel replicas optimization, make replica-result merging respect
distributed_aggregation_memory_efficient(with guards for grouping sets), aligning behavior with distributed aggregation merging semantics. - Add regression tests covering both result duplication via multiple shard connections and duplicated groups from bucket-order issues in memory-efficient aggregation merging.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/queries/0_stateless/04607_parallel_replicas_result_duplication.sql | New regression test for shard-result multiplication when multiple connections are used while parallel replicas are not applicable. |
| tests/queries/0_stateless/04607_parallel_replicas_result_duplication.reference | Expected output for the new 04607 test. |
| tests/queries/0_stateless/04606_parallel_replicas_merging_aggregated_bucket_order.sh | New regression test for duplicate groups caused by bucket-order issues when merging aggregated data with plan-based parallel replicas. |
| tests/queries/0_stateless/04606_parallel_replicas_merging_aggregated_bucket_order.reference | Expected output for the new 04606 test. |
| src/Processors/QueryPlan/ReadFromRemote.cpp | Adjust pool-mode selection to avoid duplicated shard results when multiple connections would execute the same shard query. |
| src/Processors/QueryPlan/Optimizations/applyParallelReplicas.cpp | Respect distributed_aggregation_memory_efficient when merging replica aggregation results in plan-based parallel replicas. |
`04606` wrote the result of the aggregation into a table, because such a query could not be used as a subquery: it failed with `Chunk should have AggregatedChunkInfo in MergingAggregatedTransform`. That is fixed in master, which is merged here, so the query is a subquery again and the table is gone. Both tests drop their tables in the prologue and in the epilogue now. Every test gets its own database (`tests/clickhouse-test` creates `test_<random>` per test and drops it afterwards), so this is not needed for the isolation, but it is what most of the tests around do. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
`04603_pr_plan_based_view_no_view_flag`, `04604_pr_plan_based_force_index_view` and `04605_pr_plan_based_count_distinct_serialized` are named after the feature they test, and this test belongs to the same group. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
`parallel_replicas_mode` can ask for the custom key filtering while `parallel_replicas_custom_key` is not set. Every replica reads only the part of the data its filter selects, so without the key every replica reads everything and the result of the shard is multiplied by the number of the replicas. The initiator builds the filter itself only for a cluster with a single shard, and it already failed there, because `parseCustomKeyForTable` cannot parse the empty key. Otherwise the filter is built by every replica, and `buildCustomKeyFilterIfNeeded` returned no filter silently for the empty key, so a query to a cluster with several shards returned every row as many times as there are replicas. Check the key in `parseCustomKeyForTable`, so that every caller fails the same way, and with the message about the missing custom key instead of a syntax error. An empty filter means a missing key and nothing else: a key that parses always produces a filter, and `parseCustomKeyForTable` throws rather than returns nothing for a key that does not parse. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT Assert that the custom key is parsed into something `parseCustomKeyForTable` either parses the key or throws, so the check for the missing result was never true and its message about the missing custom key was unreachable. The message is reported by `parseCustomKeyForTable` itself now, keep the expectation as an assert. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
`parallel_replicas_for_non_replicated_merge_tree` is about the task based parallel replicas: the replicas read the parts the coordinator assigns to them, and that needs the same parts on every replica. The old analyzer disabled the parallel replicas for a plain `MergeTree` table whenever the setting is not set, no matter the mode, and that also disabled building the filter by the custom key, which is built by the same interpreter. The initiator has already sent the query to every replica of the shard by then, so every replica read the whole table and the result of the shard was multiplied by the number of the replicas. A query without the custom key did not report the missing key either, because the code that reports it was not reached. Check the mode, the same way the check for FINAL right above it does. The analyzer does not disable the filtering here, so both of them behave the same way now. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
`parseCustomKeyForTable` either parses the key or throws, it never returns nothing, so the branch that reports the missing custom key when it returns nothing was never taken. It reported the key of a replica with an offset only, which left the first replica reading the whole table silently. The missing key is reported by `parseCustomKeyForTable` itself now, for every replica, keep the expectation as an assert. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
JOINs are not supported with the custom key, and the old analyzer dropped the custom key for them, promising in the log message that the query is executed without the parallel replicas. It is not what dropping the key does: the parallel replicas stay enabled, the initiator still sends the query to every replica of the shard, and the replicas are left without anything to split the data by, so every one of them reads the whole table and the result of the shard is multiplied by the number of the replicas. Disable the parallel replicas instead, the way the checks for FINAL and for a plain `MergeTree` next to it do. The analyzer executes such queries without the parallel replicas as well, and both of them return the same result now. Reported by review of #112942. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
| /// sent the query to every replica of the shard, and every replica would read the whole table. | ||
| bool is_plain_merge_tree = storage && storage->isMergeTree() && !storage->supportsReplication(); | ||
| if (is_plain_merge_tree && settings[Setting::allow_experimental_parallel_reading_from_replicas] > 0 | ||
| if (is_plain_merge_tree && context->canUseTaskBasedParallelReplicas() |
There was a problem hiding this comment.
parallel_replicas_for_non_replicated_merge_tree is still the opt-in for using parallel replicas on plain MergeTree at all: the setting text says that directly, and the planner's own eligibility check still rejects non-replicated tables when it is off. Narrowing this old-analyzer guard to canUseTaskBasedParallelReplicas means SAMPLING_KEY / CUSTOM_KEY_* fanout now stays enabled for Distributed-over-plain-MergeTree queries even when the opt-in is off.
That is a correctness problem, not just a policy mismatch: if a shard's configured "replicas" are really independent non-replicated MergeTree servers, the query now merges disjoint slices from different datasets instead of falling back to one replica per shard. If the intent is to redefine the setting to task-based-only, the planner/docs/tests need to be updated consistently in the same PR; otherwise this broad plain-MergeTree guard still needs to cover the offset-based modes too.
There was a problem hiding this comment.
I think this claim is wrong. When we tried to reproduce (queries), it showed the duplication for the old analyzer (on master):
run count() uniqExact(x)
no parallel replicas 2000 1000 ← expected
old analyzer, setting=0 6000 1000 ← what the guard actually gives
old analyzer, setting=1 2000 1000
analyzer, setting=0 2000 1000
old analyzer, range, 0 6000 1000
Ironically, it seems to be fixed on this branch. Added a test.
There was a problem hiding this comment.
A correction: it wasn't fixed here, with genuinely divergent replicas we confirmed the issue still exists. But anyway it is pre-existing, neither introduced nor fixed in this PR and will be tracked in #113490.
The table of the test is a plain `MergeTree`, and the parallel replicas are not used for it unless `parallel_replicas_for_non_replicated_merge_tree` is set. The initiator still sends the query to every replica of the shard, so the missing custom key has to be reported, but the test depended on the replicas keeping the parallel replicas enabled to report it. Ask for them explicitly, so that the test checks the missing key on its own. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
The setting says that the query is executed locally when the analyzer is disabled, and it is set by default, but it does not stop the initiator from sending the query to every replica of the shard. Only the filter by the custom key keeps the result of such a query correct, and the replicas dropped that filter for a plain `MergeTree` table, so the result was multiplied by the number of the replicas with either value of the setting. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01BAZjq1jL3wNACqVQzocPoT
Reflected in the changelog entry. |
|
Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment. TL;DRFix a few cases when parallel replicas might return duplicate rows in the output ClickGap verified: reproduced it with the script below on Reproduction-- Needs a cluster with several replicas per shard, e.g. the stateless-test
-- cluster `test_cluster_two_shard_three_replicas_localhost` (2 shards x 3 replicas).
CREATE TABLE t (x UInt64, y UInt64) ENGINE = MergeTree ORDER BY x;
INSERT INTO t SELECT number, number FROM numbers(1000);
CREATE TABLE d AS t ENGINE = Distributed('test_cluster_two_shard_three_replicas_localhost', currentDatabase(), t);
-- Parallel replicas are enabled but NOT applicable (old analyzer +
-- parallel_replicas_only_with_analyzer), so each replica runs the whole query.
-- Expected: 2000 999000 (1000 rows x 2 shards)
-- Observed on 26.7 / 26.6 / 26.5 / 26.3 / 25.8: 6000 2997000 (x3 replicas)
SELECT count(), sum(y) FROM d
SETTINGS enable_parallel_replicas = 1, max_parallel_replicas = 3,
parallel_replicas_only_with_analyzer = 1, enable_analyzer = 0,
parallel_replicas_for_non_replicated_merge_tree = 1, prefer_localhost_replica = 0;Bisect
Affects
Suggested next stepThe fix has landed on master; Component: cc fix PR author: @nickitat ClickGap · Finding: Triage metadata
|
- Case 06 (filter over an ALIAS column with a grant on the alias only): on 26.6 a trivial `SELECT count()` over a table whose only granted column is an ALIAS column throws a logical error even without any filter, so the user also gets `SELECT(id)`; `secret_token` stays denied, and the case still checks that the grant on the alias is sufficient. - Cases 15, 16, 17, 27 (custom key parallel replicas over a plain `MergeTree`): #112942 is not in 26.6, so the old analyzer disables the parallel replicas together with the custom key filter unless `parallel_replicas_for_non_replicated_merge_tree` is set. Set it. - Cases 32-36 (trivial view over a `Distributed` table inlined into the outer query): the `optimize_trivial_view_pushdown_to_distributed` setting and the code path it exercises do not exist in 26.6, so the cases and the views they read are dropped. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The robot cherry-pick of #112942 into 26.7 (#113810) came out conflicting and was auto-closed after seven idle days without anyone resolving it. Eight hours later the 26.7 backport of #112794 landed the "Bucket N is pushed twice" assert and test 04605 on the branch, so 26.7 now asserts an invariant whose fix it never received. #112942 makes the per-shard replica merge that `applyParallelReplicas` inserts obey `distributed_aggregation_memory_efficient`. Without it that merge always takes the `!memory_efficient_aggregation` branch of `MergingAggregatedStep::transformPipeline`, which resizes the pipeline to one stream and uses the plain `MergingAggregatedTransform`. That transform emits two-level buckets in `Aggregator::convertToChunks` order and never consults `should_produce_results_in_order_of_bucket_number`, so a shard that promised the initiator ascending bucket order breaks its own promise. The initiator's memory-efficient merge then trips `chassert(bucket < 0 || pushed_buckets.insert(bucket).second)` in debug and sanitizer builds, and returns duplicated aggregation keys in release builds. Merging `backport/26.7/112942` into `cherrypick/26.7/112942` conflicts in one file, `applyParallelReplicas.cpp`, in one six-line region: master passes the new `settings` argument to the visitor and calls `insertParallelReplicasSplit(query_plan, nodes)` before it, a function added to master after 26.7 was cut. The resolution keeps the `settings` argument and drops the `insertParallelReplicasSplit` call. The resolved file is byte-identical to master's own copy at the fix commit 7a902ae (blob 74365cc), because 26.7's copy equals master's copy at that commit's parent. The resolution therefore diverges from upstream by zero bytes. The other four source files and all three new tests auto-merge clean. (cherry picked from commit 0793ca6)
…942-resolved Resolve the 26.7 cherry-pick conflicts of #112942
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed several cases when parallel replicas returned duplicated rows:
distributed_aggregation_memory_efficientwas ignored by the plan-based parallel replicas, so the buckets of the memory efficient merging arrived out of order and were merged twice; and a shard was read from all of its replicas although the data was not split between them, when the parallel replicas are not applicable to the query or whenparallel_replicas_modeasks for the custom key filtering withoutparallel_replicas_custom_key.Related: #113490