Skip to content

Test build - #122570

Closed
nickitat wants to merge 142 commits into
masterfrom
tsar-pr
Closed

Test build#122570
nickitat wants to merge 142 commits into
masterfrom
tsar-pr

Conversation

@nickitat

@nickitat nickitat commented Sep 27, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

@clickhouse-gh

clickhouse-gh Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3653516]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, targeted) FAIL
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
Stateless tests (amd_asan_ubsan, flaky check) FAIL
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
Stateless tests (amd_tsan, flaky check) FAIL
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
Stateless tests (amd_msan, flaky check) FAIL
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
Stateless tests (amd_debug, flaky check) FAIL
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
Stateless tests (amd_binary, flaky check) FAIL
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) FAIL
04654_parallel_replicas_merging_aggregated_no_top_k FAIL cidb

AI Review

Summary

This PR replaces estimated read sizes with compressed-block accounting, changes automatic parallel-replica plan matching, and extends GROUP BY top-K pushdown. Changes are required: the new ordered plan-based path matches bounded local statistics to unbounded remote aggregation, and six earlier findings still hold in the current code. Addressed findings have been dropped; existing findings are linked below rather than posted again.

Missing context / blind spots
  • ⚠️ The title, “Test build,” and description do not explain the intended behavior or performance target. A short motivation and representative before/after measurements would establish the acceptance criteria.
  • ⚠️ Findings are based on tracing the current source and PR diff. No local runtime reproduction was run; the focused cases below would verify the affected execution paths.
Findings

