Skip to content

Do not enforce read row limits in the parallel-replicas row estimate - #121269

Merged
nickitat merged 8 commits into
ClickHouse:masterfrom
groeneai:parallel-replicas-estimate-row-limit-71028-class1
Oct 8, 2026
Merged

nickitat merged 8 commits into
ClickHouse:masterfrom
groeneai:parallel-replicas-estimate-row-limit-71028-class1

Conversation

@groeneai

@groeneai groeneai commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed TOO_MANY_ROWS being raised for a query that stays within its max_rows_to_read budget when parallel_replicas_min_number_of_rows_per_replica is set. The estimate sizing the replica set enforced the limit against whole granules at planning time.

Description

Surfaced by #71028's randomization (class 1 there). With parallel_replicas_min_number_of_rows_per_replica > 0, a query whose max_rows_to_read or max_rows_to_read_leaf budget is smaller than the table is rejected even when it reads no rows:

CREATE TABLE x (i int) ENGINE = MergeTree ORDER BY i SETTINGS index_granularity = 3;
INSERT INTO x SELECT number FROM numbers(10);
SELECT max(i) FROM x SETTINGS max_rows_to_read = 2;  -- Code: 158, max 2.00, current 10.00

Root cause. Sizing the replica set took its estimate from selectRangesToRead(), which analyzes with check_row_limits = true, so whole granules are charged and it throws at plan build. Nothing exempts it that early: has_projections misses the implicit _minmax_count_projection, projection selection runs later, and getRowLimits's read-in-order exemption needs an input_order_info that does not exist yet.

Change. Route that estimate through the non-enforcing, non-memoizing analysis whenever a throwing read row limit is set, as #110283 (5b6b32b788904) did for the join estimator; RelationStatisticsEstimator now shares the predicate. 113ce6b061bde then left this call site on the enforcing path during a conflict resolution. The executed read still enforces: it analyzes again, and neither estimation entry point memoizes. The price is one extra index analysis when both settings are set. Negative controls fail if enforcement is merely disarmed.

This fixes 03560_parallel_replicas_projection and the call site behind 02155_read_in_order_max_rows_to_read, whose CI failure charges 100 rows at plan build for ORDER BY a LIMIT 5 with max_rows_to_read = 12; the new test pins that shape in its read-order case. 01585_use_index_for_global_in is a different mechanism (runtime double-charge of a duplicated IN subquery), handled separately.


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

Version info

  • Merged into: 26.10.1.1856-master (included in 26.10 and later)

groeneai and others added 5 commits September 21, 2026 00:51
With parallel_replicas_min_number_of_rows_per_replica > 0 the analyzer asks
ReadFromMergeTree for a row estimate to size the replica set. That estimate ran
selectRangesToRead(), which analyzes with check_row_limits = true, so
MergeTreeDataSelectExecutor charged the whole-granule row count of the base
table against max_rows_to_read and threw TOO_MANY_ROWS at plan-build time.

The projection escape hatch cannot help there: has_projections does not see the
implicit _minmax_count_projection (it lives in
StorageInMemoryMetadata::minmax_count_projection, not hasProjections()), and
projection selection only runs later, in optimizeTreeSecondPass. So

  SELECT max(i) FROM x SETTINGS max_rows_to_read = 2

was rejected on a 10-row table even though _minmax_count_projection answers it
without reading a single data row.

Route that estimate through the non-enforcing, non-memoizing analysis whenever a
throwing read row limit is set, which is what PR ClickHouse#110283 ("Defer read limits
until read order is known", 5b6b32b) already established for the join
cardinality estimator. Commit 113ce6b kept this call site on the
pre-existing row-limit path during a conflict resolution; that pre-existing
behaviour is the defect.

Enforcement is unchanged for the read that executes: neither estimation entry
point memoizes into analyzed_result_ptr, so the executed ReadFromMergeTree
analyzes again through selectRangesToRead() and still throws when the read
really exceeds the budget. The new test pins both directions, including
sum() (which no implicit projection can serve) and the same query with
optimize_use_implicit_projections = 0.

The two estimate entry points collapse into one: selectRangesToReadForEstimation
now takes allow_query_condition_cache_, so the query-condition-cache axis and the
row-limit axis are independent, and estimateRangesToReadWithoutQueryConditionCache
is gone. RelationStatisticsEstimator reuses the new hasThrowingReadRowLimit()
predicate instead of its own inline copy (no behaviour change there).

Surfaced by the randomization in ClickHouse#71028.

Related: ClickHouse#71028

Co-Authored-By: Claude Opus 5 <[email protected]>
…test

The test set parallel_replicas_only_with_analyzer = 0, advertising that it also
runs with the old analyzer, and then asserted that

  SELECT max(i) FROM x SETTINGS max_rows_to_read_leaf = 2

returns 9. That is false with enable_analyzer = 0: the old-analyzer estimator in
adjustParallelReplicasAfterAnalysis caps query_info_copy.trivial_limit with
max_rows_to_read only, so the leaf limit stays armed and the read still throws.
The fix lives in src/Planner/, so pin enable_analyzer = 1 and drop the opt-out,
matching 03560_parallel_replicas_projection.sql, which pins it on the very query
this test copied.

Every assertion was result-only, and the planner declines parallel replicas
silently (it sets allow_experimental_parallel_reading_from_replicas = 0 itself
when the estimate does not justify a second replica). A regression that stopped
reaching the estimate under test would therefore have left the whole test green
while covering nothing: the positives pass because the query is simply correct
locally, and the negatives pass because a local read enforces the limit anyway.
Add a ParallelReplicasQueryCount witness per shape under test, following
04830_pr_plan_based_clone_marked_read.sql.

Both witnesses were mutation-tested rather than assumed live. Forcing
parallel_replicas_for_non_replicated_merge_tree = 0, and separately forcing the
silent-decline path with parallel_replicas_min_number_of_rows_per_replica = 1000,
each flip exactly those two lines from 1 to 0 and fail the test, while all the
other assertions stay green.

Also flatten the estimate's call-site ternary. Two of its three arms called the
same function, so the guard is just

  hasThrowingReadRowLimit() || !allow_query_condition_cache

which is equivalent over the whole truth table. No behaviour change: the repro,
both row-limit arms, the read-order pair, all four negative controls and the
new test's FAIL-on-base / OK-on-fix pair were re-measured on the rebuilt binary.

Co-Authored-By: Claude Opus 5 <[email protected]>
The ParallelReplicasQueryCount witnesses added earlier prove that parallel
replicas engaged, which is a weaker proposition than the one the test needs:
that the replica-count sizing estimate ran at all. At
parallel_replicas_min_number_of_rows_per_replica = 1 neither branch of the
sizing block fires (x sizes to 10 replicas, t clamps to 5 via trivial_limit),
and parallel replicas are engaged by a later step, so a regression that stopped
reaching the estimate would have left every assertion green.

Pair the projection query with the same query under a threshold the 10-row
table cannot meet, which reaches the block's silent decline, and assert zero
engagement for it. Measured: making the block's threshold guard a no-op flips
that row alone and reddens the test, while every other assertion stays green.
The declined case is also fix-live in its own right (TOO_MANY_ROWS before the
change, 9 after), and it is ordered first so no earlier coordinator can perturb
its counter.

The changelog entry covers max_rows_to_read and max_rows_to_read_leaf, and
hasThrowingReadRowLimit() reads both, but every negative control used
max_rows_to_read only, so nothing pinned that the executed read still enforces
the leaf limit. Add the leaf counterpart of the sum() control; it throws on
both binaries, naming max_rows_to_read_leaf in the message.

Narrow the call-site comment: its reanalysis clause holds only on the branch it
justifies, since the other arm memoizes the analysis the executed read reuses.

Co-Authored-By: Claude Opus 5 <[email protected]>
clickhouse-test re-runs a FAILED test up to MAX_RETRIES = 3 times, and with
--database passed it reuses the same database on every attempt. The Stress test
and the Upgrade check pass a fixed database (ci/jobs/scripts/stress/stress.py
pins odd and replicated-database workers to test_{i}), and system.query_log rows
outlive the execution, so an earlier attempt's rows satisfied every predicate of
the two witnesses: the paired probe returned 4 rows against a 2-row reference and
the read-order probe 2 against 1. Because MESSAGES_TO_RETRY is dominated by the
transients the Stress lane manufactures on purpose, a transient the retry
machinery exists to absorb turned into a permanent red on this test.

Both probes now take the latest QueryFinish row per log_comment with
argMax(..., event_time_microseconds), the idiom of
04490_join_runtime_filters_index_analysis.sql. SYSTEM FLUSH LOGS query_log runs
immediately before each probe, so the current attempt's rows are the newest and
"latest" is exactly "this attempt". initial_query_id = query_id stays: with
parallel replicas engaged the secondary queries inherit log_comment and carry the
counter at 0, so dropping it would let a secondary row win the argMax. The
reference is unchanged, and both witnesses still redden under the mutations they
were added to catch, including the source-level one that makes the sizing block
unreachable and flips the paired row alone.

The comment above the paired case said a regression that stopped reaching the
sizing block would leave both counters unchanged. It is the opposite: the
declined counter goes 0 -> 1 there, which is why the pair is a live witness.

Co-Authored-By: Claude Opus 5 <[email protected]>
Drop the call-site narration in PlannerJoinTree.cpp and state the two new ReadFromMergeTree declarations' properties in one line each.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 8 findings over 4 rounds; 1 full pass plus
fix rounds with a delta recheck each). The final round returned no findings.

# Sev Finding Verdict Evidence / action
1 ❌ The advertised max_rows_to_read_leaf fix misses the old-analyzer estimator, which caps only with max_rows_to_read (InterpreterSelectQuery.cpp:1232) AGREE in part, DISAGREE on the remedy Fixed by pinning enable_analyzer = 1 and dropping parallel_replicas_only_with_analyzer = 0, matching 03560_parallel_replicas_projection; declined the InterpreterSelectQuery.cpp change, since that configuration is documented as unsupported, is not randomized, and master has removed that analysis outright (finding 8)
2 ⚠️ The test does not prove the sizing path ran, and the expected errors are not phase-identified AGREE on liveness, DISAGREE on phase identification Added a mutation-tested ParallelReplicasQueryCount witness per shape; phase identification is implied, because on the fixed binary the plan-time estimate cannot throw
3 ⚠️ At threshold 1 the sizing block changes no setting, so it could become a no-op with the test still green AGREE (re-raise of #2), fixed Added a threshold-paired case that reaches the block's silent decline and asserts zero engagement beside the positive; confirmed live by mutating the block's own guard, which flips that one row and nothing else
4 💡 The leaf-limit success case has no negative counterpart proving execution still enforces max_rows_to_read_leaf AGREE, fixed Added a sum() read under max_rows_to_read_leaf = 2 expecting TOO_MANY_ROWS; MergeTreeDataSelectExecutor.cpp:1357-1368 checks the leaf limit beside the global one
5 💡 The estimate comment implies the executed read always reanalyzes, which is false on the memoizing branch AGREE, fixed Narrowed the claim to a throwing row limit, then dropped that call-site comment entirely at publication, so nothing states it
6 ⚠️ Both system.query_log witnesses break if the test is retried in the same database, turning a transient failure into a permanent one AGREE, fixed Collapsed each log_comment to its latest QueryFinish row with argMax(..., event_time_microseconds), the idiom of 04490_join_runtime_filters_index_analysis.sql; proved in both directions against one fixed database, reference unchanged
7 💡 The comment above the threshold-paired case claims neither counter moves if the sizing block is skipped, the opposite of what makes that case live AGREE, fixed Rewritten to state the transition: skip the block and the paired 0 becomes 1
8 ⚠️ The description asked whether the leaf pair should be capped in the old-analyzer estimator too, a configuration this branch's target no longer has AGREE, fixed Master's #120311 normalizes allow_experimental_analyzer back to 1 (executeQuery.cpp:2300, Context.cpp:4045) and obsoletes parallel_replicas_only_with_analyzer, so that paragraph was deleted rather than reworded; no other byte of the description changed

Also considered and declined, with evidence: pinning merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability = 0.0 as the sibling test does (ReadFromMergeTree.cpp:1788 disables that injection outright on a parallel-replicas read); pinning index_granularity_bytes (the index_granularity row cap binds in every randomizer draw at these row widths); repeating the read-order cases under automatic_parallel_replicas_mode = 2 (the probe plan forces mode 0 on its own context and re-enters the same call site).

Checked and not a defect: this estimate no longer memoizes, so later passes see no memoized analysis. That is the ordinary state, since every query at the default parallel_replicas_min_number_of_rows_per_replica = 0 never runs the estimate, indexes is still populated, and getPartsForPrewhere() (ReadFromMergeTree.cpp:6171) re-filters to the same pruned set.

Open #120011 gives selectRangesToReadForEstimation a different bool parameter; measured at hunk level it does not touch src/Planner/PlannerJoinTree.cpp, so it is not a supersession, and whoever merges second rebases.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per
finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-publish-slot-34:20260921-042300

@clickhouse-gh clickhouse-gh Bot closed this Sep 21, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f2c235f]

Summary: ✅


AI Review

Summary

This PR correctly routes the legacy parallel_replicas_min_number_of_rows_per_replica estimate through a non-enforcing analysis when a throwing read-row limit is set, and the new stateless test covers the projection and read-in-order cases on that path. However, the distributed/Cascades planning path still derives pre-final-shape read statistics through enforcing selectRangesToRead() calls, so the same TOO_MANY_ROWS exception remains reachable there.

Findings
  • ❌ Blockers
    • [src/Processors/QueryPlan/Optimizations/Cascades/Statistics.cpp:309, src/Processors/QueryPlan/Optimizations/Cascades/StatisticsDerivation.cpp:383, src/Processors/QueryPlan/Optimizations/optimizeTree.cpp:461, src/Processors/QueryPlan/Optimizations/makeDistributed.cpp:993, src/Processors/QueryPlan/ReadFromMergeTree.cpp:6576] [dismissed by author -- https://github.com/Do not enforce read row limits in the parallel-replicas row estimate #121269#discussion_r4060637625] make_distributed_plan = 1 still skips optimizeReadInOrder on the coordinator, but the Cascades statistics derivation and distributed bucketing paths keep calling the enforcing selectRangesToRead() / getOrCreateAnalyzedResult() flow before the worker fragment is re-optimized into its final read shape. That means a query such as SELECT a FROM t ORDER BY a LIMIT 5 SETTINGS max_rows_to_read = 12, make_distributed_plan = 1, enable_cascades_optimizer = 1 can still raise TOO_MANY_ROWS during planning, so the “pre-final-shape estimates must not enforce throwing read-row limits” invariant is still broken on the distributed-plan path. The author notes that fixing those sites needs limit enforcement to move with the fragment; I still consider this a blocker because the current patch leaves the same user-visible exception on a supported optimization path.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: either extend the non-enforcing estimate contract to the remaining make_distributed_plan = 1 / enable_cascades_optimizer = 1 pre-final estimate sites and preserve execution-time enforcement there, or narrow the claimed fixed surface so this distributed-plan failure mode is explicitly left out.

LLVM Coverage Report

⚠️ No coverage measurement for commit f2c235f: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_8.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 21, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). label Sep 21, 2026
The read-order case took its `max_rows_to_read` budget from
02155_read_in_order_max_rows_to_read, whose read is single-node. Under
parallel replicas each contributing replica charges whole granules of its
slice and the initiator sums their progress, so the rows charged for
`ORDER BY a LIMIT 5` depend on how many granules reach a reader: measured
8 on local disk and 32 on s3 storage with the same fixture. The two s3
parallel lanes therefore failed deterministically at `current rows: 20.00`
while every local-disk lane passed.

The throw came from the read that executes, not from the plan-build
estimate this PR changes (that would have charged the whole 100 rows), so
the product contract is unaffected. Widen the budget to 60 and pair the
control with it at LIMIT 80, which keeps both propositions: on the unfixed
binary the positive still throws at plan build charging the whole table,
and on the fixed one the control still throws inside
ReadPoolParallelReplicasInOrder.

Verified with the reviewed fix binary against an s3-backed server (own
MinIO, parts on cached_s3): 50/50 randomized and 50/50 not, plus 50/50 in
both modes on local disk, and the charge measured at 32 in 51/51 runs.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fix on 09f104f3: the test's budget, not the estimate

