Skip to content

Remove Context::positional_arguments_already_resolved - #126813

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:drop-context-positional-arguments-resolved-flag-v2
Oct 20, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:drop-context-positional-arguments-resolved-flag-v2

Conversation

@groeneai

@groeneai groeneai commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #124870
Related: #126075

Changelog category (leave one):

  • Improvement

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

With the experimental automatic_parallel_replicas_mode, a recursive CTE member that orders or groups by an integer constant of its projection (for example SELECT 5 AS c, k FROM t ORDER BY ALL) no longer fails with Positional argument number 5 is out of bounds.

Description

Follow-up to #124870, as asked in #124870 (comment).

Context::positional_arguments_already_resolved told the analyzer that a query is printed from a resolved query tree. Being context state, every context copy inherits it, so each fresh query analyzed from a local plan context had to reset it (#124870 added five resets), or it silently skipped positional arguments.

The same fact is now carried per analysis by SelectQueryOptions::positional_arguments_already_resolved (#126075, and createLocalPlan in #124870), and the flag has no remaining use: the parallel replicas local and remote plans pass an already resolved query tree, which is not resolved again. This PR removes the flag, its setters, Context::withUnresolvedPositionalArguments and the resets. Every other analysis that inherited the flag reads a query that is not printed from a resolved tree, so it now resolves positional arguments, as it already did inside a view.

Checking every analysis that re-reads a printed AST found one that never had the option: automatic parallel replicas re-analyzes tree->toAST() of a query tree to build its candidate plan. On master, with automatic_parallel_replicas_mode = 1, WITH RECURSIVE r AS ((SELECT 5 AS c, k FROM t ORDER BY ALL LIMIT 1) UNION ALL (SELECT c, k + 1 FROM r WHERE k < 2)) SELECT * FROM r fails with Positional argument number 5 is out of bounds ... While executing RecursiveCTESource. That re-analysis now passes the option.

Validation: 05340 gains the Buffer over Distributed case from the review of #124870 and the recursive CTE case (fails before this PR, passes with it); 05401 no longer pins serialize_query_plan = 0. 50 randomized runs pass, 20 more with serialize_query_plan = 1. 570 related tests give the same results as before the change, 157 of them also with serialize_query_plan = 1.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 2 commits October 19, 2026 19:43
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]>
…allel replicas candidate plan

The rows alone are also what the single-node plan returns, so the case now asserts through
`query_log` that `AutomaticParallelReplicasProbePlansBuilt` fired, with
`automatic_parallel_replicas_remember_boundary = 0` so every run builds the candidate plan.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; one finding raised in 2 rounds, 0 findings on the final head) plus my own cold review (nits only).

# Sev Finding Verdict Evidence / action
1 ⚠️ The recursive CTE case asserts rows only, which the single-node plan also returns, so it would stay green if the automatic parallel replicas candidate builder were bypassed AGREE, fixed The case now pins automatic_parallel_replicas_remember_boundary = 0 and checks ProfileEvents['AutomaticParallelReplicasProbePlansBuilt'] > 0 in system.query_log; with the builder skipped (huge automatic_parallel_replicas_min_bytes_per_replica) that check returns 0
2 💡 obfuscate keeps marking its inner context as a view body, although positional arguments no longer need it AGREE, kept Its remaining effects are the view-body semantics (materialized view source, table references); removing it would be a separate behaviour change
3 💡 The Buffer over Distributed case and the 05401 change already pass on master since #124870 AGREE, kept Coverage for the removal; only the recursive CTE case is claimed to fail before this PR
4 💡 The query_log check does not filter is_initial_query AGREE, kept Same filter as 05218_autopr_eligibility_gate; 41 local runs gave exactly one initial-query row each

Severity: ❌ blocker / ⚠️ major / 💡 nit.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes for the one user-visible part: with automatic_parallel_replicas_mode = 1, WITH RECURSIVE r AS ((SELECT 5 AS c, k FROM t ORDER BY ALL LIMIT 1) UNION ALL (SELECT c, k + 1 FROM r WHERE k < 2)) SELECT * FROM r fails every run on master with Positional argument number 5 is out of bounds. The flag removal has no failure of its own; a negative control (the createLocalPlan option removed) makes 05340 fail, so the test sees a missing carrier.
b Root cause explained? The context flag is inherited by every context copy, so fresh queries had to reset it. Its only remaining setters were createLocalPlan (which also sets the per-analysis option) and the parallel replicas plans (resolved query tree, not resolved again). The recursive CTE failure: automatic parallel replicas re-analyzes tree->toAST(), which prints ORDER BY 5, without the option.
c Fix matches root cause? Yes. The per-analysis option is the single mechanism; the flag, its setters, withUnresolvedPositionalArguments and the resets are deleted, and the one re-analysis of a printed AST that lacked the option now passes it.
d Test intent preserved / new tests added? 05340 gains the Buffer over Distributed case and the recursive CTE case, which also checks in query_log that the automatic parallel replicas candidate plan was built (it returns 0 when the plan is skipped); 05401 drops its serialize_query_plan = 0 pin.
e Both directions demonstrated? Recursive CTE case: fails before the change, passes after. 50 randomized runs of 05340 and 05401 pass, 20 more with serialize_query_plan = 1.
f Fix is general across code paths? Every analysis that inherited the flag was checked: printed queries carry the option, fresh queries no longer need a reset. 570 related tests give the same results as before, 157 also with serialize_query_plan = 1.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked with automatic_parallel_replicas_mode 1 and 2, both UNION spellings, both serialize_query_plan values and parallel_replicas_local_plan 1/0. Data types are not involved.
h Backward compatible? (maintainer-approved exception only) Yes. The flag was never serialized (not a setting, not sent between servers, not in plans).
i Invariants and contracts preserved? An analysis skips positional arguments only when its own query is printed from a resolved tree, decided per analysis. Context::is_view_inner_query stays for its other users.

Session id: cron:clickhouse-impl-slot-4:20261017-223900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @devcrafter, could you review this and add the can be tested label so CI runs? It removes the inherited Context::positional_arguments_already_resolved flag (the per-analysis SelectQueryOptions option now carries the same fact), and passes that option to the automatic parallel replicas candidate plan, whose re-analysis of tree->toAST() failed on a recursive CTE member with ORDER BY ALL over a constant.

@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dcafbf5]

Summary: ✅


AI Review

Summary

Removes the inherited Context::positional_arguments_already_resolved flag in favor of the existing per-analysis option, and sets that option when automatic parallel replicas reanalyze a resolved query tree. No actionable findings. The current Fast test report passes 05340_positional_arguments_view_over_remote, including the added regression cases.

Missing context / blind spots
  • ⚠️ 05401_positional_arguments_in_queries_analyzed_by_remote_replica is skipped in Fast test, and the broader stateless CI results are not available yet. The author reports passing local runs; full stateless CI would provide independent confirmation. No local build was available for additional execution.
Final Verdict

Status: ✅ Approve. No changes requested.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Oct 19, 2026
@PedroTadim PedroTadim self-assigned this Oct 20, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Oct 20, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Oct 20, 2026
Merged via the queue into ClickHouse:master with commit dceb0cc Oct 20, 2026
527 of 529 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 20, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 20, 2026
…r read

A local Merge child re-analyzes its query, so an expression over a missing
column comes back with its constants folded: `id * (a + 1)` is named
`multiply(__table1.id, _CAST(1_UInt16, 'UInt16'_String))`. The fan-out looked
it up by the unfolded name, recomputed it, and then rejected the child column
it left unread, so addMissingDefaults returned 0 for every expression of the
query. The fan-out now also tries the name with the constants folded
(foldConstantCast, skipping IN, whose set only the child's analysis builds),
and on the missing-column path accepts a child column it does not read:
every output is then a name match or a deterministic expression of the
child's columns. A Distributed child names its header from the unfolded tree,
so the unfolded name is tried first.

The query_tree_already_optimized flag lived in Context, so every context copy
inherited it, and the body of a view child, which the initiator never
optimized, ran only the resolving passes and kept `_shard_num` of its
Distributed table as a column (UNKNOWN_IDENTIFIER). It is now carried by the
read, like positional_arguments_already_resolved (ClickHouse#126075, ClickHouse#126813):
SelectQueryInfo of the Merge child, which ReadFromMerge and StorageBuffer copy
into the SelectQueryOptions of the query they re-analyze. A view body inlined
into that query (analyzer_inline_views) still skips the later passes, so
ShardNumColumnToFunctionPass runs for it. The PR no longer changes Context,
which conflicted with ClickHouse#126813.

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). pr-improvement Pull request with some product improvements 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.

3 participants