❌ Blockers

  1. Bounded local top-K statistics price unbounded remote output. optimizeGroupByTopK.cpp:562. With parallel_replicas_plan_based = 1 and parallel_replicas_local_plan = 1, the new ordered path adds the heap only to the local partial aggregation. Remote fragments were already serialized without it. For high-cardinality SELECT k, count() FROM t GROUP BY k ORDER BY k LIMIT 10, an active full-key heap produces small single-node statistics while remote replicas still send all their groups. Matching these plans can underprice network traffic and initiator merge work by orders of magnitude. Apply the same heap and ordering before remote serialization, or decline the match/use an estimate of the actual remote output. New inline finding.

  2. Automatic cluster-engine replacement bypasses the IN-subquery restriction. TableFunctionObjectStorage.cpp:254, existing thread. canReplaceClusterEngineWithClusterVariant explicitly ignores automatic mode, while the disabling checks in Planner and GlobalSubqueriesMatcher remain gated by predicates that reject automatic mode on the initiator. Consequently, automatic_parallel_replicas_mode = 1 and parallel_replicas_allow_in_with_subquery = 0 still allow object-storage cluster workers to evaluate the subquery independently. Replica-local or nondeterministic subqueries can produce different filtering results. Enforce the restriction before selecting cluster storage. The equivalent url finding remains [dismissed by author -- https://github.com/Test build #122570#discussion_r4148401271]; its current replacement predicate still takes the same path around both guards.

⚠️ Majors

  1. A top-K flag does not prove that output is replicated. considerEnablingParallelReplicas.cpp:1312, existing thread. GROUP BY a, b ORDER BY a LIMIT 10 can retain arbitrarily many tied groups: trimHeapAndPruneHashTable does not prune the hash table in prefix mode. Full-key heaps can also freeze without clearing params.top_k. Always selecting divisor 1 overprices partitioned output by up to max_parallel_replicas and rejects useful parallel execution. Distinguish genuinely bounded output from prefix/frozen heaps when estimating the network term.

  2. Partial cache hits charge skipped granule tails. MergeTreeReaderWide.cpp:726, existing thread. Every served segment is charged as a complete granule even when PREWHERE trims its rejected tail. With 8192-row granules, large strings, and a predicate selecting only the first row, the warm-cache statistics charge the entire string granule while the cold read needs its initial compressed block. This can pass the minimum-input threshold or favor fan-out solely because the cache is warm. Account for the consumed row span, or decline statistics when that span cannot be mapped to blocks.

  3. Compact-cache subcolumn accounting includes unread siblings. MergeTreeReaderCompactSingleBuffer.cpp:93, existing thread. For j JSON(k UInt64, payload String) with substream marks, j.k is read separately from disk. Because JSON reports dynamic subcolumns, a cache hit instead charges every substream of j, including a large unread j.payload. Resolve the requested path's streams or mark the measurement unsupported, as the wide reader does; otherwise cache warmth can arbitrarily inflate the replica cost-model input.

  4. Cached dictionary ranges omit a required second dictionary. MergeTreeReaderStream.cpp:668, existing thread. addRangeOfMark omits the dictionary-specific advancement implemented by MergeTreeReaderStreamSingleColumn::getRightOffset. In the latter's documented multi-dictionary layout, cached granule 4 is charged through offset 84995, although it can also need the dictionary block ending at 126531. Preserve that boundary rule or decline statistics for unresolved dictionary layouts, so narrow cached range reads are not underpriced.

  5. Unavailable duplicated-read measurements become zero. RuntimeDataflowStatistics.cpp:372, existing thread. A cached wide Dynamic column can make takeCompressedBytesRead return nullopt, but markUnsupportedCase ignores duplicated reads. The cache entry remains usable with missing duplicated bytes: 64 MiB coordinated input plus 192 MiB unavailable duplicated input can pass the default duplicated-read gate with ratio 0 instead of 0.75. Track unavailable duplicated measurements and decline the candidate when the configured limit cannot be evaluated.

Tests
  • ⚠️ Extend 05480_autopr_plan_based_group_by_order_by_top_k beyond mode 2: collect statistics, execute mode 1, and compare actual remote aggregation output with the estimate on high-cardinality keys. Current assertions only establish matching.
  • ⚠️ Cover cold-versus-warm accounting for partial PREWHERE granules, compact typed JSON paths with large siblings, and multi-dictionary range reads. Add a cached Dynamic build-side read to 05293_autopr_duplicated_read_ratio_gate and prefix/frozen heaps to the top-K divisor test.
  • ⚠️ Verify that automatic cluster-engine replacement respects parallel_replicas_allow_in_with_subquery = 0, including a subquery whose data differs between workers.
Final Verdict

❌ Block. Make ordered remote aggregation comparable to its statistics and enforce the cluster-engine subquery restriction. Correct the remaining accounting/divisor cases and add focused regression coverage before merging.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 27, 2026
@nickitat
nickitat marked this pull request as ready for review September 27, 2026 20:54
@nickitat
nickitat marked this pull request as draft September 27, 2026 21:04
@clickhouse-gh clickhouse-gh Bot added the comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). label Sep 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3653516f5 with master 64576f956 (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

162 object files changed (+84.70 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReadTask.cpp.o 270.89 KiB 239.87 KiB -31.02 KiB (-11.45%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeGroupByTopK.cpp.o 186.04 KiB 211.36 KiB +25.32 KiB (+13.61%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReaderStream.cpp.o 153.00 KiB 177.34 KiB +24.34 KiB (+15.91%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReaderWide.cpp.o 403.30 KiB 426.56 KiB +23.27 KiB (+5.77%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp.o 477.55 KiB 499.29 KiB +21.74 KiB (+4.55%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReaderCompactSingleBuffer.cpp.o 119.32 KiB 138.80 KiB +19.48 KiB (+16.33%)

719 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

724 translation units recompiled, 6391 s compile time in total, 723 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.8 s

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

Only one query was flagged: ClickBench Q20 improved by -41.4% (220 to 129 ms), and CPU time almost halved. The change is large and consistent enough that the improvement verdict holds. Even so, the PR mostly changes automatic parallel replicas, plan cache keys and the default for parallel-replicas filter push-down, and none of that has an obvious link to a single-node scan, so the cause should be confirmed with a rerun before anyone relies on the win. Q33's +6.7% falls inside master's current range on a query that is noisy on master, which is consistent with suppressing it, and it was left suppressed.

clickbench

🟢 1 improved · ⚠️ 1 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 220 129 -41.4% <0.0001 cpu: -41.4% (220 to 129 ms), and CPU time fell by nearly half, so less work was done. The diff is mostly parallel-replicas and cache-key code, and it does not show how a single-node scan gets faster.
⚠️ 33 not_sure 1047 1117 +6.7% <0.0001 +6.7% sits inside master's current range of 962-1202 ms, and this query is noisy on master. No changed code path can be tied to it, so the suppression stands.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: fc682064-c7b8-490e-b351-4456906e0bd4
  • MIRAI run: 7217800f-cfaa-4fe4-b5ed-f16310826514
  • PR check IDs:
    • clickbench_128533_1791952049
    • clickbench_128553_1791952049
    • clickbench_128560_1791952049
    • tpch_adapted_1_official_128586_1791952049
    • tpch_adapted_1_official_128618_1791952049
    • tpch_adapted_1_official_128640_1791952049

@clickhouse-gh clickhouse-gh Bot added comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). and removed comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). labels Sep 29, 2026
nickitat added a commit that referenced this pull request Sep 29, 2026
Master PR #119865 made `hasNonRewritableFunction` refuse a
non-deterministic select list as well, so the query shipped to the replicas no longer carries the
condition for `v_nondet_pr_rewrite_shapes` (`rand()`), and the read is `Default`, not `InOrder`. The
condition still reaches the local read as a PREWHERE.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122570&sha=9e0efd96ece0309ec7cee2cde51889e0a90af8ae&name_0=PR
PR: #122570

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Core/Settings.cpp Resolved
Comment thread src/Storages/StorageDistributed.cpp Resolved
@nickitat
nickitat marked this pull request as ready for review September 29, 2026 21:22
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
Comment thread src/Core/SortDescription.cpp Resolved
@nickitat
nickitat marked this pull request as draft September 29, 2026 21:35
Comment thread src/TableFunctions/TableFunctionURL.cpp Resolved
Comment thread src/Interpreters/Context.cpp Resolved
@nickitat
nickitat marked this pull request as ready for review September 30, 2026 19:55
@nickitat
nickitat marked this pull request as draft September 30, 2026 21:10
nickitat added a commit that referenced this pull request Oct 1, 2026
nickitat added a commit that referenced this pull request Oct 1, 2026
…arallel`, `no-fasttest`

Both arm `parallel_replicas_wait_for_unused_replicas`, which is server-global, and master's Style check
now requires every test that enables a fail point to run alone (`failpoint_tests_are_isolated`).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122570&sha=b7de3528ae8ad2adcedb71338789eddf7b9fe6aa&name_0=PR&name_1=Style%20check
PR: #122570

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nickitat
nickitat marked this pull request as ready for review October 1, 2026 17:16
nickitat added a commit that referenced this pull request Oct 1, 2026
…ead_ratio_gate`

In Fast test the coordinated read is about 2 MB after compression, which is under
`automatic_parallel_replicas_min_bytes_per_replica` (1 MiB per replica, 3 replicas), so the candidate was
declined by that gate even with the ratio disabled, and the at-default row passed for the wrong reason:
"Not enabling parallel replicas reading because the read of 2046191 bytes gives 682063 per replica, less
than automatic_parallel_replicas_min_bytes_per_replica 1048576". Set it to 0 so the ratio is the only gate.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122570&sha=909b19e7e6b1e751df7e0c9ba6532ed47b5a6fc2&name_0=PR
PR: #122570

Co-Authored-By: Claude Opus 5.5 <[email protected]>
&& query_settings[Setting::parallel_replicas_for_cluster_engines]
&& context->canUseTaskBasedParallelReplicas()
&& !context->isDistributed()
const auto can_use_parallel_replicas = context->canReplaceClusterEngineWithClusterVariant()

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.

❌ Blocker: this now uses the same canReplaceClusterEngineWithClusterVariant() gate as url, so object-storage table functions start taking the *Cluster path even when automatic_parallel_replicas_mode != 0. But the analyzer-side IN-subquery checks still live behind canUseTaskBasedParallelReplicas() / canUseParallelReplicasOnInitiator() (src/Planner/Planner.cpp:2747, src/Interpreters/GlobalSubqueriesVisitor.cpp:167), which stay false there.

So enable_parallel_replicas = 1, automatic_parallel_replicas_mode = 1, parallel_replicas_allow_in_with_subquery = 0 can still ship s3Cluster / azureBlobStorageCluster / icebergCluster (and the same DatabaseDataLake.cpp:909 branch) to every replica and let each replica run the subquery independently instead of disabling parallel replicas. Please move that guard to the cluster-engine replacement predicate, or reject this shape before choosing the *Cluster storage.

nickitat added a commit that referenced this pull request Oct 9, 2026
…e full path does

`autopr-decide-before-probe` declines from cached statistics before a plan with parallel replicas exists, and it
recorded only `ParallelReplicasPlanNotBuilt`. The queries it declines then vanished from the funnel of
`autopr-observability`: no `AutoParallelReplicasCostModelEvaluated`, no `AutoParallelReplicasBytesPerReplica`,
no `AutoParallelReplicasRejectedByCostModel` or `AutoParallelReplicasRejectedByThreshold`. Record the same
events as the full path records for the same outcome.

`05259_autopr_overhead_split` and `05332_autopr_min_bytes_per_replica_events` expected the decision run to build
the plan, which it no longer does; `05257_autopr_rejected_by_cost_model` passes as it is.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122570&sha=5782bf7cdfc67854d095f3f261582148f7545db9&name_0=PR&name_1=Fast+test
PR: #122570

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…GROUP BY` top-K heap

`considerEnablingParallelReplicas` ran before `tryOptimizeGroupByTopK`, so it measured and switched a plan that was
not settled yet. Its forced index analysis was also stored on the read before `setTopKColumn` stamped it, so a
`GROUP BY ... LIMIT` read never consulted its top-K query condition cache entries: ClickBench q18 read all 8.9M
rows with automatic parallel replicas against ~1M without. It now runs last.

Running last alone loses the match for `GROUP BY ... LIMIT`: the single-node plan then carries the heap and the
`__topKFilter` PREWHERE, and the plan with parallel replicas carried neither. Parallel replicas now get the heap too:
- `GroupByLimitOrderByKeysPass` orders `GROUP BY ... LIMIT` without `ORDER BY` by the grouping keys when the query
  may run with parallel replicas. Any `n` groups answer it, so the smallest `n` do too, and with the `ORDER BY` in
  the query text the replicas put the heap on their partial aggregation (`applyTopKPushdownToPartialAggregation`)
  and the initiator keeps the smallest groups after merging. The single-node plan gets the same `ORDER BY`.
- The dynamic filter is allowed on a read from parallel replicas: the heap it feeds ranks only the rows of this
  replica, so its boundary is never tighter than the one over all rows.

q18 shape on `test.hits`, 3 local replicas, median of 5: forced parallel replicas 69 ms / 4.3M rows -> 8 ms / 0.2M
rows; automatic 10 ms / 8.9M rows -> 8 ms / 0.9M rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017LMx8PkGBrowNrHvRMw4xi
nickitat and others added 2 commits October 13, 2026 19:47
… whole

`findQueryForParallelReplicas` stopped at any `Sorting` step, so in
`SELECT sum(...) FROM (SELECT ... ORDER BY k)` only the inner subquery
went to the replicas: they sorted their rows (the local one reading in
order), and the initiator merged the sorted streams just to aggregate
them. `query_plan_remove_redundant_sorting` then dropped the merge on the
initiator but not the sorting on the replicas.

Remove the redundant sortings from the plan this decision is made on, the
same way the plan the query runs with has them removed. The whole query
then goes to the replicas and they aggregate, exactly as when the
subquery has no `ORDER BY`.

This also lets automatic parallel replicas match such queries: the
single-node plan had no sorting, the parallel replicas plan did, so the
hash of the replicas' part was never found in the single-node plan
(`Cannot find step with matching hash`).

`02967_parallel_replicas_joins_and_analyzer` covers a subquery with
`ORDER BY` stopping the subquery from going to the replicas; the sortings
there are redundant, so it now keeps them with
`query_plan_remove_redundant_sorting = 0`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`GroupByLimitOrderByKeysPass` added the `ORDER BY` for every `LIMIT`, while the planner refuses the heap above
`query_plan_max_limit_for_top_k_optimization` and `TopKParams::max_k`, for negative or fractional values, and under
`exact_rows_before_limit`. There the order only cost a sort that the query did not need. The pass now applies the same
admission checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017LMx8PkGBrowNrHvRMw4xi
nickitat and others added 6 commits November 3, 2026 21:03
# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeTree.cpp
# Conflicts:
#	src/Storages/MergeTree/MergeTreeReaderWide.h
… column bound in a stripe

The previous commits found the end of a range among all the marks of the part sorted by their
offsets, which cost an array of marks times columns and a sort for every stream with a cache hit.

The granules of a part written upstream are stripes of one granule each, and the row-order lookup
of the next position is exact there, including the blocks shared by columns and empty streams. A
stripe of several granules, as written in ClickHouse Cloud, is detected from the marks of the
neighbouring granules, and the range then ends at `getRightOffsetOneColumn`, the bound the readers
use, an upper bound. Each lookup is O(1) apart from the stripe.

The column bound alone is not enough: the columns of a granule share compressed blocks even with
`compress_per_column_in_compact_parts`, and it counts the next granule for each one, 1.9x for a
whole cached column in 05443.

Related: #127586

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SZKMswoC3pzhtU6mb2KeM1
…to tsar-pr

# Conflicts:
#	src/Storages/MergeTree/MergeTreeReaderStream.cpp
…g-filters

# Conflicts:
#	src/Storages/MergeTree/IMergeTreeReader.h
…to tsar-pr

# Conflicts:
#	src/Storages/MergeTree/IMergeTreeReader.h
const auto & keys = aggregating_step->getParams().keys;
auto top_k_params = topKOfSort(sorting_step.getSortDescription(), keys, expression_step, limit, settings);
if (top_k_params)
applyTopK(source, *aggregating_step, std::move(*top_k_params), settings, nodes);

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.

❌ [P1] Match statistics against the aggregation that remote replicas execute

With parallel_replicas_plan_based = 1 and parallel_replicas_local_plan = 1, this adds the heap only to the local partial aggregation, making it match the single-node aggregation. The remote fragment was already serialized by createRemotePlanFragmentForParallelReplicas and still has no heap; this ordered path also never calls enableGroupByTopK.

For a high-cardinality SELECT k, count() FROM t GROUP BY k ORDER BY k LIMIT 10 whose full-key heap remains active, the single-node statistics describe the pruned hash table, while remote replicas send all distinct groups in their assigned ranges. decideAtBoundary then prices that unbounded remote output using the small top-K sample. It can enable parallel execution with orders of magnitude more network traffic and merge work than estimated. Adding the heap to the local branch makes the hashes match without making the remote dataflow comparable.

Please apply the same ordering and heap to the remote fragment before serialization, or decline this match until its unbounded output can be priced. Extend 05480_autopr_plan_based_group_by_order_by_top_k to execute mode 1 after collecting statistics and check remote output; its current mode 2 assertions only prove that matching succeeds.

nickitat and others added 22 commits November 4, 2026 09:50
…fragment

The previous commit gave the heap only to the local partial aggregation. The fragment shipped to the remote replicas
was already serialized without it, so they still built and sent all their groups, while automatic parallel replicas
priced their output by the bounded single-node aggregation.

Now `applyParallelReplicas` gives the partial aggregation the heap when it splits the aggregation of
`GROUP BY ... ORDER BY ... LIMIT n`, before the fragment is cloned and serialized, so the local and the remote replicas
both run it (`AggregatingStep::serialize` carries `top_k`). The shape matching of `tryOptimizeGroupByTopK` is moved to
`matchLimitedAggregation` to be shared, and `tryOptimizeOrderedGroupByTopKOverPlanFragments` is removed.

`05480` now also checks that the remote replicas skip rows in the heap and return the same groups, and that mode 1
prices the query. `04654` uses `EXPLAIN description = 0`, because the description of the shipped fragment depends on
`enable_parallel_blocks_marshalling`.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125888&sha=latest&name_0=PR
Review: #125888 (comment)
PR: #125888

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ut-bytes

# Conflicts:
#	src/Storages/MergeTree/IMergeTreeReader.h
#	src/Storages/MergeTree/MergeTreeReaderStream.cpp
#	src/Storages/MergeTree/MergeTreeReaderWide.h
…it begins

`CountedCompressedBlocks::take` subtracts the begin of a range from its end. A range that ended before
it began made the count wrap around to 2^64 in `05452` on Cloud, where compact parts are written in
stripes of several granules. The ranges of cached granules now take the stripe bound (merged from
`fix-stats-for-string-filters`), so such a range is a bug.

Related: #127835
Related: #127586

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SZKMswoC3pzhtU6mb2KeM1
…anning the marks

When the next position of a granule served from the columns cache starts inside a compressed block,
`addRangeOfPosition` scanned the following marks for the next later offset, once for each cached granule
and position. When many granules share one block, that is quadratic in the number of marks. Outside of
the stripes of several granules the offsets of the positions in row order don't decrease, and the next
such stripe starts a block after this one, so a binary search finds the same mark.

Related: #127586
Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
…lumn too

The columns of a reloaded part lose the custom serialization of the `Quantized` codec, which
`getColumnAndSerializationInPart` then takes from the requested column: after a pending rename and a
reload, the column to read is a plain `Array` read with `SerializationQuantizedVector`. The guard looked
only at the column to read, missed it, and charged the codes and the codebook, which reading the vectors
skips: 8,401,962 bytes for a cached read that is otherwise not measured.

Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
`SYSTEM STOP MERGES` holds only the instance it is run on: after `DETACH` and `ATTACH` the new instance
runs the rename mutation, which can finish before the cached reads, and then the part has the new name
and the old guard passes the test too. The case moves to its own test on a `ReplicatedMergeTree` that
cannot become a leader, so no replica assigns the mutation. The rename is waited for with
`SYSTEM SYNC REPLICA`, since `alter_sync` would wait for the mutation too. Without the fix the test fails
5 times out of 5; 05452 needs no Keeper and is not skipped by the fast test.

Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
… that use it

`takeCompressedBytesRead` counted the union of the ranges of one read step. In a stripe of several granules (the layout
of compact parts on Cloud), a compressed block of a column can hold several granules. Reading keeps the block loaded for
the next step, so it is loaded once. A granule served from the columns cache instead takes the range of the whole block
again at every step: with one granule per step and a block of 16 granules, that is 16 times the block.

Now the ranges of a step that the previous step counted are not counted again. Only the previous step is kept, which
bounds the memory, and works when reading in reverse order too. Upstream compact parts flush the blocks of every column
at each granule, so the blocks of consecutive steps don't overlap, and nothing changes there.

Related: #127586
Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SZKMswoC3pzhtU6mb2KeM1
…to tsar-pr

# Conflicts:
#	src/Storages/MergeTree/MergeTreeReaderWide.cpp
The ranges counted by the previous read step were replaced by those of the current one. A step that reads only from the
block the buffer keeps loaded reports no range, so it emptied them: when a later step served a granule of that block
from the columns cache, the block was counted again. The buffer keeps the block it loaded last until it loads another,
so that block now stays among the counted ranges until the buffer loads another. The blocks read are kept apart from
those served from the cache to know which one was loaded last.

Related: #127586

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SZKMswoC3pzhtU6mb2KeM1
…ut-bytes

Keep this branch's `MergeTreeReaderCompactSingleBuffer`: `CountedCompressedBlocks::take` counts a compressed block once
for the whole read, which covers the blocks shared by consecutive read steps in a multi-granule stripe, so the ranges
counted by the previous step and the last loaded block don't need to be kept.

Related: #127586
Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
…to tsar-pr

`MergeTreeReaderCompactSingleBuffer` keeps the version of `autopr-subcolumn-input-bytes`: its
`CountedCompressedBlocks::take` counts each compressed block of the file once across all read steps and readers,
which covers both new commits (a block counted once across the read steps, and the block loaded last not counted
again), so `ranges_served`, `last_loaded_block` and `ranges_counted_before` are not needed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LammEupM8sLAg3FM3j6Ege
…n place

`CountedCompressedBlocks::take` built the path of the file and hashed it at every read step of every stream, and
replaced a counted range it extended by a new node of the map. A reader now looks the counted ranges of a file up once
by stream and keeps a pointer to them, and `take` extends the counted range in place, so reading on from where the
previous block ended allocates nothing.

On a scan of a wide part of 40 columns with 16 threads, `takeCompressedBytesRead` drops from 2.5% to 0.7% of the
samples of the server.

Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
…ts inside it

A merge writes a granule in several calls, and may start a new dictionary in the middle of it. The next mark then points
to that dictionary, which the granule needs as well, but the range of a granule served from the columns cache ended at
the next mark. Now it goes on to the next different mark after the next one, as `getRightOffset` does when reading.

The read of the new test recorded 1,177,746 input bytes cold and 645,264 served from the cache; now 1,177,713.

Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
A dictionary is written at the end of the call that fills it, so a granule written in one call, as by every insert,
needs no dictionary after the next mark. Going on to the next different mark, as `getRightOffset` bounds a read, priced
a granule served from the columns cache with the dictionary of the next granule too: 669,259 input bytes against
359,505 when read from the part, for one granule of a part whose dictionary fills at every granule.

A merge may write a granule in several calls and start the next dictionary in the middle of it. The marks don't tell
the two cases apart, and only the dictionary of the last granule of a read is missed then, so that case is undercounted
instead. The test covers the insert now.

Related: #127835

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CVmLtoabe9AeMvcwV5SBnf
@nickitat nickitat closed this Nov 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant