Skip to content

Fix wrong results of ORDER BY ALL with an integer constant over remote inside a view and over Merge - #124870

Merged
PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-positional-args-local-shard-in-view
Oct 19, 2026
Merged

PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-positional-args-local-shard-in-view

Conversation

@groeneai

@groeneai groeneai commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #94359
Related: #126075

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 wrong results (unsorted rows, duplicate DISTINCT rows) and Positional argument number N is out of bounds errors for ORDER BY ALL queries whose projection contains an integer constant, when they read from remote or Distributed inside 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 by k, the same query with DISTINCT returns duplicates, and SELECT k FROM view(...) fails with Positional argument number 3 is out of bounds. The AST fuzzer hit it as Logical error: 'Equal values are not contiguous within the range assumed to be sorted' in DistinctSortedStreamTransform (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%29

ORDER BY ALL expands to the projection after positional arguments are replaced, so the constant reaches the shard query as a bare ORDER BY 3. createLocalPlan marks the local replica's context as already resolved, but replaceNodesWithPositionalArguments ignores 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_resolved and sets it for the Merge child, Buffer, *Cluster and the GLOBAL IN filter. This PR sets it in createLocalPlan: 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: executable input queries, row policies, additional_table_filters, a table function argument in a subquery with SETTINGS and the predicate of mergeTreeAnalyzeIndexes. These reset it.

Validation: on master, the test's cases for these shapes fail and pass with this PR (the view body, obfuscate and Merge cases are guards); 50 randomized runs pass, also with serialize_query_plan = 1. The CI-shaped query aborts a debug master build. executable inputs (no user scripts in stateless tests) were checked locally.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.227-master (included in 26.11 and later)

groeneai and others added 2 commits October 9, 2026 07:55
…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 9, 2026
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
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).

# Sev Finding Verdict Evidence / action
1 ⚠️ The inlined-view reset in StorageView::getViewSubqueryContext was not exercised: analyzer_inline_views defaults to 0 AGREE, fixed inlined view body case added; removing only that reset turns it red (NOT_AN_AGGREGATE)
2 💡 Context.h comment said the flag does not propagate through getSQLSecurityOverriddenContext AGREE, fixed Context::createCopy copies it for ordinary and INVOKER views; comment rewritten

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

Session id: cron:clickhouse-review-slot-9:20261009-090700

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05340_positional_arguments_view_over_remote fails on master every run (wrong order, DISTINCT duplicates, Positional argument number N is out of bounds, Merge rows of default values); the CI-shaped DISTINCT query over a 3-part ReplacingMergeTree aborts a debug master server with the CI logical error.
b Root cause explained? ORDER BY ALL puts a bare integer constant into the shard query; createLocalPlan marks the local replica's context resolved, but replaceNodesWithPositionalArguments ignored the flag in a view-inner context inherited from the surrounding view, so the local replica sorted by another column. A Merge child re-analyzed from its AST never set the flag.
c Fix matches root cause? Yes. The resolved flag is authoritative where it is consumed, view-context makers reset it so view bodies are still resolved, and the Merge child sets it. Nothing at the assertion site.
d Test intent preserved / new tests added? New SQL test: order, pruned projection, DISTINCT, out-of-range constant, two view-body guards (expanded, and inlined with analyzer_inline_views = 1), Merge (two symptoms).
e Both directions demonstrated? Yes, same rig and Build-ID-checked binaries: all cases except the guards differ on master and match on the fix. Mutations: without both view-context resets the expanded guard and 03802/04105 fail with NOT_AN_AGGREGATE; without only the getViewSubqueryContext reset the inlined guard fails the same way.
f Fix is general across code paths? createLocalPlan (remote, Distributed, stored views and view()), ReadFromMerge child re-analysis, both view-context makers; parallel replicas local/remote plans measured unaffected (built from the analyzed tree).
g Fix generalizes across inputs (params/datatypes/wrappers)? Constants inside and outside the projection range, pruned and full projections, DISTINCT; GROUP BY ALL and LIMIT BY ALL measured unaffected; 50 randomized runs, also with serialize_query_plan = 1.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; only previously wrong results and rejected queries change.
i Invariants and contracts preserved? A query printed from a resolved query tree is never resolved positionally again, and a view body is resolved where it is expanded. The flag is set only on fresh context copies (local plan, per-child Merge context, view contexts).

Session id: cron:clickhouse-impl-slot-4:20261009-084400

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7a7a3c7]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Cannot list the mutations left unfinished by the stress phase FAIL cidb IGNORED
Cannot count the mutations left unfinished by the stress phase FAIL cidb IGNORED
Cannot run the mutation entries left behind by the killed mutations (see undrained_mutation_errors.txt) FAIL cidb IGNORED
Cannot submit the mutation that has to survive the upgrade FAIL cidb IGNORED
Segmentation fault (STID: 5726-4458) FAIL cidb IGNORED

AI Review

Summary

The 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 7a7a3c74e064958ba61d4be6100b1d39512c0100: no new actionable findings; earlier findings are addressed. The added regression test matched its reference output, and additional checks passed for Executable inputs, Buffer, serialized plans, table filters, and nested views.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Oct 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7a7a3c74e with master 54c2b7d7b (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 76cb67e41; 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.

Object file sizes

96 object files changed (+21.36 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageMergeTreeAnalyzeIndexes.cpp.o 562.50 KiB 582.37 KiB +19.86 KiB (+3.53%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1314 translation units recompiled, 8555 s compile time in total, 1313 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.3 s

Job report

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 812012d

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 (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05316_secret_arguments_declared_by_engines test regression from merged #123364, not from this PR: under DatabaseReplicated the CREATE DICTIONARY row is counted twice in system.query_log (0 2 instead of 0 1, the password stays hidden). 21/21 reruns pass; 38 PRs show it in this lane since 2026-10-09 09:47Z #124928 (external, open)
Stateless tests (arm_asan_ubsan, azure, sequential) infra: the job was killed by its 9000 s timeout at test 1155 of 1180, so no per-test result was uploaded (the job is allow_failure) #123849 (mine, open)
Mergeable Check, PR praktika rollups of the DBReplicated row (Failed: Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2)) #124928 (external, open)

The new test 05340_positional_arguments_view_over_remote passed every flaky check (amd_asan_ubsan, amd_debug, amd_msan, amd_tsan, amd_binary), and both Bugfix validation (functional tests) jobs passed.

Session id: cron:our-pr-ci-monitor:20261009-143012

Comment thread src/Storages/StorageView.cpp Resolved
@PedroTadim PedroTadim self-assigned this Oct 15, 2026
…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]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
… 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]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
…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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 15, 2026
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]>
@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai

Two non-blocking suggestions:

  1. Please update the description. Resolve positional arguments in queries a remote server analyzes itself #126075 is merged, and it already added SelectQueryOptions::positional_arguments_already_resolved and set it for the Merge child, StorageBuffer, ReadFromRemote and IStorageCluster. This PR's own part is the local shard plan (createLocalPlan now sets the option, which, unlike the context flag, is honoured inside a view) and the resets for queries not printed from the resolved tree. A Related: link to Resolve positional arguments in queries a remote server analyzes itself #126075 would help.

  2. Follow-up idea: the context flag is inherited by every context copy, so any future code that analyzes a fresh query from a local-plan context outside a view has to remember Context::withUnresolvedPositionalArguments, or it silently skips positional arguments. Now that every query printed from a resolved tree sets the option itself (createLocalPlan here, the rest in Resolve positional arguments in queries a remote server analyzes itself #126075), and ParallelReplicasLocalPlan hands the interpreter an already-resolved query tree, is setPositionalArgumentsAlreadyResolved(true) still needed anywhere? If not, dropping it would remove these resets and the risk of missing one in the future.

@groeneai

Copy link
Copy Markdown
Collaborator Author
  1. Done: the description now covers only this PR's part and links Resolve positional arguments in queries a remote server analyzes itself #126075.

  2. No, nothing needs it any more. Its only consumer is replaceNodesWithPositionalArguments, outside a view. The createLocalPlan setter is covered by the option now, and the 6 setters in ParallelReplicasLocalPlan.cpp are on an already analyzed query tree, which the interpreter does not analyze again. Inside a view the flag is ignored already, so the in-view cases of 05340 and 05401 exercise those sites without it.

Measured with this head minus all 7 setPositionalArgumentsAlreadyResolved(true) calls: 05340 and 05401 pass, also with serialize_query_plan = 1; 432 positional, distributed, parallel-replicas, view and row-policy tests (146 of them also with serialize_query_plan = 1) give the same results as this head, apart from load timeouts that pass on re-run; 12 parallel-replicas queries with positional ORDER BY/GROUP BY/LIMIT BY, ORDER BY ALL with a constant, subqueries, JOIN, view, Merge and Distributed return the same rows as without parallel replicas, with the local plan and with serialize_query_plan = 1.

So the flag can go, together with withUnresolvedPositionalArguments, its call sites and the resets in mergeTreeAnalyzeIndexes and ProjectionsDescription. I'll send that as a follow-up PR once this one is merged, with the Buffer over Distributed case from the bot thread and without the serialize_query_plan = 0 pin in 05401 (both pass on this head), so this PR stays as you approved it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7a7a3c7

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
Upgrade check (amd_release) / Segmentation fault (STID: 5726-4458) crash, not from this PR (it does not touch joins or temporary data): segfault in the TemporaryBlockStreamHolder constructor under GraceHashJoin::addBuckets while a JoinStep is built; the same STID is in the Upgrade check of 14 other unrelated PRs since 2026-10-16 17:35Z #126204 (mine, open)
Upgrade check (amd_release) / the 4 Cannot list/count/submit/run ... mutation rows fallout of the crash above: the server was down (Connection refused on port 9000); all 15 Upgrade check runs with this segfault in the last 7 days carry exactly these 4 rows #126204 (the owner of the row above)
Mergeable Check, PR praktika rollups of the rows above #126204 (the owner of the rows above)

Session id: cron:our-pr-ci-monitor:20261018-083006

@PedroTadim
PedroTadim added this pull request to the merge queue Oct 19, 2026
Merged via the queue into ClickHouse:master with commit f4f941b Oct 19, 2026
177 of 179 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

The follow-up that removes Context::positional_arguments_already_resolved and its resets is #126813. It also adds the Buffer over Distributed case to 05340 and unpins serialize_query_plan in 05401, as promised above.

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Oct 20, 2026
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]>
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-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants