Skip to content

Add a regression test for force_primary_key with the automatic parallel replicas probe - #121301

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:autopr-estimate-no-throwing-row-limits
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:autopr-estimate-no-throwing-row-limits

Conversation

@groeneai

@groeneai groeneai commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #71028
Related: #121269

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

Regression test for class 2 of #71028. With automatic_parallel_replicas_mode 1 or 2 and parallel_replicas_min_number_of_rows_per_replica set, the probe plan's replica-count estimate enforced max_rows_to_read and max_rows_to_read_leaf while force_primary_key was cleared, so a query that must fail with INDEX_NOT_USED failed with TOO_MANY_ROWS instead (04032_fixedstring_prefix_key_condition, 03171_indexing_by_hilbert_curve).

The fix landed in #121269. This PR carried the same fix and is now cut down to its test, as requested in #71028 (comment): the test of #121269, 05250, pins automatic_parallel_replicas_mode = 0 and does not reach the probe.

05233 covers force_primary_key through modes 1 and 2, the TopK read that skips the query condition cache, a read through a view whose own SETTINGS carry the limit, the leaf row limit and the single-node path, plus controls where the read really exceeds the limit and must still fail with TOO_MANY_ROWS. Each arm also checks AutomaticParallelReplicasProbePlansBuilt, so it cannot pass by skipping the probe: with parallel_replicas_local_plan = 0 every error still matches and only that check goes red.

Validation: on current master (d6c2532ef90) it passes 50 of 50 runs under default randomization and 50 of 50 under the #71028 reproduction settings. On a base without #121269 it fails with Expected server error code: 277 but got: 158.


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

groeneai and others added 5 commits September 21, 2026 06:05
…ount estimate

With automatic parallel replicas enabled, a query that sets force_primary_key = 1
together with a throwing max_rows_to_read and a non-zero
parallel_replicas_min_number_of_rows_per_replica received TOO_MANY_ROWS instead of
INDEX_NOT_USED, so the force-index guard was silently not enforced.

The automatic-parallel-replicas optimization builds a throwaway probe plan purely to
cost whether replicas pay off, and deliberately clears force_primary_key on it. That
probe's planner-time index analysis, however, still ran with the user's throwing row
limits enforced, and it runs before the real plan's analysis. So the probe's
max_rows_to_read violation escaped to the client and preempted the INDEX_NOT_USED the
real plan would have raised. The exception stack places the throw under
considerEnablingParallelReplicas building that probe, not under the executed read.

Select the estimation-only analysis when the query carries a throwing read-row limit,
the same shape estimateReadRowsCount already uses for the same reason: later planning
may make the executed read exempt from those limits, and the executed read analyzes
again once its final mode is known. Queries without such a limit keep the memoizing
selectRangesToRead path, so none pays a second index analysis it does not pay today.
estimateRangesToReadWithoutQueryConditionCache takes check_row_limits as a required
parameter, so its only caller states per query whether the analysis it asks for is
throwaway.

No setting is added and no default changes, so SettingsChangesHistory.cpp needs no
entry; the only behaviour change is which error an already-failing query receives.

Reported by Alexey Milovidov on ClickHouse#71028 as class 2 of the latent parallel-replicas bugs
that randomizing parallel_replicas_min_number_of_rows_per_replica surfaced, via
04032_fixedstring_prefix_key_condition and 03171_indexing_by_hilbert_curve.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ver the remaining estimate paths

Review follow-up to the previous commit.

The gate that decides whether the replica-count estimate may enforce throwing row
limits is now read from the analyzed step's context instead of from the query being
planned, matching the sibling call site in RelationStatisticsEstimator.cpp. Range
analysis takes the limits it enforces from that context
(MergeTreeDataSelectExecutor::filterPartsByPrimaryKeyAndSkipIndexes), so that is the
object the gate has to agree with. The two objects coincide for a direct read and
for a read through a view the estimate cannot descend into, but they diverge when the
outer planner finds the read inside an eligible view: there the row limit comes from the
view's own context and the query selecting from it carries none. On that shape this is a
behaviour change, and the view arm added in the following commit pins it.

The regression test now pins every setting that gates building the probe plan.
parallel_replicas_local_plan is randomized by the test runner and at 0 the probe is
never built, so the arms could pass without observing anything; with the pins the
unfixed binary fails 50 of 50 randomized runs.

Three arms are added:

* a read reached through a view, where the row limit comes from the view rather than
  from the query selecting from it;

* the arm that skips the query condition cache, which needs
  use_query_condition_cache_for_top_k = 0 together with ORDER BY and LIMIT. No test
  reached it, so the new check_row_limits parameter survived being hard-coded back to
  true;

