Repository navigation
Fix parameterized view with a subquery-valued Array/Tuple parameter - #111790
alexey-milovidov merged 4 commits into
Conversation
A parameterized view called with a scalar-subquery argument of a large-literal type (Array, Tuple, LowCardinality, ...) failed with UNKNOWN_QUERY_PARAMETER. evaluateScalarSubqueryIfNeeded keeps such results as a __getScalar reference instead of a literal (scalar subquery optimization), so resolveTableFunction did not collect the value as a view parameter (it only accepts a ConstantNode). Force the scalar subquery to fold to a literal while resolving a parameterized view argument via a new parameterized_view_arguments_in_resolve_process flag, mirroring table_function_arguments_in_resolve_process. The optimization is unchanged for every other scalar subquery. Closes: ClickHouse#68041 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-3:20260724-114800 |
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 6 findings across rounds; bounded: 1 full pass + 1 fix round + 1 delta recheck; final recheck clean).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-3:20260724-114800 |
|
cc @PedroTadim @yakov-olkhovskiy — could you review this? It fixes issue #68041: a parameterized view called with a subquery-valued argument of an |
|
Workflow [PR], commit [9aa89d3] Summary: ✅
AI ReviewSummaryThis PR fixes the main Findings
Final VerdictStatus: |
The first commit fixed the query-tree execution path so a subquery-valued
parameter (e.g. an Array from a scalar subquery) folds to a literal and is
matched against the view's query parameters.
EXPLAIN SYNTAX and the legacy analyzer expand parameterized views through a
separate AST path: analyzeFunctionParamValues / FunctionParameterValuesVisitor.
It only recorded literal, CAST-literal and function right-hand sides, so a
subquery value was dropped and ReplaceQueryParameterVisitor threw
UNKNOWN_QUERY_PARAMETER, even though plain execution of the same query now
succeeds.
Collect any non-literal value (function, CAST, or scalar subquery) by
evaluating it to a constant and serializing it with the value's own data type
via serializeTextEscaped, matching the escaped format ReplaceQueryParameterVisitor
deserializes (the analyzer counterpart in QueryAnalyzer does the same). This also:
- fixes CAST wrapping a subquery, which the old CAST branch dropped;
- text-escapes string values, so values with special characters (e.g. a tab in
a LowCardinality(String)) are no longer truncated;
- stops the collector from descending into a value subquery, so an inner
predicate that references the parameter name can no longer overwrite the
collected value.
Extends the regression test with EXPLAIN SYNTAX (exact substituted value),
CAST(subquery), an escaped LowCardinality(String) value, and a subquery whose
predicate references the parameter name.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Internal second-model review adjudication (click to expand)Two rounds of an independent second-model review on the AST-expansion fix; every finding verified against the code before acting.
Both new liveness assertions were confirmed to fail on a deliberately regressed build (raw serialization + descent restored) and pass on the fix. Final review round: 0 findings. |
The AST-expansion path for parameterized views (`analyzeFunctionParamValues`, used by `EXPLAIN SYNTAX` and legacy `enable_analyzer = 0` execution through `Context::executeTableFunction`) stored a top-level string literal argument as raw bytes via `convertFieldToString`, which returns the unescaped string for `Field::String`. The consumer `ReplaceQueryParameterVisitor::resolveParameterValueAsField` reads the saved value back with `deserializeTextEscaped`, so a value containing a tab, newline or backslash (e.g. `pv(nm = 'a\tb')`) stopped at the first such byte and the query threw `BAD_QUERY_PARAMETER` (only N of M bytes parsed). Route literal values through the same `evaluateConstantExpression` + `serializeTextEscaped` path already used for function- and subquery-valued arguments, matching the analyzer counterpart in `QueryAnalyzer`, which has no separate literal path. Add direct-literal regression cases (tab / newline / backslash for `String` and `LowCardinality(String)`) covering both the legacy execution path and `EXPLAIN SYNTAX`. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Scalar subquery values of an unfolded type (Array, Tuple, LowCardinality, ...)
in a parameterized view argument are now executed for real during only-analyze
resolution instead of taking the sample-block default. evaluateScalarSubqueryIfNeeded
gated real execution only on table_function_arguments_in_resolve_process, so in
only-analyze mode (getSampleBlock: CREATE TABLE ... AS SELECT / INSERT SELECT
header inference) a parameterized view argument fell into the sample-block branch
and its default value (e.g. an empty array) was folded into the ConstantNode and
substituted into the view. When the view's projected type depends on the argument
value this made header inference diverge from execution, e.g.
CREATE VIEW v AS SELECT toFixedString('x', length({p:Array(Int32)})) AS s;
CREATE TABLE t ENGINE = Memory AS
SELECT s FROM v(p = (SELECT groupArray(number) FROM numbers(3)));
threw "FixedString size must be positive" because the default [] (length 0) was
used for the header, while execution would produce FixedString(3).
Treat parameterized_view_arguments_in_resolve_process the same as
table_function_arguments_in_resolve_process when deciding only_analyze_subquery,
mirroring the existing table-function handling. Extends test
03690_parameterized_view_array_subquery_param with analyzer-only header cases
across Array / Tuple / LowCardinality.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
| /// Returns true if this function is a `parameter = value` assignment that was collected. | ||
| bool visitFunction(const ASTFunction & parameter_function) | ||
| { | ||
| if (parameter_function.name != "equals" && parameter_function.children.size() != 1) |
There was a problem hiding this comment.
This guard still lets any non-equals function through whenever it has the normal single arguments child. In the AST-based paths (EXPLAIN SYNTAX and enable_analyzer = 0 execution), a call like pv(concat(name, '!')) is then treated as if the user had supplied name = '!': concat falls through here, expression_list->children[0] is an ASTIdentifier, and we store it in parameter_values. Query-tree execution only collects real equals assignments, so the two paths still diverge and a positional/non-assignment expression can silently satisfy or override a view parameter.
This needs to reject either condition (name != "equals" or children.size() != 1), and I would add a small regression that the AST path does not extract parameters from concat(name, '!')-style arguments.
There was a problem hiding this comment.
Confirmed as a real defect, but it is pre-existing and a separate concern, so I will fix it in its own follow-up PR rather than fold it in here.
Pre-existing: the guard name != "equals" && children.size() != 1 is byte-identical at this PR's merge-base (18de9dbe, FunctionParameterValuesVisitor.cpp:43) and at the current head (9aa89d38, line 49). This PR's diff for the file only unifies the value-serialization branch and tightens the inner expression_list check; it never touches this outer guard, so pv(concat(name, '!')) behaves the same before and after this PR.
Separate concern: this PR fixes subquery-valued view arguments (#68041). The guard is a different root cause (positional / non-equals argument syntax on the legacy AST path), and correcting it changes externally-visible behavior, since pv(concat(name, '!')) is currently accepted there and would start being rejected. That deserves its own changelog entry and review, so I would rather not mix two concerns in one bugfix.
Follow-up PR will change the guard to name != "equals" || children.size() != 1 and add a regression that the AST path does not extract a parameter from concat(name, '!')-style arguments, matching query-tree behavior.
There was a problem hiding this comment.
Follow-up opened: #112194
One correction to what I wrote above: the || flip I promised is not the right fix, and on its own it would have introduced a divergence in the opposite direction. A parametric spelling equals(7)(name, 'a') keeps its parameters in a second child of the ASTFunction, so children.size() == 2, and that shape is accepted on both paths today. With || the legacy path would have started rejecting it.
The follow-up therefore keys the shape check on ASTFunction::arguments instead of on children, and it also closes a second mechanism the flip does not touch: the visitor recursed into rejected subtrees, so a nested assignment such as pv(tuple(name = 'a')) or pv((name = 'a') AND 1) was still collected. Both are replaced by a top-level-arguments-only walk mirroring QueryAnalyzer::resolveTableFunction.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 38/40 (95.00%) · Uncovered code |
The middle assertion reads the ConstantJoin "Shrinking stored blocks" log line from system.text_log, filtered by a 60-second recency window (event_time >= now() - 60). text_log.event_time is the message emission time, not the flush time, so this window races the duration of the preceding SYSTEM FLUSH LOGS. On a loaded parallel runner the flush can take tens of seconds, and the emitted line then falls out of the window, so count() returns 0 instead of 1. Measured on four failing runs, all on the parallel sanitizer jobs: the flush took 65.8s on master sha 693a303, 59.7s on PR ClickHouse#110886 sha 06b7c4b, 101.2s on PR ClickHouse#111790 and 60.9s on PR ClickHouse#111691 sha 19338ec. In each case the line's age at the assertion was at or just past the 60-second boundary (66s, 60.1s, 101s, 62s), and for the master and ClickHouse#110886 runs the server log holds the shrink line for the exact failing query id, so the shrink did happen and only the time predicate excluded it. Widen the window to 600s. This is safe because the per-test timeout is 600s, so a flush slow enough to push the emitted line past a 600s window would trip the per-test timeout first. The assertion is unchanged and never weakened: rows are scoped exactly by query_id from system.query_log filtered by log_comment and current_database = currentDatabase(), and CI assigns every test run a unique database, so the time predicate only prunes the scan. This mirrors 00177_memory_bound_merging.sh, which uses now() - 600 on the same text_log-via-query_id pattern. Reports: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=693a303c1017477fc39aaa7706af0ec078e13fbc&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29 https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110886&sha=06b7c4b127f65dbc45d7c26d867a4801c0742209&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29 Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment. TL;DRFix parameterized view with a subquery-valued Array/Tuple parameter ClickGap verified: reproduced it with the script below on ReproductionSET enable_analyzer = 1;
SET enable_scalar_subquery_optimization = 1;
CREATE TABLE pv_data (AccountId Int32) ENGINE = Memory;
INSERT INTO pv_data VALUES (1)(2)(3)(5);
CREATE TABLE pv_ids (AccountId Int32) ENGINE = Memory;
INSERT INTO pv_ids VALUES (1)(2)(3);
CREATE VIEW pv_array AS SELECT * FROM pv_data WHERE AccountId IN {AccountIds : Array(Int32)};
SELECT AccountId FROM pv_array(AccountIds = (SELECT groupArray(AccountId) FROM pv_ids)) ORDER BY AccountId;
-- Affected build: Code 456. Substitution `AccountIds` is not set. (UNKNOWN_QUERY_PARAMETER)
-- Fixed build: returns 1 / 2 / 3Bisect
Affects
Suggested next stepThe fix has landed on master; the affected release branches above still need the backport. Component: cc fix PR author: @groeneai ClickGap · Finding: Triage metadata
|
|
Checked the ClickGap backport request. Two corrections to the affected set, and the port is not mechanical. Affected set. 26.7 is affected too (ClickGap did not test it), and 26.4/26.2/26.1 are not active branches (their
So the affected active set is 26.7, 26.6, 26.5, 26.3, 25.8. Missing prerequisite. This PR extends the mechanism added by #110254 ( The conflict is not cosmetic. Resolving it the natural way (taking the master side) leaves With #110254 applied first, this PR cherry-picks cleanly on 26.7, 26.6, 26.5 and 26.3 ( 25.8 is different. Labels. Per @alexey-milovidov could you apply Not part of the backport: the positional/non- |
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 middle assertion reads the ConstantJoin "Shrinking stored blocks" log line from system.text_log, filtered by a 60-second recency window (event_time >= now() - 60). text_log.event_time is the message emission time, not the flush time, so this window races the duration of the preceding SYSTEM FLUSH LOGS. On a loaded parallel runner the flush can take tens of seconds, and the emitted line then falls out of the window, so count() returns 0 instead of 1. Measured on four failing runs, all on the parallel sanitizer jobs: the flush took 65.8s on master sha 693a303, 59.7s on PR ClickHouse#110886 sha 06b7c4b, 101.2s on PR ClickHouse#111790 and 60.9s on PR ClickHouse#111691 sha 19338ec. In each case the line's age at the assertion was at or just past the 60-second boundary (66s, 60.1s, 101s, 62s), and for the master and ClickHouse#110886 runs the server log holds the shrink line for the exact failing query id, so the shrink did happen and only the time predicate excluded it. Widen the window to 600s. This is safe because the per-test timeout is 600s, so a flush slow enough to push the emitted line past a 600s window would trip the per-test timeout first. The assertion is unchanged and never weakened: rows are scoped exactly by query_id from system.query_log filtered by log_comment and current_database = currentDatabase(), and CI assigns every test run a unique database, so the time predicate only prunes the scan. This mirrors 00177_memory_bound_merging.sh, which uses now() - 600 on the same text_log-via-query_id pattern. Reports: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=693a303c1017477fc39aaa7706af0ec078e13fbc&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29 https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110886&sha=06b7c4b127f65dbc45d7c26d867a4801c0742209&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29 Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rized-view-subquery-array-param Fix parameterized view with a subquery-valued Array/Tuple parameter
Closes: #68041
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
UNKNOWN_QUERY_PARAMETERwhen a parameterized view is called with a subquery-valued argument whose type isArray,TupleorLowCardinality, e.g.SELECT * FROM v(param = (SELECT groupArray(x) FROM t)).Description
When a parameterized view argument value is a scalar subquery, the analyzer resolves it and then collects the parameter only if the resolved node is a
ConstantNode(QueryAnalyzer::resolveTableFunction). For the large-literal types inuseless_literal_types(Array,Tuple,AggregateFunction,Function,Set,LowCardinality),evaluateScalarSubqueryIfNeededkeeps the value as a__getScalarreference instead of folding it to a literal (the scalar subquery optimization). The parameter was therefore silently dropped and the view failed withCode 456. Substitution '...' is not set. (UNKNOWN_QUERY_PARAMETER). Scalar-typed subquery arguments (e.g.Int32) were unaffected because they are always folded to a literal.A parameterized view argument value must fold to a literal to be matched against the view's query parameters, so the fix forces literal folding for that narrow resolution window via a new
parameterized_view_arguments_in_resolve_processflag (mirrors the existingtable_function_arguments_in_resolve_process). The scalar subquery optimization is unchanged everywhere else.Version info
26.8.1.158(included in26.8and later)