Skip to content

Fix force_index_by_date/force_primary_key INDEX_NOT_USED reading through a view with parallel replicas (serialize_query_plan = 0 stopgap) - #109409

Closed
groeneai wants to merge 17 commits into
ClickHouse:masterfrom
groeneai:fix-108266-filter-pushdown-view
Closed

groeneai wants to merge 17 commits into
ClickHouse:masterfrom
groeneai:fix-108266-filter-pushdown-view

Conversation

@groeneai

@groeneai groeneai commented Jul 4, 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 a false-positive INDEX_NOT_USED error thrown when a query with force_index_by_date or force_primary_key reads through a view (or subquery) with parallel replicas enabled, even though the predicate covers the partition/primary key. The fix covers the default query transport (serialize_query_plan = 0); with serialize_query_plan = 1 a follower can still throw — fixing that lane is deferred to plan-based parallel replicas.

Description

Closes: #108266

Reading through a view under parallel replicas threw INDEX_NOT_USED for force_index_by_date / force_primary_key even when the predicate covered the key:

CREATE TABLE nginx (timestamp DateTime) ENGINE = MergeTree PARTITION BY toYYYYMMDD(timestamp) ORDER BY timestamp;
CREATE VIEW v_nginx AS SELECT * FROM nginx;
SELECT count() FROM v_nginx WHERE timestamp >= '2026-06-05 12:00:00'
SETTINGS enable_parallel_replicas = 1, max_parallel_replicas = 3,
         cluster_for_parallel_replicas = 'default',
         parallel_replicas_for_non_replicated_merge_tree = 1, force_index_by_date = 1;
-- Code: 277. INDEX_NOT_USED

Reading the base table directly, or the view without parallel replicas, worked.

Root cause. force_index_by_date / force_primary_key are enforced on the MergeTree reading step (MergeTreeDataSelectExecutor::filterPartsByPartition, ReadFromMergeTree::selectRangesToRead), which must see the query's filter. When a table is read through a view under parallel replicas, the view is planned as its own inner query, so the outer WHERE stays in a FilterStep above the view boundary and never reaches the inner reading step. The key condition is then always unknown there, so both guards throw even though the outer filter is valid (the result was always correct, only the index-usage check was at the wrong layer). An explicit subquery does not hit this because the analyzer inlines it into a single plan; a view stays a separate reading step.

Fix. The existing parallel_replicas_filter_pushdown mechanism already pushes the filter through the view boundary into the reading step. This change enables it automatically in buildContext when parallel replicas is used on the initiator and either guard is set, unless the user set the setting explicitly. The index is then genuinely used, the guards are enforced correctly (a covered predicate passes, and a genuinely unused index still throws), and parallel replicas stays enabled (no fallback, no no-op).

Scope and known limitation (serialize_query_plan = 1). A follower receives the pushed filter only through the shipped query AST (ReadFromParallelRemoteReplicasStep::initializePipeline injects it via addFilters). With serialize_query_plan = 1 (the "distributed plan" transport) the initiator ships a query plan that was serialized before the filter is pushed, and the follower runs that plan and ignores the rewritten AST — so a follower's reading step still does not see the predicate and the guards can still throw a false-positive INDEX_NOT_USED in that mode. Per review, this fix must not override serialize_query_plan, and force-carrying the predicate into the serialized plan would be new transport machinery out of scope for a stopgap. So this PR is explicitly a serialize_query_plan = 0 stopgap: it fixes the default AST transport; the serialize_query_plan = 1 lane is deferred to plan-based parallel replicas, where index pushdown into a view works automatically. The regression test pins serialize_query_plan = 0 and documents the limitation in its header.

The regression test covers positives (base table as a control; view, view-over-view, and aliased view, with each guard and both; view without parallel replicas as a control) and negatives (a predicate that does not use the key must still throw INDEX_NOT_USED through views, including nested views). Verified on a 3-replica loopback cluster: with serialize_query_plan = 0 all positives pass and negatives throw; with serialize_query_plan = 1 a follower still throws the documented false positive.


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

…ry_key under parallel replicas

force_index_by_date and force_primary_key are enforced on the MergeTree
reading step, which must see the query's filter. When a table is read
through a view (or subquery) under parallel replicas, the view is planned
as its own inner query, so the outer WHERE predicate stays in a FilterStep
above the view boundary and never reaches the inner reading step. The key
condition is then always unknown there, so both guards throw a false
INDEX_NOT_USED even for a query whose predicate does cover the key. Reading
the base table directly, or the view without parallel replicas, works
because the predicate folds into the reading step.

The parallel_replicas_filter_pushdown mechanism already pushes the filter
through the view boundary into the reading step (both the initiator local
plan and the fragment shipped to the replicas). Enable it automatically
when either guard is set and parallel replicas is used on the initiator,
unless the user set the setting explicitly. The index is then genuinely
used, the guards are enforced correctly (a covered predicate passes and a
genuinely unused index still throws), and parallel replicas stays enabled.

Fixes ClickHouse#108266.
@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master (no fix), SELECT count() FROM v_nginx WHERE timestamp >= '2026-06-05 12:00:00' SETTINGS enable_parallel_replicas=1, max_parallel_replicas=3, cluster_for_parallel_replicas='default', parallel_replicas_for_non_replicated_merge_tree=1, force_index_by_date=1 throws Code 277 every time (view over a PARTITION BY toYYYYMMDD(timestamp) MergeTree). Base-table and view-without-PR variants return the correct count.
b Root cause explained? Yes. Both guards are enforced on the MergeTree reading step (MergeTreeDataSelectExecutor::filterPartsByPartition, ReadFromMergeTree::selectRangesToRead), which must see the query filter. Reading through a view under parallel replicas plans the view as its own inner query, so the outer WHERE stays in a FilterStep above the view boundary and never reaches the inner reading step. The key condition is then alwaysUnknownOrTrue() there, so the guards throw even though the outer filter covers the key (an explicit subquery is inlined into one plan and does not hit this).
c Fix matches root cause? Yes. parallel_replicas_filter_pushdown pushes the filter through the view boundary into the reading step (initiator local plan + shipped fragment). The fix enables it automatically when a guard is set and PR is used on the initiator, so the predicate reaches the reading step where the guard lives. It addresses the mechanism directly, not a symptom.
d Test intent preserved / new tests added? Yes. New test 04501_force_index_by_date_parallel_replicas_view asserts positives (view / view-over-view / aliased view, each guard and both) return the correct count AND negatives (a predicate that does not use the key) still throw INDEX_NOT_USED through views. The guards keep their meaning; a genuinely unused index still fails.
e Both directions demonstrated? Yes. Under clickhouse-test: base build (fix reverted, rebuilt) FAILS the new test (Code 277 on the view+PR+force_primary_key case); fix build passes [ OK ] (7 positives + 3 serverError negatives).
f Fix is general across code paths? Yes. Both enforcement sites (force_index_by_date in filterPartsByPartition, force_primary_key in selectRangesToRead) are covered by the same pushdown, verified for each guard alone and both together, and for view-over-view and aliased views. Not a per-site guard-skip.
g Fix generalizes across inputs? Yes. Verified across execution modes (parallel_replicas_local_plan 1/0, parallel_replicas_prefer_local_replica 1/0, remote-only), nesting (view, view-over-view, column-aliased view), and both guards. Direct-table reads are unchanged (still enforce and still throw for an unused key).
h Backward compatible? Yes. No format, setting-default, or on-disk change. parallel_replicas_filter_pushdown is only auto-enabled when not set explicitly, so an explicit user value (including =0) is always respected. No SettingsChangesHistory change needed (no default changed).
i Invariants and contracts preserved? Yes. The change only flips a query-context setting in buildContext; it reuses the existing, tested filter-pushdown machinery. Results are unchanged (the outer FilterStep always filtered correctly); only the index-usage check now sees the predicate. Parallel replicas stays enabled (no fallback, no no-op).

Session id: cron:clickhouse-worker-slot-4:20260704-192300

@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @devcrafter — this implements the filter-pushdown-through-view fix you described on #108266: when a guard (force_index_by_date/force_primary_key) is set and parallel replicas is used on the initiator, it auto-enables parallel_replicas_filter_pushdown so the outer predicate reaches the view-inner reading step. The index is genuinely used (covered predicate passes, unused index still throws), and parallel replicas stays enabled (no fallback, no no-op).

@nickitat nickitat added the can be tested Allows running workflows for external contributors label Jul 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [df8ae7f]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 4/6) FAIL Performance dashboard
adaptive_aggregation_heavy_payload #1 unstable query history
lazyMaterialization #15 unstable query history
number_formatting_formats #0 unstable query history
number_formatting_formats #2 unstable query history

AI Review

Summary

This PR narrows the original fix to a serialize_query_plan = 0 stopgap: it auto-enables parallel_replicas_filter_pushdown for force_index_by_date / force_primary_key queries under task-based parallel replicas, and adds 04501 to prove the view case stops throwing a false-positive INDEX_NOT_USED. The source-side change matches that narrowed contract, but the new system.query_log assertion in the regression is not scoped to the current run, so the test can fail on reruns even when the fix is correct.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/04501_force_index_by_date_parallel_replicas_view.sql:83] The ParallelReplicasUsedCount self-check scans every matching 04501_fipr_% row since yesterday(), while the .reference expects exactly six rows. Re-running 04501 against the same server process will pick up the previous run's rows as well and produce duplicate output unrelated to the bug being fixed. Scope the query to the current run (for example by exact query_ids / a fresh timestamp) or collapse to one row per log_comment.
Final Verdict

⚠️ Needs one test fix before merge: make the new system.query_log assertion in 04501 deterministic across reruns.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.40% +0.10%

Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 4, 2026
groeneai and others added 2 commits July 4, 2026 21:43
Lock the view-inner-query execution mode this PR fixes. The regression covers
the plan shape where the view is executed as its own inner query and the outer
predicate must cross that boundary; that mode is produced by the default
parallel_replicas_allow_view_over_mergetree = 0. If that beta setting's default
ever flips to 1, views would be planned via the outer-view path and the positive
cases would pass without exercising the parallel_replicas_filter_pushdown
auto-enable added here, so pin it explicitly to keep the test tied to the buggy
mode.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The previous change auto-enables parallel_replicas_filter_pushdown when
force_index_by_date / force_primary_key is set, so the outer predicate is
pushed through the view boundary into the reading step and the guards are
enforced correctly under parallel replicas.

That pushdown reaches a follower only through the shipped query AST
(ReadFromParallelRemoteReplicasStep rewrites the AST with the pushed-down
filter). With serialize_query_plan = 1 (the "distributed plan" mode) the
initiator ships a query plan that was serialized before the filter is pushed,
built from the query tree in the step constructor, and the follower runs that
plan and ignores the rewritten AST. So the pushed filter never reaches the
follower's reading step: its key condition is unknown, no pruning happens, and
force_primary_key / force_index_by_date throw a false INDEX_NOT_USED on the
follower even for a covered predicate.

Ship the AST for this case by disabling serialize_query_plan while the pushdown
is active (a guard is set and parallel replicas is used on the initiator).
serialize_query_plan is a transport optimization that is off by default, so it
is overridden even when set (it can be set through a profile, where isChanged
does not distinguish an explicit user choice). The follower then receives the
predicate through the AST, the index is genuinely used, and parallel replicas
stays enabled.

Fixes ClickHouse#108266.

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

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 522f087 to complete the follower path.

The distributed plan CI lane (amd_asan_ubsan, distributed plan) failed the new test: Stateless tests (...)/04501 threw Code 277 INDEX_NOT_USED from a follower (127.0.0.2) on the positive force_primary_key case. That lane sets serialize_query_plan = 1 via a config profile.

Root cause: parallel_replicas_filter_pushdown delivers the pushed filter to a follower only through the shipped query AST (ReadFromParallelRemoteReplicasStep rewrites the AST with the filter in initializePipeline). With serialize_query_plan = 1 the initiator ships a query plan that was serialized in the step constructor, before the filter is pushed, and the follower executes that plan and ignores the rewritten AST. So the follower's reading step gets Key condition: unknown (no pruning) and the guard throws even for a covered predicate. Without a guard this was masked by the outer FilterStep re-filtering the follower's full output; with the guard it surfaces as a false INDEX_NOT_USED.

Fix: while the pushdown is active (a guard is set and parallel replicas is used on the initiator), also disable serialize_query_plan so the AST is shipped and the filter reaches the follower. serialize_query_plan is a transport optimization that is off by default, so it is overridden even when set — it can arrive through a profile, where isChanged does not distinguish an explicit user choice. Parallel replicas stays enabled; the index is genuinely used on the followers.

Verified on a 3-replica loopback cluster (base build 8c1ac41e throws on the follower; fix build 31c93d46 passes): the distributed plan lane condition (serialize via profile) now passes 8/8, the normal lane 5/5 and with random settings 3/3, and the negatives (view / nested-view non-key predicate + force_*) still throw INDEX_NOT_USED. Added two positive serialize_query_plan = 1 cases and one negative to the test, so the follower path is covered on every lane.

The force-index parallel-replicas block in buildContext() disables
serialize_query_plan so the pushed-down filter reaches followers through the
shipped AST. additional_table_filters with parallel replicas is only supported
with serialize_query_plan = 1 (the analyzer throws SUPPORT_IS_DISABLED or
disables parallel replicas otherwise), so restrict the override to the case
where additional_table_filters is empty. This keeps the view follower fix
intact while leaving the additional_table_filters path untouched.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…hed filter

The previous commit skipped the serialize_query_plan = 0 override whenever
additional_table_filters was set, to protect the plain-table
additional_table_filters + parallel-replicas path (which is only supported with
serialize_query_plan = 1). But that condition also suppressed the override for a
view read that happens to have additional_table_filters targeting the view. In
that case the additional filter is applied above the view boundary, so the outer
key predicate still has to cross the boundary via parallel_replicas_filter_pushdown,
and that pushed filter reaches a follower only through the shipped AST. With
serialize_query_plan = 1 the follower serializes its plan before the filter is
pushed, so force_index_by_date / force_primary_key still threw a false-positive
INDEX_NOT_USED on the follower.

Distinguish the two cases with Context::isViewInnerQuery(), which
StorageView::getViewContext() sets on the view's inner context: a view-inner read
always ships the AST (its additional_table_filters, if any, do not constrain this
inner read), while a plain-table read keeps serialize_query_plan = 1 when
additional_table_filters is set. The new positive cases in the regression test
fail on the previous binary and pass here.
@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — d9fb78b

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) (job-level, all test rows OK) hung-check / GlobalThreadPool-shutdown deadlock (server unresponsive in teardown, SYSTEM STOP DISTRIBUTED SENDS -> Code 209 SOCKET_TIMEOUT) #108212 (ours, merged) / #105905 (ours, merged)

Not PR-caused: this PR changes only the query planner (InterpreterSelectQueryAnalyzer.cpp) plus the 04501 stateless test, which cannot cause a server shutdown deadlock during the stress teardown. Chronic across unrelated PRs. All other 172 checks pass. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109409&sha=d9fb78b097c0feb7794b1b02ad9a5e4f9ec26e52&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29

Session id: cron:our-pr-ci-monitor:20260705-070000

@devcrafter

devcrafter commented Jul 7, 2026 •

Copy link
Copy Markdown
Member

I'd prefer avoiding enabling beta settings parallel_replicas_filter_pushdown for view when force_index_by_date or force_primary_key are enabled. It's a current PR limitation. Also, parallel_replicas_allow_view_over_mergetree would work as well for simple views.

In fact, we are moving to plan based parallel replicas where the index push down into view should work automatically.

But if the life is unberable w/o fixing this limitation in current PR implementation then we can try this fix. But we shouldn't touch serialize_query_plan setting

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks. Understood on both constraints: I will not force-enable parallel_replicas_filter_pushdown for the view case, and I will not touch serialize_query_plan.

One thing that makes a stopgap awkward: the follower path only breaks in the serialize_query_plan = 1 (distributed plan) lane, because a follower receives the pushed filter only through the shipped AST, and the serialized plan predates the pushdown. Without touching serialize_query_plan, that lane cannot be fixed with the current pushdown approach. The non-distributed-plan lane works with pushdown alone.

Since you are moving to plan-based parallel replicas where index pushdown into a view works automatically, I would rather not land a partial stopgap that leaves the distributed-plan lane broken. Options:

  1. Defer to the plan-based direction and close this PR (keep force_index_by_date throws INDEX_NOT_USED exception with parallel replicas and view #108266 open for that work).
  2. Land a minimal stopgap limited to the non-distributed-plan case (pushdown only, no serialize_query_plan change), documenting the distributed-plan limitation.

Which do you prefer? I can also look at parallel_replicas_allow_view_over_mergetree for the simple-view case if that is the cleaner path.

/// replicas otherwise). So skip the override for a plain-table read that has additional_table_filters;
/// a view-inner read always ships the AST (its additional_table_filters, if any, are applied above the
/// view boundary and do not constrain this inner read).
if (result_context->getSettingsRef()[Setting::parallel_replicas_filter_pushdown]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is questionable. Needs help from @devcrafter

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, the questionable part is the serialize_query_plan override, which @ devcrafter has asked me not to touch. That override is the only way the current pushdown reaches followers in the distributed-plan lane (a follower gets the pushed filter only through the shipped AST, and the serialized plan predates the pushdown), so without it a stopgap leaves that lane broken.

I laid out the options above (issuecomment-4906803169): (1) defer to the plan-based parallel replicas direction and close this PR (keep #108266 open for that work), (2) land a minimal stopgap limited to the non-distributed-plan lane (pushdown only, no serialize_query_plan change), documenting the distributed-plan limitation, or (3) evaluate parallel_replicas_allow_view_over_mergetree for simple views. Happy to go whichever way you and @ devcrafter prefer.

alexey-milovidov and others added 2 commits July 15, 2026 04:15
…-plan limitation

The 04501 test failed in the two distributed-plan CI lanes: with
`serialize_query_plan = 1` the initiator ships a query plan serialized
before the filter pushdown, so a follower's reading step never sees the
pushed predicate and `force_index_by_date` / `force_primary_key` throw a
false-positive `INDEX_NOT_USED`. Per the review discussion the fix must
not override `serialize_query_plan`, and fixing that lane is deferred to
plan-based parallel replicas, so the test pins `serialize_query_plan = 0`
and documents the limitation.

Failing report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109409&sha=cee99bfd286734aa92ef72687d731ea5b5998067&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%2C%201%2F2%29
PR: ClickHouse#109409

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master (the branch was 11 days stale) and pushed a test-side fix for the two red distributed plan lanes: the 04501 test now pins serialize_query_plan = 0 and documents the limitation in its header.

Rationale: per the discussion above, the fix must not override serialize_query_plan, and with serialize_query_plan = 1 the initiator ships a plan serialized before the pushdown, so a follower's reading step never sees the predicate — that lane cannot pass with the current pushdown approach and its fix is deferred to plan-based parallel replicas. This is the shape of option 2 (minimal stopgap covering the default AST transport, limitation documented).

Verified locally on a 3-replica loopback cluster (test_cluster_one_shard_three_replicas_localhost): the positive cases pass with the pin, and with serialize_query_plan = 1 the follower still throws the false-positive INDEX_NOT_USED, matching the CI failure exactly.

The option 1 vs 2 decision (close in favor of the plan-based direction, or land this stopgap) remains with @devcrafter.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks @devcrafter. @ alexey-milovidov merged master and pushed the option-2 shape onto this branch: a test-only pin (serialize_query_plan = 0) with the distributed-plan limitation documented in the test header. The fix does not override serialize_query_plan; the source only auto-enables parallel_replicas_filter_pushdown when parallel replicas run on the initiator and force_index_by_date/force_primary_key is set and the user did not set the setting explicitly. CI is re-running and green so far.

The remaining call is yours: land this stopgap (option 2), or close in favor of the plan-based parallel replicas direction where the pushdown works automatically (option 1)? Either way is fine with us.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ff83228

CI is fully finished on this head. Every failure has an owner.

Check / test Reason Owner / fixing PR
Stateless tests (amd_asan_ubsan, distributed plan, parallel) — 41 unrelated tests fleet-wide host-OOM (Code 241, MEMORY_LIMIT_EXCEEDED (total) OvercommitTracker), transient 01:00-04:45 UTC window; this PR's own test 04501 is NOT among the failures #110503 (ours, open)
Finish Workflow / Post Hooks downstream cascade behind the fleet-OOM red Mergeable Check #110503 (ours, open)

The option-2 stopgap pushed by @ alexey-milovidov (serialize_query_plan = 0 test pin + documented limitation, no serialize_query_plan override, scoped pushdown auto-enable) is intact on this head; its own test lanes are green.

Session id: cron:our-pr-ci-monitor:20260715-070000

@rschu1ze rschu1ze assigned rschu1ze and devcrafter and unassigned rschu1ze Jul 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3d2596c

CI is fully finished on this head (Config + Finish Workflow passed). Every failure below has an owner; none is caused by this PR's diff.

Check / test Reason Owner / fixing PR
BuzzHouse (amd_msan) / AST subtree not found in children (STID 1218-27e6) logical error (trunk fuzzer finding, unrelated) #110394 (ours, open)
Integration (amd_asan_ubsan, db disk, old analyzer, 5/6) / test_check_table::test_check_all_tables chronic flaky (60 PRs/30d) a fix task is investigating at full effort (fixing-PR link to follow here)
Integration (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter chronic flaky (606 PRs, 121 master, 30d) #111029 (external, open, Closes #110036)

Session id: cron:our-pr-ci-monitor:20260722-210000

scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
…matically

force_index_by_date / force_primary_key over a view under parallel_replicas_plan_based no longer throw a false-positive INDEX_NOT_USED, without enabling parallel_replicas_filter_pushdown (the filter is pushed into the reading step by standard plan optimization before the split). Complements ClickHouse#109409, which fixes the query-tree path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits July 31, 2026 03:55
The positive cases only asserted final counts, which match local execution,
so the test stayed green if a planner change silently fell back to local
execution and re-broke the "parallel replicas stays enabled" part of the
contract. Tag each positive with a `log_comment` and assert
`ProfileEvents['ParallelReplicasUsedCount'] > 0` on the initiator via
`system.query_log`, following `02950_parallel_replicas_used_count`.

Verified locally on a 3-replica loopback cluster: the check returns 1 on
the fixed path and 0 when the query falls back to local execution.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master (the branch was 9 days / ~3800 commits stale, clean merge) and pushed one commit addressing the remaining actionable AI-review Major:

  • 26859fd — the 04501 regression's positive cases now prove parallel replicas actually stayed enabled: each positive is tagged with a log_comment and the test asserts ProfileEvents['ParallelReplicasUsedCount'] > 0 on the initiator via system.query_log (same pattern as 02950_parallel_replicas_used_count), so a silent planner fallback to local execution fails the test instead of passing on matching counts.

Verified on a local 3-replica loopback cluster on the merged head: the test passes, and the new check is load-bearing (returns 0 for a local-execution fallback with the identical count, 1 on the fixed path).

The other AI-review Major (serialize_query_plan = 1 follower path) remains dismissed per the recorded constraints: the override is off-limits per @devcrafter, and carrying the pushed predicate into the serialized plan is the plan-based parallel replicas work — the PR is explicitly a serialize_query_plan = 0 stopgap. The design decision (land this stopgap vs. close in favor of plan-based parallel replicas) still rests with @devcrafter.

All three CI failures on the previous head were unrelated with owners (see the CI finish ledger above).

@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.60% 78.70% +0.10%

Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 26859fd

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, parallel) / Logical error: Bad cast from type DB::ColumnNullable to DB::ColumnString (STID 5793-6473) trunk bug in MergeTreeDataPartWriterOnDisk::initColumnsSubstreamsIfNeeded, reachable on master and hit across unrelated pull requests; this PR touches only src/Interpreters/InterpreterSelectQueryAnalyzer.cpp plus one new stateless test #112501 (external, open)
Stateless tests (amd_tsan, parallel) / Server died the same abort as the row above, seen from the runner side (one event, not a second failure) #112501 (external, open)
Stateless tests (amd_tsan, parallel) / Scraping system tables post-abort diagnostics could not dump zookeeper_log because the server was already gone; downstream of the same abort #112501 (external, open)
Stress test (arm_release) / Logical error: Part level Min-Max index was constructed from unexpected columns set. (STID 5721-5ba9) trunk bug in the Min-Max index file-order hint after a part_minmax_index_columns downgrade, spread across unrelated pull requests #111511 (ours, open)
Stateless tests (amd_debug, parallel) / 04367_distributed_plan_merge_scatter_multishard real hang, not a timeout flake: an unbounded condition-variable wait when max_threads is drawn as 1. The runner's own diagnosis on this run reports Runs: 139, Failed: 0, Passed: 139, which is expected because the hang needs that draw plus scheduling luck #111762 (external, open)

Session id: cron:our-pr-ci-monitor:20260731-155315

@devcrafter

Copy link
Copy Markdown
Member

Merged master (the branch was 9 days / ~3800 commits stale, clean merge) and pushed one commit addressing the remaining actionable AI-review Major:

* [26859fd](https://github.com/ClickHouse/ClickHouse/commit/26859fd83a4592be89dd55aba95f68740f49e163) — the `04501` regression's positive cases now prove parallel replicas actually stayed enabled: each positive is tagged with a `log_comment` and the test asserts `ProfileEvents['ParallelReplicasUsedCount'] > 0` on the initiator via `system.query_log` (same pattern as `02950_parallel_replicas_used_count`), so a silent planner fallback to local execution fails the test instead of passing on matching counts.

Verified on a local 3-replica loopback cluster on the merged head: the test passes, and the new check is load-bearing (returns 0 for a local-execution fallback with the identical count, 1 on the fixed path).

The other AI-review Major (serialize_query_plan = 1 follower path) remains dismissed per the recorded constraints: the override is off-limits per @devcrafter, and carrying the pushed predicate into the serialized plan is the plan-based parallel replicas work — the PR is explicitly a serialize_query_plan = 0 stopgap. The design decision (land this stopgap vs. close in favor of plan-based parallel replicas) still rests with @devcrafter.

All three CI failures on the previous head were unrelated with owners (see the CI finish ledger above).

This behavior is naturally fixed when parallel_replicas_plan_based is enabled. See 04604_pr_plan_based_force_index_view.sql tests, added in #111063

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed on a 3-replica loopback cluster on master (865c2a5c5d2e), reading count() through a simple view with force_index_by_date = 1, force_primary_key = 1:

setting result
parallel_replicas_plan_based = 1 611200
default (parallel_replicas_plan_based = 0) Code: 277 ... (INDEX_NOT_USED)
parallel_replicas_filter_pushdown = 1 611200
parallel_replicas_allow_view_over_mergetree = 1 611200

The negative case (WHERE value = 1 with force_primary_key = 1) still throws under parallel_replicas_plan_based = 1, so the guard does not become a no-op there. 04604_pr_plan_based_force_index_view.sql is on master since #111063 merged on 2026-07-27.

One caveat before closing: parallel_replicas_plan_based is EXPERIMENTAL and defaults to false, so on a default configuration the false positive is still reachable (row 2). Weighing that is your call. I am fine with closing #109409 in favour of the plan-based path, and I would rather not land a stopgap that auto-enables a beta setting, which is what you objected to originally.

Could you close #109409 once you have decided, since you are the assignee? I will not push anything further to the branch.

For #108266: do you consider it fixed once parallel_replicas_plan_based is enabled, or should it stay open until that is the default?

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Routine maintenance pass: merged master (the branch was 8 days / ~3700 commits stale; clean merge, no conflicts) and pushed ebbb78ff435. The modified translation unit compiles on the merged head, and the referenced settings (parallel_replicas_filter_pushdown, force_index_by_date, force_primary_key) and canUseParallelReplicasOnInitiator are unchanged on current master.

All three CI failures on the previous head (26859fd83a4) were unrelated to this PR's diff, each with an owner:

Check / test Reason Owner
Stateless (amd_debug) / 04367_distributed_plan_merge_scatter_multishard timeout, CI-diagnosed not reproducible (139/139 reruns passed) #112301
Stateless (amd_tsan) / Bad cast from type DB::ColumnNullable to DB::ColumnString in SerializationString::serializeBinaryBulkWithSizeStream (+ consequent "Server died") MergeTree write-path serialization, not touched here #113891
Stress (arm_release) / Part level Min-Max index was constructed from unexpected columns set in getProbablyWrittenFiles part minmax width mismatch fix in flight in #112878

The open decision is unchanged and rests with @devcrafter: close this PR in favour of the plan-based path (parallel_replicas_plan_based, #111063, covered by 04604_pr_plan_based_force_index_view) or land this serialize_query_plan = 0 stopgap because parallel_replicas_plan_based is experimental and off by default, so the false positive is still reachable on a default configuration. This push is only mechanical branch upkeep and does not presume either outcome.

@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing df8ae7fc8 with master 887b93e16 (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
Binary Master PR Δ
programs/clickhouse-stripped 710.16 MiB 707.12 MiB -3.04 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ebbb78f

CI is fully finished on this head and there are no failures to own.

Check / test Reason Owner / fixing PR
CH Inc sync private upstream sync CH Inc sync (private, not actionable)

178 check-runs: 160 success, 17 skipped, 0 queued or in progress, 0 failed. Config Workflow and
Finish Workflow are both green. CIDB has ingested this commit (326872 rows across 160 distinct
checks) with 0 rows in FAIL or ERROR.

Moving to review.

Session id: cron:our-pr-ci-monitor:20260808-170000

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master and resolved the adjacent InterpreterSelectQueryAnalyzer.cpp conflict by retaining both the guarded parallel_replicas_filter_pushdown setup and the current inject_random_order_for_select_without_order_by safeguard. The branch is updated; the remaining option-1-vs-option-2 product decision explicitly belongs to @devcrafter.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9cb32cb

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. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, s3 storage, parallel, 1/3) / 04512_aggregation_in_order_cancellation flaky: the test asserts a KILL lands within a wall-clock window, which is not reliable under TSan #114756 (mine, open)

Not caused by this PR. #114756 deletes that stateless test and replaces it with a failpoint-driven
integration test, so it addresses this exact failure mode rather than a neighbouring one. It is still
open, so the fix is not on this head and rule 3b applies (link it, no master merge).

This PR's diff is the filter-pushdown/force_index_by_date path in InterpreterSelectQueryAnalyzer
and does not touch AggregatingInOrderTransform or query cancellation.

Coverage verified against praktika: 177 check-runs, 0 incomplete, 0 DROPPED leaves.

Session id: cron:our-pr-ci-monitor:20260816-170000

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
…` opt-out

The fix only auto-enables `parallel_replicas_filter_pushdown` when the user
did not set it explicitly (`isChanged`), but `04501` never exercised that
contract: an unconditional "always set it to `1`" would have kept every
positive green while silently ignoring an explicit
`parallel_replicas_filter_pushdown = 0`.

Add three negatives pairing a covered view predicate with an explicit
`parallel_replicas_filter_pushdown = 0` (both guards together and each on its
own), which must still throw the pre-fix `INDEX_NOT_USED`, plus a positive with
an explicit `parallel_replicas_filter_pushdown = 1`.

Verified on a local three-replica loopback server: the test passes and the new
negatives do throw (the `serverError` hints are enforced client-side).
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Upkeep pass on this PR (head df8ae7fc8899):

  • Merged master (branch was 11 days stale, clean merge, no submodule drift; net diff vs master unchanged apart from the test additions below).
  • The single CI red on the previous head — 04512_aggregation_in_order_cancellation in Stateless tests (amd_tsan, s3 storage, parallel, 1/3), unrelated to this PR — is fixed on master: Replace the AggregatingInOrderTransform cancellation test with a failpoint integration test #114756 merged on 2026-08-16 (it replaces that stateless test with a failpoint integration test) and Flaky test: 04512_aggregation_in_order_cancellation #116304 was closed as fixed by it. Merging master pulls the fix in.
  • Addressed the unresolved AI-review finding (the only actionable one): 04501_force_index_by_date_parallel_replicas_view now covers the explicit parallel_replicas_filter_pushdown override — three negatives with an explicit parallel_replicas_filter_pushdown = 0 over a covered view predicate that must still throw INDEX_NOT_USED, plus a positive with an explicit parallel_replicas_filter_pushdown = 1. This pins the isChanged guard as load-bearing. Verified on a local three-replica loopback server: the test passes on the merged head.

The remaining unresolved thread is the open design question (land this serialize_query_plan = 0 stopgap vs. close in favour of plan-based parallel replicas, #111063) — that is @devcrafter's call; nothing changed there in this pass.

SYSTEM FLUSH LOGS query_log;
SELECT log_comment, ProfileEvents['ParallelReplicasUsedCount'] > 0
FROM system.query_log
WHERE event_date >= yesterday() AND type = 'QueryFinish'

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 system.query_log self-check is not scoped to the current run: it reads every QueryFinish row in current_database() whose log_comment matches 04501_fipr_% since yesterday(), but the .reference expects exactly six rows. If 04501 is re-run against the same server process, the six rows from the previous run are still visible here, so this query returns 12 rows and the regression fails for reasons unrelated to the force_index_* fix. The other log_comment LIKE ... tests around this area usually avoid that by adding an event_time window, selecting the exact query_ids they just issued, or collapsing to one row per log_comment. Can we scope this assertion the same way?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, with a correction to which lane this bites in and to which of the three fixes holds.

The ordinary stateless lanes are already safe: the runner mints a fresh test_<random> database per test execution and drops it afterwards (tests/clickhouse-test:2263, _cleanup gated on need_cleanup = not args.database at :4043), so current_database = currentDatabase() keys on a value unique to that attempt.

The stress lanes are the exposure. ci/jobs/scripts/stress/stress.py:372 pins --database=test_{i} on odd workers and :354 gives i % 3 == 2 workers --replicated-database --database test_{i}, so one database serves that worker's whole run and is never dropped. The trigger is the runner's own retry: MAX_RETRIES = 3 on any MESSAGES_TO_RETRY hit (tests/clickhouse-test:201, :119), a list that includes ConnectionPoolWithFailover: Connection failed at try, which this test's three-replica pool can produce under the stress disruptor. The retry re-runs the file, still sees the first attempt's six rows, returns twelve, and fails on the row count instead of on the transient.

That also rules out the event_time window, which only helps if the retry lands outside it and nothing guarantees that; 02950_parallel_replicas_used_count, which this assertion follows, has the same hole. Collapsing to one row per log_comment holds: GROUP BY log_comment with argMax(ProfileEvents['ParallelReplicasUsedCount'] > 0, event_time_microseconds) returns exactly six rows however many attempts ran.

One caveat that would otherwise rule argMax out, and turns out not to: the stress profile enables the server-side AST fuzzer for any query and a fuzzed re-execution does inherit log_comment, but it never reaches logQueryFinish, because the fuzzer drives the pipeline itself and never calls BlockIO::onFinish. Measured on a debug build, 20 seeds at ast_fuzzer_runs = 5: the 100 fuzzed runs produced 68 QueryStart and 32 ExceptionBeforeStart rows carrying the seed's log_comment, and 0 QueryFinish.

I am not pushing this over the current head, so the edit is for whoever is working the file.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - df8ae7f

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. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 4/6) perf harness: compare.sh writes one run-errors.tsv row per traceback LINE, so a single failing perf test scores 10 errors, and that substring is the only term that fails the shard a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)

Not caused by this PR. The shard's message is 10 errors, 11 too long, 4 unstable. Over 30 days the
same errors term reds this check on 47 other PRs and 9 times on master, on both amd_release and
arm_release. Mechanism: ci/jobs/scripts/perf/compare.sh:1769-1773 passes GNU-BRE escape
sequences, including escaped grouping plus \| and \+, to rg, whose Rust-regex dialect reads
them as literal characters. Both selective patterns therefore miss every Python traceback and the
head -10 fallback emits ten traceback lines as ten rows. report.py:394 counts rows via
error_tests += len(run_error_rows) and performance_tests.py:1914 fails the check on the substring
errors. The too long term does not gate at all: 64,548 green runs of this check carry it.

This PR's diff is the filter-pushdown / force_index_by_date path in
InterpreterSelectQueryAnalyzer, guarded by canUseParallelReplicasOnInitiator together with
force_index_by_date or force_primary_key. The performance harness sets none of those three, so
the new branch never runs in the performance suite.

Coverage verified against praktika: 174 check-runs, 0 incomplete, 0 DROPPED leaves.

Session id: cron:our-pr-ci-monitor:20260826-093000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison run-errors miscount: #116491

@devcrafter

Copy link
Copy Markdown
Member

We are moving torwards plan-based parallel replicas, there it's fixed naturaly - #109409 (comment)

@devcrafter devcrafter closed this Aug 26, 2026
pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Sep 20, 2026
compare.sh picks one error blurb per failing performance test with a
three-tier fallback: match a line naming an exception, else a line of the
"socket.timeout: timed out" shape, else the first ten lines of the log.
Both selective patterns were written in GNU basic-regex syntax, with
escaped grouping, alternation and quantifier, but they are executed by
ripgrep, whose dialect reads those escapes as the literal characters
"(", "|" and "+". Tier one therefore searched for the literal text
"(Exception|Error):" and tier two for one non-space followed by a literal
plus, a colon and a space. Neither can match a Python traceback.

The patterns are valid regexes, so ripgrep exits 1 for "no match" rather
than 2 for "bad pattern", and the || chain silently took head -10 on
every failing test. head -10 captures the TOP of a traceback, so the
exception at the bottom was never recorded. Deleting six backslashes
restores the original intent: basic-regex \(A\|B\):[^:] and rust-regex
(A|B):[^:] are the same language, as are ^[^ ]\+: and ^[^ ]+: .
ripgrep has no POSIX-basic mode, so no flag makes the old spelling mean
what it said.

head -10 then emitted ten lines, sed prefixed each with the test name,
and report.py did error_tests += len(run_error_rows), counting rows under
a name that says tests, so one failing test scored ten. Counting distinct
test names makes the variable's name true.

Measured in default.perf_run_errors_v1, the sink for run-errors.tsv:
345,311 groups of exactly ten rows per (run, test) and zero groups of one
or two, even though --max-count=2 can only ever emit one or two, so the
selective tiers had never once fired. In the 30 days to 2026-08-26 the
"errors" term reds 142 Performance Comparison master_head runs across 47
pull requests, plus 9 runs on master whose message begins with exactly
"10 errors". Of the release_base rows, 113,800 of 113,810 are argparse
usage text while zero contain the "unrecognized arguments" line that
actually names the defect; that line matches tier two.

This cannot turn a red shard green. head -10 is kept and a ripgrep exit
of 1 still falls through, so a non-empty error log still yields at least
one row, and report.py hardcodes the plural " errors" for every count, so
the substring gate in performance_tests.py still fails the shard on
"1 errors". Only the number and the text change.

Verified on the artifacts of a real failing job (PR ClickHouse#109409, arm_release
master_head 4/6): before the change, running report.py in that run's
extracted working directory reproduces its own message
"10 errors, 11 too long, 4 unstable" byte for byte, and the extraction
block reproduces its run-errors.tsv byte for byte; after the change the
same inputs give "1 errors, ..." and two rows naming the ServerException
and the 300 s timeout. Per .claude/CLAUDE.md the tests for a CI script
change are throwaway and not committed, and ci/tests is being removed in
Remove ci/tests (attempt 2).

Related: ClickHouse#109409

Co-Authored-By: Claude Opus 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 groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

force_index_by_date throws INDEX_NOT_USED exception with parallel replicas and view

5 participants