* automatic_parallel_replicas_mode = 0 with parallel replicas enabled, the one
  configuration in which this change moves limit enforcement from planning to the
  executed read. It pins that TOO_MANY_ROWS is still raised there, now from the
  executed read's own re-analysis.
…eaf row limit

Review follow-up. The fix's control flow is unchanged; a dead default argument is
dropped and two arms are added.

The view arm's inner query carried an ORDER BY, which makes the view ineligible for the
view-over-MergeTree path, because getUnderlyingMergeTreeStorageForParallelReplicas
accepts only a pass-through inner query. The estimate then ran inside the nested planner
that StorageView::read builds, where the planner's settings and the read step's context
are the same object, so the arm could not tell the two apart. Without the ORDER BY the
view is eligible: the estimate runs in the outer plan on the read found inside the view,
the outer query carries no row limit of its own, and the limit the analysis enforces
comes from the view's context. The arm now discriminates, and reading the gate from the
query being planned rather than from the analyzed step leaves it failing with
TOO_MANY_ROWS.

Two arms cover max_rows_to_read_leaf, the gate's second clause. No arm set it, so
deleting that clause kept the whole test green while every leaf-limited query went back
to receiving TOO_MANY_ROWS instead of INDEX_NOT_USED.

estimateRangesToReadWithoutQueryConditionCache no longer defaults check_row_limits. Its
only caller passes the argument, and a future caller should have to decide whether the
analysis it asks for is throwaway.

Co-Authored-By: Claude Opus 5 <[email protected]>
The arms were written A, B, D, C, E and on, so the file reads out of order.

Arm C switches enable_parallel_replicas off, so whichever arm follows it has to set
that setting again to observe anything. Arm D covers the row limit still biting when
parallel replicas really are used and inherits the setting from the preamble, so
moving arm C in front of it also gives arm D its own, the way the arms that already
follow C carry theirs. Without that line arm D would still expect TOO_MANY_ROWS and
still pass, from the single node path instead of the one it is there to cover.

Co-Authored-By: Claude Opus 5 <[email protected]>
Tighten the estimate-path comment to two lines; no content removed.
@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; 4 rounds, 5 gate findings plus my own
cold reviews; the last two gate rounds returned 0 findings on this diff). Rows below are the findings
that bear on shipped content; draft-artifact corrections are kept out of it. Every AGREEd item is
fixed in the branch's follow-up commits; the citations are the durable reference.

# Sev Finding Verdict Evidence / action
1 ❌ The throwing-limit guard was read from the planner's settings, while the analysis it selects consumes the read step's context settings (src/Planner/PlannerJoinTree.cpp) AGREE, fixed Enforcement derives the limits from filter_context's context (MergeTreeDataSelectExecutor.cpp:1175, :1548), and the precedent this copies reads the step's own context (RelationStatisticsEstimator.cpp:132). Guard now reads reading_step->getContext()->getSettingsRef(); a view carrying its own max_rows_to_read pins the difference
2 ⚠ The test could pass without ever building the probe plan: parallel_replicas_local_plan is randomized and was unpinned AGREE, fixed Randomized at tests/clickhouse-test:1874; at 0 the builder declines (InterpreterSelectQueryAnalyzer.cpp:195-199) and the untouched path returns the expected error anyway. Every probe-gating setting is now pinned
3 ⚠ The new check_row_limits argument had no test: its only caller needs use_query_condition_cache_for_top_k = 0 plus ORDER BY with LIMIT AGREE, fixed That setting defaults to true and is not randomized, so the arm was unreachable repo-wide. Added an ORDER BY ... LIMIT case with the TopK cache gate off; hard-coding the parameter back to true reddens that arm alone
4 ⚠ No arm covered automatic_parallel_replicas_mode = 0 with parallel replicas on, the only case where enforcement moves from planning to the executed read AGREE, fixed That cell decides whether a query that used to fail with TOO_MANY_ROWS still fails at all. Added as a control; the throw now comes from the executed read's own re-analysis
5 ⚠ The view arm could not discriminate the guard's settings source: its inner ORDER BY made the view ineligible for the view-over-MergeTree path, so the estimate ran inside the view's nested planning, where the two settings objects coincide AGREE, fixed StorageView.cpp:456-458 rejects such a view, and getViewContext (:338-345) leaves parallel replicas on inside it precisely because it was rejected, so the arm was red pre-fix but proved less than it looked. Without the inner ORDER BY the view is eligible, the outer planner analyses a read whose context is the view's, and the arm is red without row 1's fix
6 ⚠ Nothing covered max_rows_to_read_leaf, the predicate's second clause AGREE, fixed getRowLimits treats the leaf limit symmetrically (MergeTreeDataSelectExecutor.cpp:1548-1568), so deleting that clause left every arm green while leaf-limited queries kept the bug. Added the leaf twin of the defect arm plus its limit-still-bites control, and mutation-checked both
7 ⚠ A commit message called reading the guard off the analyzed step an alignment and "not a behaviour change" on every reachable shape AGREE, fixed Refuted on the example that claim cites: for a read the outer planner finds inside an eligible view the two settings objects diverge, and the arm added there is red without the change. The message now states where they coincide, where they diverge, and which arm pins it
8 💡 estimateRangesToReadWithoutQueryConditionCache's check_row_limits default argument had no user AGREE, fixed One call site tree-wide, always explicit. Default removed so a future caller must decide whether its analysis is throwaway
9 💡 Arm E's comment stated the opposite of the mechanism it relies on AGREE, fixed automatic_parallel_replicas_min_bytes_per_replica = 0 disables the pre-planning size gate (considerEnablingParallelReplicas.cpp:340-343) rather than passing it

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.

Two hazards this change could plausibly have introduced were checked and are absent. The extra
non-memoizing analysis makes getAnalyzedResult() null more often on the probe's local read, and
considerEnablingParallelReplicas.cpp:540 treats null as the normal case and transplants the
single-node analysis, so no LOGICAL_ERROR becomes reachable and
04034_autopr_min_rows_per_replica_reuses_index_analysis is not undermined. And
optimize_use_implicit_projections is randomized and unpinned, which could have routed the
limit-still-bites arms through the graceful exceeded_row_limits return instead of the throw; it
cannot, because neither fixture has projections, projection parts, or exact-range analysis.

One disclosure about the test: arm D re-asserts SET enable_parallel_replicas = 1, which the arms
after it also do, because arm C turns the setting off and arms share one session. Without that line
arm D still satisfies its TOO_MANY_ROWS expectation, from the single-node path rather than the
parallel-replicas path it exists to cover, so the emptying would be silent; probed directly, and the
serverError expectation is negative-controlled.

Also examined and deliberately not raised. Cascades/Statistics.cpp:309 and
Cascades/StatisticsDerivation.cpp:383 run the same costing analysis with throwing row limits
enforced, but they memoize the result and do not clear force_primary_key, so they cannot report an
error the executed read would not, and they sit behind enable_cascades_optimizer, off by default.
The old-analyzer sibling of the changed call site (InterpreterSelectQuery.cpp:1263 ->
estimateNumberOfRowsToRead) still analyses with limits enforced, but it cannot trip them: it sets
query_info_copy.trivial_limit from max_rows_to_read and the executor clamps the running estimate
to trivial_limit before checking (MergeTreeDataSelectExecutor.cpp:1351-1357). And the new
predicate duplicates RelationStatisticsEstimator.cpp:133-135 verbatim; a shared helper would edit a
pre-existing call site outside this change's scope, so the established shape is copied instead.

Session id: cron:clickhouse-review-slot-8:20260921-080103

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Question Answer
a Deterministic repro? Yes. 04032_fixedstring_prefix_key_condition with the five culprit settings pinned and randomization off, 100%; Expected server error code: 277 but got: 158, max rows: 3.00, current rows: 6.00. The new test is red in 50 of 50 randomized runs before the fix.
b Root cause explained? The automatic-parallel-replicas probe plan runs planner-time index analysis with the user's throwing row limits enforced while having cleared force_primary_key, and it runs before the real plan's analysis, so its max_rows_to_read violation preempts the INDEX_NOT_USED. Exception stack: SizeLimits::check <- ReadFromMergeTree::selectRangesToRead <- buildJoinTreeQueryPlan <- considerEnablingParallelReplicas.
c Fix matches root cause? Yes. A costing analysis stops enforcing an execution limit, at the only site that knows the analysis is throwaway. No widened bound, no test tag, no settings clamp, no guard at the throw site.
d Test intent preserved / new test added? No existing test modified. 05233_force_primary_key_auto_parallel_replicas adds one arm per scenario: the bug; the row limit still biting; the row limit still biting when parallel replicas really are used; the single-node contract; the mode-1 route; the query-condition-cache-skipping route; a read inside a pass-through view, where the limit comes from the view's own context rather than from the query selecting from it; and the same first two arms again through max_rows_to_read_leaf. Every setting that gates building the probe plan is pinned in the test, because at parallel_replicas_local_plan = 0 (randomized by the runner) the probe is not built and the arms would pass vacuously.
e Both directions? Yes, between binaries differing only by this diff. 04032: red before, green after. New test: 50 FAIL / 0 OK before, 50 OK / 0 FAIL after, and 50 OK / 0 FAIL under default randomization. 03171's query shape: 158 before, 277 after.
f General across code paths? Both arms of the estimate are covered, and every part of the change is mutation-checked: three separate mutants, each restoring one half of the source diff, turn one specific test arm red and leave the rest green (the query-condition-cache call, the leaf clause of the row-limit gate, and reading that gate from the analyzed step rather than from the query being planned). Every other costing-analysis carrier was measured: the relation-statistics estimate already had this guard and is untouched; the mode-1 bytes gate analyzes the main plan's step and memoizes, so it is not a throwaway and raises the correct error; the main-plan analysis is untouched.
g Generalizes across inputs? The change is plan-level control flow keyed on settings, so type wrappers are not carriers. The settings matrix is the input space and is covered: automatic_parallel_replicas_mode {0,1,2} x parallel_replicas_min_number_of_rows_per_replica {0,1} x force_primary_key {0,1} x the row limit {max_rows_to_read, max_rows_to_read_leaf} x {absent, exceeded, not exceeded} x the query-condition-cache TopK gate {on, off} x the read {direct, inside a view}.
h Backward compatible? Yes. No setting added, no default changed, so no SettingsChangesHistory.cpp entry and no format change. The only behaviour change is which error an already-failing query receives. The one configuration where enforcement moves from planning to the executed read (automatic_parallel_replicas_mode = 0 with parallel replicas on) has its own test arm: TOO_MANY_ROWS is still raised, with the same message, from the executed read's own re-analysis.
i Invariants and contracts preserved? The estimation call does not memoize, so the executed read still analyzes with its own final shape. Measured rather than assumed: with the fix, the stack for that arm goes through getAnalysisResultImpl under initializePipeline instead of through the planner. No data path, block structure, sort order or concurrency contract is touched; no durability path is involved.

Regression sweeps, FAIL-set diffs against the unfixed binary on the same rig, same client binary, randomization off: the parallel_replicas suite (140 tests, the runner's positional pattern) and a blast-radius suite (123 test files, 129 instances: content matching force_primary_key, or a row-limit setting crossed with force-index/parallel-replicas). Each suite was swept twice, once with the culprit settings that make the changed path reachable at all (with defaults, enable_parallel_replicas = 0, so nothing reaches it) and once at plain defaults. Zero tests fail only with the fix, in all four sweeps. Three fail only without it: the new test, 04032_fixedstring_prefix_key_condition, and 03560_parallel_replicas_projection, an existing test the fix repairs (deterministic 3/3 each way). Every test failing on both binaries was checked to fail for the same reason on both, so that bucket hides nothing; 04654_parallel_replicas_merging_aggregated_no_top_k is excluded as flaky (OK FAIL OK with the fix) rather than counted as an improvement.

force_index_by_date needs no change: the probe does not clear it, so it still fires there. Verified non-vacuously on the same fixture (the same query without it hits the row limit; with it alone the partition expression is genuinely unusable), so no permanent test arm was added for it.

@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0aa5368]

Summary: ✅


AI Review

Summary

PR #121301, head 0aa5368fae0e0ddf895717bfa16dce935df9220a, adds regression coverage for force_primary_key with the automatic parallel replicas probe, including both read row limits, the TopK estimation path, and view-local settings. The implementation fix already landed in PR #121269. No actionable findings in the current test-only diff.

Missing context / blind spots
  • ⚠️ Runtime evidence relies on the author's reported repeated passes and failure on an unfixed base. Current-head stateless and flaky-check CI jobs are still running, and no local ClickHouse binary was available. Completed CI reports would close this validation gap.
Final Verdict

Status: ✅ Approve.

@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
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ea4843d92 with master 2ee0ab46f (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 295f03a88; 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ea4843d

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
Upgrade check (amd_release) / Error message in clickhouse-server.log not from this diff: the scan holds one error code only, Code: 47 UNKNOWN_IDENTIFIER with the message Unknown expression identifier b. Maybe you meant: ['a'], raised by MutatePlainMergeTreeTask on part all_1_1_1_2. That line carries 97 rows on 91 distinct pull requests in 30 days with 0 on true master, onset 2026-08-31, and this PR changes the parallel replicas replica-count estimate, not mutation execution #118499 (mine, open)
Mergeable Check, PR aggregator statuses mirroring the row above #118499 (mine, open)

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

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

groeneai and others added 2 commits October 17, 2026 12:41
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]>
With the fix on master every arm gets the same error whether or not the
automatic parallel replicas probe is built, so assert the probe counter per
arm. With parallel_replicas_local_plan = 0 only this check goes red.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Do not enforce throwing row limits in the parallel replicas replica-count estimate Add a regression test for force_primary_key with the automatic parallel replicas probe Oct 17, 2026
@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 17, 2026

This branch has not been deployed

No deployments
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-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