05250_parallel_replicas_min_rows_estimate_row_limit failed on the four lanes whose MergeTree sits on object storage (three s3 storage, one azure) and passed on every local-disk lane. All four report the same thing, and it is not flaky (35/35 and 169/169 on the randomized-settings recheck, 39/39 and 161/161 with randomization off, 3/3 on the two rerun lanes):

SELECT a FROM t ORDER BY a LIMIT 5 SETTINGS max_rows_to_read = 12, log_comment = '05250_read_order_pr';
Code: 158 ... max rows: 12.00, current rows: 20.00: While executing Remote. (TOO_MANY_ROWS)

current rows is 20, not 100, so the plan-build estimate this PR changes did not enforce: the throw is the read that executes, which the PR deliberately leaves enforcing, and both engagement witnesses are green in every failing log. The budget is what was wrong. I took 12 from 02155_read_in_order_max_rows_to_read, whose read is single-node; under parallel replicas each contributing replica charges whole granules of its slice, so the same query charges 8 rows on local disk and 32 on object storage. 20 is just where a 12-row budget gets crossed.

cae048be widens that budget to 60 and pairs the control with it at LIMIT 80, so one budget serves the section: the LIMIT 5 read fits, the LIMIT 80 read cannot. Both propositions still hold, measured on both binaries: without the fix the positive still throws at plan build with current rows: 100.00 at the new budget, and with it the control still throws inside ReadPoolParallelReplicasInOrder. Verified against an s3-backed server here (own MinIO, parts on cached_s3, charge 32 in 51 of 51 runs with randomization live) and against a local-disk one, 50/50 in both randomization modes on each. No source file changed.

/// limits. In that case use an estimation-only analysis; execution will analyze again
/// after its final read mode is known.
analyzed_result = has_throwing_row_limit ? reading->selectRangesToReadForEstimation() : reading->selectRangesToRead();
analyzed_result = reading->hasThrowingReadRowLimit()

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.

This only fixes the legacy RelationStatisticsEstimator path. With make_distributed_plan = 1 and enable_cascades_optimizer = 1, optimizeTree.cpp:427-428 skips optimizeReadInOrder, but the Cascades stats code still does a direct selectRangesToRead() in src/Processors/QueryPlan/Optimizations/Cascades/Statistics.cpp:308-309 and src/Processors/QueryPlan/Optimizations/Cascades/StatisticsDerivation.cpp:382-383. A query like SELECT a FROM t ORDER BY a LIMIT 5 SETTINGS max_rows_to_read = 12, make_distributed_plan = 1, enable_cascades_optimizer = 1 can therefore still raise TOO_MANY_ROWS during statistics derivation, before the worker fragment is re-optimized into the exempt read-in-order shape. This needs the same non-enforcing estimate path (or a shared helper for all pre-final-shape statistics callers), otherwise the fix remains incomplete on the Cascades/distributed-plan path.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Reproduced, and wider than the two sites named

It throws on this branch, so the finding is real. t is 100 rows with index_granularity = 4, and the
mode also needs distributed_plan_workers_num when no worker cluster is configured, otherwise the query
stops at SUPPORT_IS_DISABLED before it reaches the estimate:

SELECT a FROM t ORDER BY a LIMIT 5 SETTINGS max_rows_to_read = 12,
  make_distributed_plan = 1, enable_cascades_optimizer = 1,
  distributed_plan_workers_num = 3, distributed_plan_execute_locally = 1;

Code: 158. Limit for rows (controlled by 'max_rows_to_read' setting) exceeded,
max rows: 12.00, current rows: 100.00. (TOO_MANY_ROWS)

Stack: Cascades/Statistics.cpp:309 -> selectRangesToRead -> MergeTreeDataSelectExecutor.cpp:1367
SizeLimits::check. I reached 309 only; StatisticsDerivation.cpp:383 has the same shape, but this
query does not go through it.

