Repository navigation
Fix force_index_by_date/force_primary_key INDEX_NOT_USED reading through a view with parallel replicas (serialize_query_plan = 0 stopgap) - #109409
Conversation
…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.
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-4:20260704-192300 |
|
cc @nickitat @devcrafter — this implements the filter-pushdown-through-view fix you described on #108266: when a guard ( |
|
Workflow [PR], commit [df8ae7f] Summary: ❌
AI ReviewSummaryThis PR narrows the original fix to a Findings
Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code |
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]>
|
Pushed 522f087 to complete the follower path. The Root cause: Fix: while the pushdown is active (a guard is set and parallel replicas is used on the initiator), also disable Verified on a 3-replica loopback cluster (base build 8c1ac41e throws on the follower; fix build 31c93d46 passes): the |
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.
CI finish ledger — d9fb78bEvery 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
Not PR-caused: this PR changes only the query planner ( Session id: cron:our-pr-ci-monitor:20260705-070000 |
|
I'd prefer avoiding enabling beta settings 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 |
|
Thanks. Understood on both constraints: I will not force-enable One thing that makes a stopgap awkward: the follower path only breaks in the 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:
Which do you prefer? I can also look at |
| /// 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] |
There was a problem hiding this comment.
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.
…-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]>
|
Merged Rationale: per the discussion above, the fix must not override Verified locally on a 3-replica loopback cluster ( The option 1 vs 2 decision (close in favor of the plan-based direction, or land this stopgap) remains with @devcrafter. |
|
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. |
CI finish ledger — ff83228CI is fully finished on this head. Every failure has an owner.
The option-2 stopgap pushed by @ alexey-milovidov ( Session id: cron:our-pr-ci-monitor:20260715-070000 |
CI finish ledger — 3d2596cCI is fully finished on this head (Config + Finish Workflow passed). Every failure below has an owner; none is caused by this PR's diff.
Session id: cron:our-pr-ci-monitor:20260722-210000 |
…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]>
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]>
|
Merged
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 ( All three CI failures on the previous head were unrelated with owners (see the CI finish ledger above). |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code |
CI finish ledger - 26859fdEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260731-155315 |
This behavior is naturally fixed when |
|
Confirmed on a 3-replica loopback cluster on master (
The negative case ( One caveat before closing: 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 |
|
🕵 Routine maintenance pass: merged All three CI failures on the previous head (
The open decision is unchanged and rests with @devcrafter: close this PR in favour of the plan-based path ( |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units7 translation units recompiled, 9 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - ebbb78fCI is fully finished on this head and there are no failures to own.
178 check-runs: 160 success, 17 skipped, 0 queued or in progress, 0 failed. Moving to review. Session id: cron:our-pr-ci-monitor:20260808-170000 |
|
🕵 Merged current |
CI finish ledger - 9cb32cbEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not caused by this PR. #114756 deletes that stateless test and replaces it with a failpoint-driven This PR's diff is the filter-pushdown/ Coverage verified against praktika: 177 check-runs, 0 incomplete, 0 Session id: cron:our-pr-ci-monitor:20260816-170000 |
…` 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).
|
🕵 Upkeep pass on this PR (head
The remaining unresolved thread is the open design question (land this |
| SYSTEM FLUSH LOGS query_log; | ||
| SELECT log_comment, ProfileEvents['ParallelReplicasUsedCount'] > 0 | ||
| FROM system.query_log | ||
| WHERE event_date >= yesterday() AND type = 'QueryFinish' |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
CI finish ledger - df8ae7fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not caused by this PR. The shard's message is This PR's diff is the filter-pushdown / Coverage verified against praktika: 174 check-runs, 0 incomplete, 0 Session id: cron:our-pr-ci-monitor:20260826-093000 |
|
Fixing PR for the Performance Comparison run-errors miscount: #116491 |
|
We are moving torwards plan-based parallel replicas, there it's fixed naturaly - #109409 (comment) |
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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a false-positive
INDEX_NOT_USEDerror thrown when a query withforce_index_by_dateorforce_primary_keyreads 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); withserialize_query_plan = 1a 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_USEDforforce_index_by_date/force_primary_keyeven when the predicate covered the key:Reading the base table directly, or the view without parallel replicas, worked.
Root cause.
force_index_by_date/force_primary_keyare 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 outerWHEREstays in aFilterStepabove 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_pushdownmechanism already pushes the filter through the view boundary into the reading step. This change enables it automatically inbuildContextwhen 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::initializePipelineinjects it viaaddFilters). Withserialize_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-positiveINDEX_NOT_USEDin that mode. Per review, this fix must not overrideserialize_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 aserialize_query_plan = 0stopgap: it fixes the default AST transport; theserialize_query_plan = 1lane is deferred to plan-based parallel replicas, where index pushdown into a view works automatically. The regression test pinsserialize_query_plan = 0and 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_USEDthrough views, including nested views). Verified on a 3-replica loopback cluster: withserialize_query_plan = 0all positives pass and negatives throw; withserialize_query_plan = 1a follower still throws the documented false positive.Workflow [PR]
Sync PR [sync-upstream/pr/109409]