Skip to content

Bind parameterized-view parameters only from top-level equals args - #112194

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-parameterized-view-non-equals-argument
Jul 28, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-parameterized-view-non-equals-argument

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #111790

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):

Fixes wrong results when a parameterized view is called with an argument that is not a parameter = value assignment. With enable_analyzer = 0, and in EXPLAIN SYNTAX at default settings, calls such as pv(concat(name, '!')), pv(name, 'a'), pv(name != 'a') and pv(tuple(name = 'a')) silently bound a view parameter to an unrelated expression instead of reporting UNKNOWN_QUERY_PARAMETER as the analyzer does. Such calls are now rejected identically on both execution paths.

Description

analyzeFunctionParamValues in src/Parsers/FunctionParameterValuesVisitor.cpp is the legacy-AST parameterized-view parameter collector. It is reached from Context::executeTableFunction (execution at enable_analyzer = 0) and from InterpreterExplainQuery's ExpandParameterizedViewsMatcher (EXPLAIN SYNTAX, at default settings). The query-tree collector in QueryAnalyzer::resolveTableFunction accepts only genuine equals assignments among the top-level arguments of the view call, so the two paths diverged: on the legacy paths a bogus argument silently satisfied or overrode a parameter and the view returned wrong rows, while the analyzer rejected the same query with UNKNOWN_QUERY_PARAMETER.

Two independent mechanisms produced the divergence.

The outer guard read if (parameter_function.name != "equals" && parameter_function.children.size() != 1) return false;. It rejects only when the name is not equals and the child count is not 1, and every ordinary parsed function has exactly one child (its arguments list), so the second conjunct was always false and the name check never fired. Two consequences followed: a non-equals binary function such as concat(name, '!') was read as name = '!'; and the view call itself was not rejected either, so for a positional call pv(name, 'a') the view's own argument list was read as if it were an equals argument list, binding name = 'a'.

Separately, the visitor recursed into every child of a rejected node, so a nested well-formed assignment was still collected: pv(tuple(name = 'a')), pv((name = 'a') AND 1) and pv(if(1, name = 'a', name = 'b')) all bound a parameter. Correcting the guard alone does not close this.

The fix replaces the free recursion and the broken guard with an explicit walk that mirrors the analyzer: iterate the top-level arguments of the view call, and accept an argument only when it is an ASTFunction named equals whose arguments list holds exactly two children, the first an ASTIdentifier and the second a constant expression. Any other argument shape binds nothing, which leaves the parameter unset and gives it exactly the treatment the analyzer path already gives it. The value-serialization branch is unchanged.

The shape check deliberately keys on ASTFunction::arguments rather than on children[0] / children.size(). A parametric spelling equals(7)(name, 'a') stores its parameters as a second child (ASTFunction.h, addParametersToAggregateFunction) and is accepted on both paths today, so a child-count test would make the legacy path start rejecting it: a fresh divergence in the opposite direction. Three positive controls in the new test pin that shape, two of which run through this collector, and the mutation matrix below confirms those two are the only rows a child-count implementation breaks (the third is served by the query-tree collector and is insensitive to any change here).

Behavior change. Argument spellings that are not assignments now leave the parameter unset on the legacy path and in EXPLAIN SYNTAX, where they were previously accepted, so the query raises UNKNOWN_QUERY_PARAMETER (or, for a Nullable parameter, substitutes NULL, exactly as on the analyzer path). That is the point of the change: it aligns those paths with the default-settings analyzer behavior, and the documented pv(param = value) spelling has always worked on both. No setting default moves, so no SettingsChangesHistory.cpp entry is needed (that file tracks Settings only, and this PR touches nothing under src/Core/). No serialization, format or protocol change.

Out of scope, pinned as unchanged. WITH 'a' AS s SELECT * FROM pv(name = s) also diverges (UNKNOWN_QUERY_PARAMETER at enable_analyzer = 0, correct rows at = 1), but for an unrelated reason: the legacy path cannot evaluate a WITH alias to a constant. That is constant-expression evaluation, not argument-shape validation, and the new test asserts both of its current verdicts so the behavior is not silently changed here.

Verification. Debug build, Build ID 53b7b30946688c2b1425ff81ba7fbd7098dc8319; base measurements on the pristine master snapshot, Build ID 9ebd11fe9bc8d54774fc02e726da1a5923b741c0 (byte-identical FunctionParameterValuesVisitor.cpp, QueryAnalyzer.cpp, Context.cpp, InterpreterExplainQuery.cpp and StorageView.cpp to origin/master). The head commit adds a comment-only edit on top of the measured commit and so builds to a4bfa6f1ed8481848c71881abc184e3821981243; the comment-stripped source hash is identical for the two, and the new test was re-run on the rebuilt binary.

Both directions, driven statement by statement against a server of each binary: the new test's 68 statements produce 13 failures on pristine master and 0 with the fix. The 13 are the four non-equals binary/unary shapes, the uppercase EQUALS spelling, the two positional shapes, the three nested-assignment shapes and the three EXPLAIN SYNTAX shapes.

Mutation matrix (predictions written before building each mutant; all three matched exactly):

mutant predicted measured
restore the free recursion only the 3 nested-assignment rows regress exactly those 3
drop the equals-name check the 4 non-equals shapes plus their EXPLAIN SYNTAX row regress exactly those 5
key on children[0]/children.size() (the naive guard flip) only the 2 parametric-equals rows regress exactly those 2

The matrix shows the two halves of the fix are each load-bearing, and for different rows: the equals-name check closes the non-equals functions, while the top-level-only walk closes the positional and nested shapes. Restoring the source after the matrix rebuilt to the bit-identical Build ID.

50 randomized runs of the new test: 50/50 pass.

Existing-test blast radius. First, a static sweep of all of tests/, functional and integration: every view created with a {parameter:Type} placeholder is located, then every top-level argument of every call of that view name that is not an identifier = ... assignment. Outside the new test itself there are exactly three such arguments tree-wide, and all three are numbers(3), numbers(10) and numbers(100) in 04105_explain_syntax_parameterized_view, where numbers is a registered table function and takes precedence over the same-named view before this collector is reached (that precedence is itself asserted by 04105). 02428_parameterized_view's SELECT * FROM test_02428_mv1(test) is a call on a MATERIALIZED view, whose reference already expects ERROR, and it was additionally checked on both binaries and still reports ERROR. In the integration suite only test_parameterized_view defines a placeholder view, and every call there is a name = value assignment. So no existing .reference can change.

Second, executed: the 26 pre-existing stateless tests whose sources mention parameterized/parametrized were run on both binaries and produced identical failure sets: 25 pass, and 02428_parameterized_view fails on both with a ReplicatedMergeTree async-insert timeout against a bare local server (an environment limitation, not a regression).

groeneai and others added 2 commits July 27, 2026 14:51
The legacy-AST parameter collector `analyzeFunctionParamValues` guarded with
`name != "equals" && children.size() != 1`, which only rejects when both
clauses hold. Every ordinary parsed function has exactly one child (its
`arguments` list), so the name check never fired: a non-`equals` function such
as `concat(name, '!')` was stored as if the user wrote `name = '!'`, and the
view call itself passed the guard too, so a positional `pv(name, 'a')` had the
view's own argument list read as an `equals` argument list. Independently the
visitor recursed into rejected subtrees, so a nested assignment inside
`tuple(...)`, `... AND 1` or `if(...)` was still collected.

The query-tree collector accepts only genuine `equals` assignments among the
top-level arguments of the call, so execution at `enable_analyzer = 0` and
`EXPLAIN SYNTAX` at default settings returned wrong rows where the analyzer
correctly raised UNKNOWN_QUERY_PARAMETER.

Replace the free recursion and the broken guard with a top-level-arguments-only
walk mirroring `QueryAnalyzer::resolveTableFunction`, so both paths bind the
same parameter set by construction. The shape check keys on
`ASTFunction::arguments` rather than on `children`, because a parametric
`equals(7)(name, 'a')` stores its parameters as a second child and is accepted
on both paths today; a child-count test would make the legacy path start
rejecting it, which is a fresh divergence in the opposite direction.