It is a false rejection, not just an early one. With the budget raised until the estimate stops
objecting, the read that executes charges 17 rows (system.query_log.read_rows for the initiator), and
that figure is budget-independent: 17 at max_rows_to_read 1000, at 100, and unlimited, because the
read-order early stop is driven by LIMIT, not by the budget. The sweep throws at 12, 20, 30, 50 and 99
with current rows: 100.00 and succeeds at 100. So every budget in [17, 99] rejects a query that reads
17 rows. That also settles the objection that the site memoizes its analysis and the executed read
reuses it: the analysis says 100, the read charges 17.

Two corrections.

  1. Patching the two Cascades sites is not sufficient. make_distributed_plan = 1 alone throws
    identically, through a third site: tryMakeDistributedRead runs only when
    enable_cascades_optimizer = 0 (optimizeTree.cpp), and it calls the enforcing, memoizing
    getOrCreateAnalyzedResult() (ReadFromMergeTree.h:425). CascadesOptimizer is built only when both
    settings are on and is the only caller of estimateStatistics, so the two modes are mutually exclusive
    and neither Cascades site runs in that one. The error therefore stays reachable with no experimental
    setting at all. I did not establish that this third shape is a false rejection: its runtime accounting
    under local fragment execution is ambiguous, and separating that needs an instrumented build rather than
    a settings sweep.

  2. It is not introduced here. Both shapes throw identically, same message and same row counts, on the
    base build this branch was cut from, and none of the three sites appears in this diff.

I am not widening this PR for it. Its scope is the parallel-replicas replica-count estimate, and the
repro engages no parallel replicas. The third site is also not a drop-in swap for the non-enforcing
helper: it memoizes deliberately and setupDistributedReadBuckets consumes the result immediately
afterwards, so making it non-enforcing forces the executed read to re-analyze, which is a
distributed-plan design call rather than a parameter change. A shared pre-final-estimate helper, as
suggested, may well be the right shape, and selectRangesToReadForEstimation plus
hasThrowingReadRowLimit from this PR are the pieces it would reuse. I am tracking it separately with
these measurements and will link a PR here if one opens.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up on the pre-final estimate sites from the review comment above (this is the separate-tracking
report I promised, not a change to this PR).

The sites. Under make_distributed_plan, four coordinator-side analyses enforce a throwing
max_rows_to_read before the read's final mode exists: Cascades/Statistics.cpp:309,
Cascades/StatisticsDerivation.cpp:383, makeDistributed.cpp:913, and Cascades/RuleUtils.cpp:39 ->
setupDistributedReadBuckets -> getOrCreateAnalyzedResult(). The fourth matters: swapping the first
three to the existing non-enforcing selectRangesToReadForEstimation() only relocates the rejection
there, because that path deliberately does not memoize. It would also reintroduce the second
coordinator-side index analysis that d60c9272da84c removed and 05175_distributed_plan_index_analysis_once
pins.

Measured false rejection. MergeTree ORDER BY a, 100 rows, index_granularity = 4,
SELECT a FROM t ORDER BY a LIMIT 5 with make_distributed_plan = 1, enable_cascades_optimizer = 1:
the plan that runs charges 17 rows (identical at max_rows_to_read 0, 100 and 1000, so the early stop
is driven by LIMIT), while every budget in [17, 99] is rejected at plan time with
current rows: 100.00.

Why I did not simply make the four sites non-enforcing. For a distributed plan that coordinator
check is currently the only place max_rows_to_read is checked at all for a read that ends up reading
in order:

  • a fragment is rebuilt from a serialized plan and ReadFromMergeTree::serialize ships no analysis, so
    it analyzes afresh, but with input_order_info already installed, which is exactly when
    MergeTreeDataSelectExecutor::getRowLimits returns empty limits;
  • the per-chunk check cannot cover it either: SelectQueryInfo::storage_limits is populated only by the
    planner and the interpreters, neither of which runs for a fragment, so ISource::getReadProgress
    falls back to an empty list and ReadProgressCallback checks nothing. QueryStatus carries only the
    time limits.

Control: SELECT a FROM t ORDER BY a LIMIT 1000000 SETTINGS max_rows_to_read = 2000 is rejected with
make_distributed_plan = 0 (per-chunk check) and, once the four sites stop enforcing, would read the
whole table with make_distributed_plan = 1.

Two adjacent gaps, for the record. A bucketed fragment's analysis-time check runs against the whole
snapshot selection rather than its own bucket (initializePipeline analyzes at
ReadFromMergeTree.cpp:4929, the bucket's marks are substituted at :5016), so a budget between one
bucket and the whole table is rejected. And a locally executed task does not insert a process-list entry
of its own, while a stateless worker does (StatelessTaskExecutor.cpp:134).

The decision I would like from a maintainer. Making the estimates non-enforcing requires the
fragment to carry the read's limits, and there is more than one sound way:

  1. serialize the read's StorageLimits list with the step: needs a query-plan serialization version
    bump, and preserves a subquery's own scoped limits;
  2. rebuild one entry in ReadFromMergeTree::deserialize from the task context: no protocol change, but
    a subquery's stricter max_rows_to_read collapses to the query-level one;
  3. keep the premature check and accept the false rejection.

Options 1 and 2 also make distributed fragments start enforcing a limit they ignore today, which is what
StatelessTaskExecutor.cpp:91 already documents but is a behaviour change for current users. I would
pick 1. If someone tells me which they want, I will implement it and link the PR here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cae048b

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. CH Inc sync passed on this head, so nothing here is ownerless.

Check / test Reason Owner / fixing PR
Build profile diff infra, not from this diff: RuntimeError: CI logs cluster query failed, raised at ci/jobs/build_profile_diff_job.py:234 from compare_symbols, so the job exits 1 instead of skipping when the CI logs cluster does not answer the binary_symbols read. The failing query is the plain symbol-size comparison for this head against base 295f03a88c5e, with no reference to the changed files #121048 (external, open)
PR aggregator status mirroring the row above #121048 (external, open)

Gates (a) to (d): 0 of 176 check runs queued or running, Config Workflow, Style check and Finish Workflow all success, Mergeable Check success, 70 min since the last job finished (anchor 2026-09-21T13:04:10Z), and every failing row above has an owner.

Session id: cron:our-pr-ci-monitor:20260921-140539

@alexey-milovidov alexey-milovidov mentioned this pull request Sep 21, 2026
1 task done
@nickitat nickitat self-assigned this Sep 22, 2026
@nickitat

Copy link
Copy Markdown
Member

@copilot resolve the merge conflicts in this pull request

…stimate-row-limit-71028-class1

# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
@groeneai

Copy link
Copy Markdown
Collaborator Author

Resolved the conflicts by merging current master in f2c235f.

The only conflict was master's new allow_top_k_prewhere_query_condition_cache_ argument in ReadFromMergeTree.cpp, in the estimation helpers this PR merges into one. It is passed exactly as on master (off when the estimate skips the query condition cache); nothing else changed, and the PR's tests pass on the merged build.

@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f2c235f05 with master 4d8c59665 (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.

Compile time of recompiled translation units

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

Job report

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Hi @nickitat, gentle ping on the question above: which option do you want for giving a distributed fragment the read's row limits (1 serialize StorageLimits with the step, 2 rebuild them in ReadFromMergeTree::deserialize, 3 keep the premature check)? Thanks.

@nickitat
nickitat added this pull request to the merge queue Oct 8, 2026
@nickitat

nickitat commented Oct 8, 2026

Copy link
Copy Markdown
Member

Hi @nickitat, gentle ping on the question above: which option do you want for giving a distributed fragment the read's row limits (1 serialize StorageLimits with the step, 2 rebuild them in ReadFromMergeTree::deserialize, 3 keep the premature check)? Thanks.

create in issue for that and ask davenger for an advice

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

Opened #124697 and asked @ davenger there. Since #119958 the fragment's read has the limits, so what is left to decide is only whether the coordinator keeps checking max_rows_to_read.

Merged via the queue into ClickHouse:master with commit 33c3959 Oct 8, 2026
149 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 8, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 17, 2026
ClickHouse#121269 fixed the same defect on master: the replica-count estimate takes
the estimation-only analysis when the read step carries a throwing row
limit. Drop this branch's src/ change and keep 05233, which covers the
automatic parallel replicas probe with force_primary_key (05250 pins
automatic_parallel_replicas_mode = 0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants