Skip to content

Reject collection literals as data-type arguments (STID 1941-1bfa) - #104520

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-1941-ast-data-type-literal-clean
May 10, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-1941-ast-data-type-literal-clean

Conversation

@groeneai

@groeneai groeneai commented May 10, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

AST fuzzer (amd_debug) and related sanitizer/fuzzer jobs hit a chronic LOGICAL_ERROR: Inconsistent AST formatting (STID 1941-1bfa) in executeQuery.cpp:1280 whenever a fuzzed query puts a collection literal ((NULL), [NULL], {a: 1}) inside a parameterized data type's argument list.

Latest hit: PR #100177 (commit 9322e66):

CREATE TABLE t0__fuzz_31 (`a` Nullable(multiply((NULL), Int8)), ...) ENGINE = ReplacingMergeTree ...

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100177&sha=9322e66151ea6cc3017cc476e1f8d958bb56421c&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29

The bug has been hit by 20+ unrelated PRs over the last 30 days. Master is unaffected (the round-trip check fires only in DEBUG/sanitizer builds, and master CI doesn't usually run AST fuzzer mutations against the same seed). PR #102547 by @zoomxi (merged 2026-04-29) fixed one specific variant (INSERT with SAMPLE and OFFSET); this PR addresses the broader collection-literal variant.

Root cause

Inside ParserDataType::parseImpl (src/Parsers/ParserDataType.cpp), arguments to a parameterized data type were parsed with ParserAllCollectionsOfLiterals, which accepts (...), [...], {...} (with false for the map case). For multiply((NULL), Int8) this gives DataType_multiply -> [Literal_Tuple_(NULL), DataType_Int8].

Formatting that AST goes through FieldVisitorToString::operator()(const Tuple &), which prints a single-element Tuple literal as tuple(NULL) (the explicit function form, used to avoid (NULL) re-parsing as a parenthesized expression in regular SQL contexts).

Re-parsing multiply(tuple(NULL), Int8) in data-type-argument context: tuple(NULL) starts with an identifier (not (/[/{), so ParserAllCollectionsOfLiterals doesn't trigger. Falls through to ParserDataType, which parses it as ASTDataType("tuple") with a Literal_NULL child. Different shape → getTreeHash differs → LOGICAL_ERROR.

The same goes for multiply([NULL], Int8) (Literal_Array_(NULL) ↔ [NULL] re-parsed as a Literal_Array... but the formatter for empty arrays / various edge cases also drifts). I confirmed the exact same crash for both (NULL) and [NULL] variants locally.

Fix

No real data type takes a collection literal as a parameter:

  • Simple literals: FixedString(5), Decimal(10, 2), DateTime64(3, 'UTC')
  • Nested types: Nullable(Int32), Array(String), LowCardinality(...)
  • Special handling: Tuple(Int32, String), Enum8('a' = 1, 'b' = 2) (separate code paths in the same function)

Replace ParserAllCollectionsOfLiterals literal_parser(false) with ParserLiteral literal_parser. Malformed queries are now rejected at parse time with SYNTAX_ERROR (Code 62) instead of crashing later in the round-trip check.

Verified locally:

  • multiply((NULL), Int8), multiply([NULL], Int8), Nullable(multiply((NULL), Int8)) → SYNTAX_ERROR (was: LOGICAL_ERROR crash)
  • Sanity-tested 13 common type families (UInt32, Decimal(10,2), DateTime64(3,'UTC'), FixedString(5), Nullable(String), Tuple(...), Array(Tuple(...)), Enum8(...), LowCardinality(Nullable(FixedString(10))), Map(String, Array(Int32)), SimpleAggregateFunction(sum, UInt64), AggregateFunction(uniq, Int32), Variant(...)) — all parse correctly.

Test changes

tests/queries/0_stateless/03210_inconsistent_formatting_of_data_types.sh had one case Array((1), UInt8) in the "possibly incorrect but should round-trip" section that relied on the old behavior. Move it to the "invalid queries that don't parse" section alongside three new regression cases for STID 1941-1bfa. The 4 tracked-as-valid cases continue to round-trip unchanged.

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.499

Parser change in `ParserDataType` to no longer accept tuple/array/map
literals like `(1)`, `[1, 2]` or `{a: 1}` as arguments to a
parameterized data type (e.g. `multiply((NULL), Int8)` inside a column
type). Previously these were parsed by `ParserAllCollectionsOfLiterals`
into an `ASTLiteral` with `Field::Tuple` (or `Field::Array`) sitting
inside the type's argument list. The formatter then prints that Tuple
literal as `tuple(NULL)` (the explicit function form, see
`FieldVisitorToString::operator()(const Tuple &)`), and re-parsing
`multiply(tuple(NULL), Int8)` in this context yields an
`ASTDataType("tuple")` instead of an `ASTLiteral`, which breaks the AST
round-trip check in `executeQuery` (DEBUG/sanitizer builds) with
`LOGICAL_ERROR: Inconsistent AST formatting` (STID 1941-1bfa).

No real data type takes a collection literal as a parameter — every
parameterized type either takes simple literals (e.g. `FixedString(5)`,
`Decimal(10, 2)`, `DateTime64(3, 'UTC')`), nested types (e.g.
`Nullable(Int32)`, `Array(String)`), or has special handling
(`Tuple(Int32, String)`, `Enum8('a' = 1)`). Rejecting collection
literals at parse time is the cleanest fix: the malformed query is
caught up-front with `SYNTAX_ERROR` instead of crashing later in the
round-trip check.

Existing test `03210_inconsistent_formatting_of_data_types` had one
case (`Array((1), UInt8)`) in the "possibly incorrect but should
round-trip" section that depended on the old behavior. Move it to the
"invalid queries that don't parse" section together with three new
regression cases (`multiply((NULL), Int8)`, `multiply([NULL], Int8)`,
`Nullable(multiply((NULL), Int8))`) covering the STID 1941-1bfa
variants reported in CI.

Closes the chronic STID 1941-1bfa fuzzer family for the
collection-literal-in-data-type variant. CI: PR ClickHouse#100177
(commit 9322e66) AST fuzzer (amd_debug) failure
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100177&sha=9322e66151ea6cc3017cc476e1f8d958bb56421c&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate

Per TASK.md Phase 4 step 9 — answering the five mandatory questions:

a) Deterministic repro? ✅ Yes. The minimal repro is one statement:

build/programs/clickhouse local --query "CREATE TABLE t (a multiply((NULL), Int8)) ENGINE = Memory"

Without the fix this aborts with LOGICAL_ERROR: Inconsistent AST formatting (STID: 1941-1bfa). With the fix it returns SYNTAX_ERROR (Code 62) immediately.

b) Root cause explained? ✅ Yes. The parser uses ParserAllCollectionsOfLiterals to parse data-type arguments, which accepts (NULL) as a Literal_Tuple_(NULL) (ASTLiteral with Field::Tuple([NULL])). The formatter then prints that single-element Tuple literal as tuple(NULL) (the explicit function form, see comment in FieldVisitorToString::operator()(const Tuple &)). Re-parsing multiply(tuple(NULL), Int8) in data-type-argument context produces an ASTDataType("tuple") because tuple(NULL) starts with an identifier (not (/[/{), so the literal collection parser doesn't trigger and the data-type parser handles it as a parameterized DataType. Same input text → different AST shape after one round-trip → getTreeHash differs → LOGICAL_ERROR.

c) Fix matches root cause? ✅ Yes. The fix is at the source of the divergence: data-type arguments no longer accept collection literals at all. No real data type takes a tuple/array/map literal as a parameter — every parameterized type uses simple literals (FixedString(5), Decimal(10, 2), DateTime64(3, 'UTC')), nested types (Nullable(Int32), Array(String)), or has its own special handling (Tuple(Int32, String), Enum8('a' = 1)). Rejecting them upfront catches the malformed query at parse time with SYNTAX_ERROR, eliminating the round-trip mismatch.

d) Test intent preserved? / New tests added? ✅ Yes. 03210_inconsistent_formatting_of_data_types had one case (Array((1), UInt8)) in the "possibly incorrect but should round-trip" section that depended on the old behavior. It's moved to the "invalid queries that don't parse" section together with three new regression cases (multiply((NULL), Int8), multiply([NULL], Int8), Nullable(multiply((NULL), Int8))) covering the STID 1941-1bfa variants reported by the AST fuzzer in CI. The 4 valid round-trip cases in the test continue unchanged.

e) Demonstrated in both directions? ✅ Yes. With the master HEAD binary, all three repro queries crash with LOGICAL_ERROR. With the fix applied, all three return SYNTAX_ERROR (Code 62) cleanly. Sanity-tested 13 common type families (UInt32, Decimal(10, 2), DateTime64(3, 'UTC'), FixedString(5), Nullable(String), Tuple(Int32, String, Array(Int32)), Array(Tuple(Int32, String)), Enum8('a' = 1, 'b' = 2, 'c' = 3), LowCardinality(Nullable(FixedString(10))), Map(String, Array(Int32)), SimpleAggregateFunction(sum, UInt64), AggregateFunction(uniq, String), Variant(...)) — all still parse correctly. Test 03210_inconsistent_formatting_of_data_types passes locally with the updated reference.

f) Fix is general, not a narrow patch? ✅ Yes. This is the universal fix for the STID 1941-1bfa collection-literal variant. Any combination of unknown DataType name (multiply, divide, etc. — the data-type-name parser is permissive by design) wrapping any collection literal ((...), [...]) at any nesting depth (Nullable(unknown(...)), Array(unknown(...)), etc.) was producing the same class of AST round-trip mismatch. After the fix, all such constructs are rejected at parse time. The only narrower fix considered (changing FieldVisitorToString to output (NULL,) with trailing comma instead of tuple(NULL)) would have updated 25+ reference test files and risked behavior drift in expression contexts; the parser-level fix is both simpler and more semantically correct (data types should never have collection literal parameters).

Session: cron:clickhouse-ci-task-worker:20260510-124500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @evillique @alexey-milovidov — could you review this? It fixes the chronic AST fuzzer trunk bug STID 1941-1bfa for the collection-literal-in-data-type variant (fuzzer mutates a column type to multiply((NULL), Int8); parser produces Literal_Tuple_(NULL) inside the type's argument list; formatter prints it as tuple(NULL); re-parsing gives DataType_tuple; AST round-trip mismatch crashes executeQuery in DEBUG/sanitizer builds). The fix rejects collection literals as data-type arguments at parse time — no real data type uses them as parameters.

@clickhouse-gh

clickhouse-gh Bot commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [427aaa2]

Summary: ✅


AI Review

Summary

This PR fixes a real parser/formatter round-trip mismatch by rejecting collection literals in data-type argument lists, which turns a DEBUG/sanitizer LOGICAL_ERROR into an early SYNTAX_ERROR, and updates the stateless regression test accordingly. I did not find correctness, safety, compatibility, or rollout issues in the current diff.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label May 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 100.00% (4/4) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov self-assigned this May 10, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 10, 2026
Merged via the queue into ClickHouse:master with commit 8e5ccac May 10, 2026
165 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label May 10, 2026
niyue pushed a commit to niyue/ClickHouse that referenced this pull request May 31, 2026
…_operators=false` contexts

Inside `CODEC` / `STATISTICS` / `BACKUP_NAME` argument lists, `ASTFunction::formatImpl`
forces `frame.allow_operators = false`, so a multi-argument `Function_tuple` falls back
to its function-call form `tuple(arg, arg, ...)` instead of the operator form
`(arg, arg, ...)`.

`RoundBracketsLayer::getResultImpl` in `src/Parsers/ExpressionListParsers.cpp` sets
`parenthesized = true` on any node it unwraps from a single-element `(expr)`. So when a
query like
    CREATE TABLE t (c0 Int CODEC(not((not(materialize(1), materialize(2)))), ZSTD))
        ENGINE = Memory
first formats, the parser-synthesized inner `Function_tuple` (lifted from the multi-arg
`not(a, b)`) emits as `tuple(materialize(1), materialize(2))`. Re-parsing the output then
sees `tuple(...)` wrapped in `(...)` from the outer `not(...)` argument list and sets
`parenthesized = true` on the re-parsed `Function_tuple`. The next format pass adds an
extra `(...)` around `tuple(...)` via the `parenthesized` flag's parens emission in
`IAST::decideParensEmission`, breaking the format-parse-format round-trip with
`Logical error: 'Inconsistent AST formatting' (STID 1941-1bfa)` in debug / sanitizer
builds.

Both `tuple(a, b)` and `(tuple(a, b))` denote the same value, so dropping the redundant
outer paren in `allow_operators = false` contexts is semantics-preserving and keeps the
round-trip stable. The new clause mirrors the existing literal-tuple suppression a few
lines above.

The fix is gated on `args.size() > 1` so the single-argument `tuple(x)` form keeps its
existing behaviour, and on `!frame.allow_operators` so plain expression contexts where
the operator form `(a, b)` is canonical are unaffected.

This is a partial fix for chronic STID 1941-1bfa: it addresses the `CODEC` / multi-arg
`not(a, b)` subvariant and the `ALTER TABLE ... MODIFY STATISTICS ... TYPE
concatAssumeInjective((...))` subvariant. The other reported subvariants — `DESCRIBE
TABLE (SELECT ... COLUMNS(multiIf(...)) ...)` and qualifier-chained `db.t.COLUMNS(*)` —
involve different parser/formatter paths (`COLUMNS` matcher / `DESCRIBE` wrapper) and
need separate fixes.

Related: PR ClickHouse#102547 (zoomxi, INSERT-with-SAMPLE-OFFSET), PR ClickHouse#104520 (data-type
collection literals), PR ClickHouse#104626 (lambda-after-comma).

Affected PRs (90-day window per @alexey-milovidov 2026-05-14 directive on PR ClickHouse#100412):
93037, 104440, 104812, 104591, 100177, 100651, 104523, 94517, 103428, 99495, 97540,
103866, 103349, 101447, 102646, 100453, 100386, 99179, 94849, 98677, 99131, 99277,
99275, 99227, 99229, 99246, 98884, 99138, 99021, 99105, 98906, 99055, 99011, 99066,
99033, 97821, 70661, 103389, 103347, 100700, master.

CI report (PR ClickHouse#100412 sighting):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100412&sha=3284612ceea8078d500d582ce82e5ace86b239cf&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
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-ci 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