Repository navigation
Fix wrong results of ORDER BY ALL with an integer constant over remote inside a view and over Merge - #124870
Conversation
…uery `ORDER BY ALL` (and `GROUP BY ALL` / `LIMIT BY ALL`) expands to the whole projection after positional arguments are replaced, so an integer constant in the projection reaches the printed shard query as a bare literal, e.g. `SELECT 3, k, src ... ORDER BY 3 DESC, k DESC, src DESC`. `createLocalPlan` marks the local replica's context with `setPositionalArgumentsAlreadyResolved(true)`, but `replaceNodesWithPositionalArguments` honoured that flag only outside view-inner contexts, and the copied context inherits `is_view_inner_query` when the `remote`/`Distributed` read is inside a view. The local replica then resolved `3` as the third projection column, while the remote replicas kept it a constant. Consequences: the merged stream is not sorted by the `ORDER BY`, `DISTINCT` in order returns duplicates and trips the `Equal values are not contiguous` assertion in debug builds, and a constant larger than the pruned projection fails with `Positional argument number N is out of bounds`. The already-resolved flag is now authoritative. The view-inner exemption is kept only for the SECONDARY_QUERY skip, and the two view-context makers reset the flag, so a view body read through a local shard plan is still resolved where it is expanded (03802, 04105). `ReadFromMerge` re-analyzes a child from the AST printed from the resolved query tree without setting the flag, which gave the same double resolution for a `Merge` table over a MergeTree and a Distributed table (rows of default values, or the out-of-bounds error); it now sets the flag as well. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`analyzer_inline_views = 1` resolves a view body in the context made by `StorageView::getViewSubqueryContext`, so the reset of the already-resolved flag there needs its own case: without it the inlined body of `v_pos` (`GROUP BY 1`) fails with `NOT_AN_AGGREGATE` when read through the local replica of `remote`. Also correct the `positional_arguments_already_resolved` field comment: the flag is copied with the context, and only the view contexts reset it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 rounds; 2 findings in round 1, 0 in round 2).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20261009-090700 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20261009-084400 |
|
Workflow [PR], commit [7a7a3c7] Summary: ❌
AI ReviewSummaryThe change prevents local shard plans inside views from interpreting already-resolved integer constants as positional arguments, while preserving positional resolution for fresh query bodies. Reviewed head Final VerdictStatus: ✅ Approve. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes96 object files changed (+21.36 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units1314 translation units recompiled, 8555 s compile time in total, 1313 of them have a recent master baseline. Translation units without a recent master baseline:
|
CI finish ledger - 812012dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The new test Session id: cron:our-pr-ci-monitor:20261009-143012 |
…analyzes The "already resolved" mark of a local shard plan is inherited by every context copy, so besides view bodies it also reached queries that are not printed from the shard query: input queries of `executable`, row policies and `additional_table_filters` (also of an inlined view), and the query argument of a table function in a subquery with `SETTINGS`. Their `ORDER BY 1` / `GROUP BY 1` stayed constants: wrong rows or NOT_AN_AGGREGATE. On master they resolved inside a view, through the view-inner exemption that the previous commit removed, so this also fixes that regression. `Context::withUnresolvedPositionalArguments` resets the mark for these queries. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… as a view body
`obfuscate` (`ObfuscateSource::makeInnerContext`, now on master) marks its hidden
inner query with `setIsViewInnerQuery(true)` and relies on it to resolve
positional arguments also on a local shard plan context. Since the view-inner
exemption is gone from `replaceNodesWithPositionalArguments`, that context kept
the `positional_arguments_already_resolved` flag inherited from the local plan,
so `remote('127.0.0.1', obfuscate(... ORDER BY 1 DESC LIMIT 1))` read the wrong
row and `GROUP BY 1` failed with NOT_AN_AGGREGATE on the local replica only.
Every caller of `setIsViewInnerQuery(true)` marks a query body parsed from
scratch, so the setter now resets the flag itself. This replaces the two
explicit resets in `StorageView` and covers `obfuscate` without touching it.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hard query The local shard plan of a `remote`/`Distributed` read inside a view body analyzes the shard query with a copy of the view context. The context flag `positional_arguments_already_resolved` is ignored in view bodies, so the shard query was re-resolved positionally, which is the original bug. Making that inherited flag authoritative inside view bodies (the previous commits) also made it skip every OTHER query analyzed with copies of the local plan context inside a view: the predicate of `mergeTreeAnalyzeIndexes`, the hidden query of `obfuscate`, and any further site that analyzes a query of its own at read time. Those were resolved on master. Carry "already resolved" for the printed query in `SelectQueryOptions` instead. It reaches only the `QueryAnalyzer` of that analysis and is not inherited by context copies. The local shard plan and the `Merge` child set it. The inherited context flag keeps master's semantics (ignored in view bodies), so the view-body reset in `setIsViewInnerQuery` is no longer needed. Also reset the context flag for the predicate of `mergeTreeAnalyzeIndexes`, which was skipped outside a view on master as well. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The distributed plan job sets serialize_query_plan = 1 in the default profile, where two cases test something other than what they are for: - The row policy case: a remote server that executes a shipped plan does not apply its own row policies at all (ClickHouse#112891), so it returns every row whatever the policy says. - The Buffer-in-a-view case: the shard query of the Distributed destination is then planned on the initiator by `createLocalPlan`, inside the view body, where its context flag is ignored. That is the site ClickHouse#124870 fixes, not the Buffer marker this case pins. Both lines still fail on master with the pin. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-local-shard-in-view Master (ClickHouse#126075) added the same `SelectQueryOptions::positional_arguments_already_resolved` plumbing through `addQueryTreePasses`, `QueryAnalysisPass` and `QueryAnalyzer`. Took master's version of it, dropped the duplicate member that the auto-merge added to `SelectQueryOptions`, and dropped this branch's now-redundant assignment in `ReadFromMerge::createPlanForTable`, which master already sets via `positionalArgumentsAlreadyResolved`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵️ @groeneai Two non-blocking suggestions:
|
Measured with this head minus all 7 So the flag can go, together with |
CI finish ledger - 7a7a3c7Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261018-083006 |
f4f941b
|
The follow-up that removes |
The context flag told the analyzer that the query was printed from a resolved query tree, so its integer constants are not positions. Being context state, it was inherited by every context copy, so every fresh query analyzed from a local-plan context had to reset it (`Context::withUnresolvedPositionalArguments` and the manual resets), or it silently skipped positional arguments. Since ClickHouse#126075 and ClickHouse#124870 the same fact is carried per analysis by `SelectQueryOptions::positional_arguments_already_resolved`, and the flag is dead: - `createLocalPlan` sets the option for the printed local shard query, which was the only analysis the flag was meant for. - `createLocalPlanForParallelReplicas` and `createRemotePlanForParallelReplicas` hand the interpreter an already resolved query tree, which `QueryAnalyzer` does not resolve again, and disable parallel replicas on those contexts, so the automatic parallel replicas builder never re-analyzes a printed AST there. - The other queries printed from a resolved tree (`Merge` child, `Buffer`, `IStorageCluster`, `ReadFromRemote` `GLOBAL IN` header, a received secondary query and its `INSERT SELECT`) carry the option since ClickHouse#126075. - Everything else that inherited the flag is a fresh query, where skipping is wrong: table function arguments, row policies, `executable` inputs and the `mergeTreeAnalyzeIndexes` predicate (the resets removed here), and the analyses that inherited the flag without a reset (the inner query of a view pushed down to `Distributed`, `loop`, the generated `TimeSeries` and `prometheusQuery` queries). Inside a view the flag was already ignored, so outside a view the behaviour now equals the in-view one. The query tree constructor of `InterpreterSelectQueryAnalyzer` builds the plan for automatic parallel replicas by re-analyzing `tree->toAST()` with the caller's options, which never carry the option. A recursive CTE member executed by `RecursiveCTESource` goes through it, so with `automatic_parallel_replicas_mode` enabled `WITH RECURSIVE r AS (SELECT 5 AS c, k FROM t ORDER BY ALL ...)` failed with `Positional argument number 5 is out of bounds`. That lambda now passes the option, since the AST it analyzes is always printed from the resolved tree. `Context::is_view_inner_query` stays, it has other users (view source replacement, scalar subqueries, `extractTableReferencesOutsideViews`); only the comments that justified it by positional arguments are updated. Tests: the bot's `Buffer` over `Distributed` case and the recursive CTE case are added to `05340_positional_arguments_view_over_remote`, and the `serialize_query_plan = 0` pin in `05401` is dropped. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #94359
Related: #126075
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results (unsorted rows, duplicate
DISTINCTrows) andPositional argument number N is out of boundserrors forORDER BY ALLqueries whose projection contains an integer constant, when they read fromremoteorDistributedinside a view.Description
On 26.8.18.2,
SELECT * FROM view(SELECT 3, k, src FROM remote('127.0.0.{1,2}', currentDatabase(), t) ORDER BY ALL DESC)returns rows not sorted byk, the same query withDISTINCTreturns duplicates, andSELECT k FROM view(...)fails withPositional argument number 3 is out of bounds. The AST fuzzer hit it asLogical error: 'Equal values are not contiguous within the range assumed to be sorted'inDistinctSortedStreamTransform(found on #124468, not caused by it): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124468&sha=08d19c7f33b3bf3f0b8ed897b52e40710d25e13e&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29ORDER BY ALLexpands to the projection after positional arguments are replaced, so the constant reaches the shard query as a bareORDER BY 3.createLocalPlanmarks the local replica's context as already resolved, butreplaceNodesWithPositionalArgumentsignores that flag in a view-inner context, which the copied context inherits inside a view (since #94359). The local replica sorted by the third column, the remote replicas by the constant.Change: #126075 added
SelectQueryOptions::positional_arguments_already_resolvedand sets it for theMergechild,Buffer,*Clusterand theGLOBAL INfilter. This PR sets it increateLocalPlan: unlike the context flag, it is honoured inside a view. Outside a view, the inherited context flag also skipped positional arguments in queries that are not printed from the resolved tree:executableinput queries, row policies,additional_table_filters, a table function argument in a subquery withSETTINGSand the predicate ofmergeTreeAnalyzeIndexes. These reset it.Validation: on master, the test's cases for these shapes fail and pass with this PR (the view body,
obfuscateandMergecases are guards); 50 randomized runs pass, also withserialize_query_plan = 1. The CI-shaped query aborts a debug master build.executableinputs (no user scripts in stateless tests) were checked locally.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/124870]
Version info
26.11.1.227-master(included in26.11and later)