Argument spellings that are not assignments now raise UNKNOWN_QUERY_PARAMETER
on those paths, aligning them with the default analyzer behaviour. The
documented `pv(param = value)` spelling is unaffected.

Related: ClickHouse#111790

Co-Authored-By: Claude Opus 5 <[email protected]>
The `///` block added above `analyzeFunctionParamValues` asserted two
invariants that this branch's own test disproves.

It said the legacy-AST and analyzer paths "bind exactly the same set of
parameters". They agree on argument SHAPE, not on value ACCEPTANCE: this file
requires the value to already be an `ASTLiteral`, `ASTFunction` or
`ASTSubquery` (unchanged from master), so a bare identifier never reaches
`evaluateConstantExpression`, while the analyzer resolves the value node and
accepts anything that folds to a constant. That is exactly the
`WITH 'a' AS s SELECT * FROM pv(name = s)` case, whose two current verdicts
04648_parameterized_view_non_equals_argument.sql pins as divergent because the
difference is pre-existing and deliberately out of scope here.

It also said an argument of any other shape "makes `ReplaceQueryParameterVisitor`
report `UNKNOWN_QUERY_PARAMETER`". Not for a `Nullable` parameter:
`resolveParameterValueAsField` throws only when the type is not nullable and
otherwise substitutes `NULL`, as `03454_parameterized_views_null.sql` exercises.

The comment now states shape parity, names both consumer outcomes accurately,
and records the value-acceptance difference as pre-existing and pinned.

The same two claims appear in the previous commit's message, which is left as
written since this branch does not rewrite history: "bind the same parameter set
by construction" there should be read as the argument SHAPES, and "raise
UNKNOWN_QUERY_PARAMETER" as leaving the parameter unset, which a `Nullable`
parameter turns into `NULL` rather than an error.

Comment text only. The comment-stripped source is byte-identical to the previous
commit (sha256 7a2bf9e80835adac, versus fb9b2c4f2d302541 on master), no test
assertion changes, and the test still passes.
@groeneai

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

Two review rounds over this change, each an independent cold read followed by a second-model
pass, plus one implementation fix round between them. 5 findings, 4 agreed and fixed, 0
disagreed. The second-model pass on the final head returned no findings.

# Finding Severity Verdict
❌ 1 The collector's new doc comment claimed the legacy-AST and analyzer paths "bind exactly the same set of parameters" and that an unbound parameter always yields UNKNOWN_QUERY_PARAMETER. Both are wrong: the two paths agree on argument SHAPE but not on value ACCEPTANCE (the WITH 'a' AS s case this PR's own test pins as divergent), and resolveParameterValueAsField substitutes NULL rather than throwing for a Nullable parameter. major AGREE, fixed. The comment now states shape parity only, names the value-acceptance difference as pre-existing and out of scope, and records the Nullable exception.
❌ 2 The description's blast-radius sweep printed an exact pair of counts that is not reproducible from the predicate the sentence describes: re-implementing that predicate gives 40 / 37, a looser reading gives 37 / 31, against the stated 38 / 35. major AGREE, fixed. The paragraph now states the predicate-invariant result (exactly three such arguments exist outside the new test, each named) and drops the fragile pair. The substance was unaffected; only the wording was.
❌ 3 The description carried the same two false claims as finding 1 (UNKNOWN_QUERY_PARAMETER unconditionally; a stale Build ID and a mis-stated count of parametric-equals controls). major AGREE, fixed. Nullable substitution is now stated, both Build IDs are recorded with their comment-only relationship, and the control count is corrected to three, two of which reach this collector.
💡 4 The header's pre-existing one-line doc comment for analyzeFunctionParamValues is ungrammatical and now less precise than the .cpp block. nit AGREE, deliberately not changed: byte-identical on master and unrelated to this root cause; touching it would widen a one-concern diff.
💡 5 A parenthesized assignment pv((name = 'a')) is not in the pinned matrix. nit AGREE, no coverage owed. Traced: round brackets around a single element only set a flag on the node (no extra child), so the node is still the equals call and its verdict is unchanged by this PR.

Checks run beyond the findings above: the two consumers of the collector were enumerated
independently and match the intended scope; the new walk was compared statement by statement
against QueryAnalyzer::resolveTableFunction; the arguments-not-children decision was
re-derived from the parser (a parametric equals carries a second child, so the one-character
guard flip suggested by the original report would have created a divergence in the opposite
direction); test liveness was traced to the 13 statements that fail without the fix rather than
assumed; the blast-radius sweep was re-run tree-wide with an independent predicate over both
the functional and integration suites; and the head's comment-only commit was verified to leave
the executable content byte-identical to the reviewed commit, so the recorded 50/50 run and
mutation matrix still apply to it.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT * FROM pv(concat(name, '!')) SETTINGS enable_analyzer = 0 returns the wrong row ! 9 on every run, and EXPLAIN SYNTAX SELECT * FROM pv(concat(name, '!')) renders WHERE equals(name, '!') at default settings. No randomization, no timing: 13 of the new test's 68 statements fail on a pristine master debug binary (Build ID 9ebd11fe9bc8d54774fc02e726da1a5923b741c0) on every run.
b Root cause explained? Yes. analyzeFunctionParamValues guarded with name != "equals" && children.size() != 1, which only rejects when BOTH hold; every ordinary parsed function has exactly one child (its arguments list), so the name test never fired. Consequences: a non-equals function (concat) was read as name = <2nd arg>, and the view call itself passed the guard so a positional pv(name, 'a') had the view's own argument list read as an equals argument list. Independently, the visitor recursed into rejected subtrees, so a nested equals (tuple(name = 'a'), (name = 'a') AND 1, if(1, name = 'a', name = 'b')) was still collected. The analyzer collector (QueryAnalyzer::resolveTableFunction) inspects only top-level arguments that are equals, hence the divergence.
c Fix matches root cause? Yes. The free recursion and the broken guard are replaced by a top-level-arguments-only walk that mirrors the analyzer's own argument-shape test, so the two paths accept the same argument SHAPES by construction. Value ACCEPTANCE is deliberately left as it is: the legacy path requires the value to already be a literal, function call or subquery, while the analyzer resolves the value node and accepts anything that folds to a constant (e.g. a WITH alias) — a pre-existing difference, out of scope here and pinned as unchanged in the test. No symptom guard, no widened bound, no tag.
d Test intent preserved / new tests added? New test 04648_parameterized_view_non_equals_argument.sql (68 statements). No existing test is modified and no existing .reference changes. The test asserts the SAME verdict on both paths per shape (so it pins convergence, not just the legacy outcome), and pins 14 positive controls including the parametric equals(7)(name, 'a') spelling and the out-of-scope WITH-alias rows.
e Both directions demonstrated? Yes. Driven statement by statement against a server of each binary: 13 failures on pristine master, 0 with the fix (Build ID 53b7b30946688c2b1425ff81ba7fbd7098dc8319; the final head adds a comment-only edit and so builds to a4bfa6f1ed8481848c71881abc184e3821981243, with the comment-stripped source hash identical between the two, and the test re-run [ OK ] on it). 50/50 randomized runs pass. Three mutants, each with its prediction written before building, matched exactly: restoring the recursion regresses only the 3 nested rows; dropping the equals-name check regresses only the 4 non-equals shapes plus their EXPLAIN SYNTAX row; keying on children[0]/children.size() regresses only the 2 parametric-equals rows. Restoring the source rebuilt to the bit-identical Build ID.
f Fix is general across code paths? Yes. Both legacy surfaces share one collector (git grep analyzeFunctionParamValues gives exactly Context.cpp:3006 and InterpreterExplainQuery.cpp:201), so one change covers execution at enable_analyzer = 0 and EXPLAIN SYNTAX at default settings. The analyzer collector is the reference behavior and is deliberately untouched; Context::buildParameterizedViewStorage and StorageView::replaceQueryParametersIfParameterizedView consume an already-built map and need no change.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, and the argument-shape matrix is asserted in the test: plain equals, function-call equals(...), parametric equals(7)(...), equals() with an empty argument list, multiple assignments, a repeated parameter (last wins), literal / subquery / CAST right-hand sides, uppercase EQUALS, positional 1- and 2-argument calls, mixed assignment + non-assignment, AND / tuple / if nesting, a literal on the left ('a' = name), a qualified identifier on the left, an unknown parameter name, and an empty call. Each row's accept/reject verdict is pinned on both paths.
h Backward compatible? This is a deliberate, user-visible tightening of the legacy path onto the default analyzer behavior, stated in the changelog entry: argument spellings that are not assignments now leave the parameter unset where they were silently accepted, so ReplaceQueryParameterVisitor reports UNKNOWN_QUERY_PARAMETER (or, for a Nullable parameter, substitutes NULL — resolveParameterValueAsField), exactly as on the analyzer path today. The migration is the documented pv(param = value) spelling that already worked on both paths. No setting default moves (git diff --name-only <merge-base> -- src/Core/ is empty), so no SettingsChangesHistory.cpp entry is needed. No serialization, format or protocol change; nothing persisted.
i Invariants and contracts preserved? Yes. analyzeFunctionParamValues keeps its signature and its contract of returning the collected NameToNameMap; the invariant it now upholds is that a parameter is bound only by a top-level identifier = <constant expression> argument of the view call, identically on both paths. Every early return leaves the map in a consistent state (an unbound parameter is handled by the existing ReplaceQueryParameterVisitor path — UNKNOWN_QUERY_PARAMETER, or NULL for a Nullable parameter — so no new error path is invented). The shape check keys on ASTFunction::arguments rather than children, so a parametric equals keeps its current verdict instead of being rejected by child-count arithmetic. Pure AST-level visitor: no locks, no storage, no replication, no persisted state.

Session id: cron:clickhouse-impl-slot-43:20260727-185900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @pufit @george-larionov could you review this? It makes the legacy-AST parameterized-view parameter collector accept only top-level identifier = value arguments, mirroring QueryAnalyzer::resolveTableFunction: today a broken guard lets a non-equals function (pv(concat(name, '!'))) or a positional call (pv(name, 'a')) silently bind a parameter, and unbounded recursion collects a nested assignment (pv(tuple(name = 'a'))), so enable_analyzer = 0 and EXPLAIN SYNTAX return wrong rows where the analyzer raises UNKNOWN_QUERY_PARAMETER.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 28, 2026
@PedroTadim PedroTadim self-assigned this Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a21581c]

Summary: ✅


AI Review

Summary

This PR narrows the legacy parameterized-view argument collector to top-level equals assignments, so the old execution path and the EXPLAIN SYNTAX AST rewrite stop binding parameters from unrelated function arguments or nested predicates. I did not find an outstanding correctness, compatibility, or evidence gap in the current head: the new stateless test covers the broken non-equals, positional, nested-assignment, and parametric-equals shapes, and the PR’s CI report is all green.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 25/27 (92.59%) · Uncovered code

Full report · Diff report

@PedroTadim
PedroTadim enabled auto-merge July 28, 2026 12:13
@PedroTadim
PedroTadim added this pull request to the merge queue Jul 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a21581c

CI has fully finished on this head: 174 check-runs, 0 queued, 0 in progress, Finish Workflow
success at 13:51:51Z. Zero failing checks (156 success, 18 skipped), so there is nothing to
assign an owner to. CIDB reports 0 FAIL/ERROR rows for this commit.

Check / test Reason Owner / fixing PR
(none) - no failures on this head

Session id: cron:our-pr-ci-monitor:20260728-140000

Merged via the queue into ClickHouse:master with commit 762bbac Jul 28, 2026
178 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 28, 2026
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 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.

3 participants