Skip to content

Fix inconsistent AST formatting for CODEC with tuple-wrapped multi-arg unary functions (STID 1941-1bfa) - #104991

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-codec-tuple-paren-round-trip-1941-1bfa
May 31, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-codec-tuple-paren-round-trip-1941-1bfa

Conversation

@groeneai

@groeneai groeneai commented May 15, 2026 •

Copy link
Copy Markdown
Collaborator

Queries like the following abort the server with Logical error: 'Inconsistent AST formatting between 'ExpressionList' and 'ExpressionList' (STID 1941-1bfa) in debug / sanitiser builds, because the format-parse-format round-trip check in DB::executeQueryImpl diverges by one paren level around the inner tuple(...):

CREATE TABLE t (c0 Int CODEC(not((not(materialize(1), materialize(2)))), ZSTD)) ENGINE = Memory;

The first format pass emits CODEC(not((not(tuple(materialize(1), materialize(2))))), ZSTD). The re-parse sees tuple(...) wrapped in (...) (from the outer not(...) parenthesised argument); RoundBracketsLayer::getResultImpl in src/Parsers/ExpressionListParsers.cpp sets parenthesized = true on the unwrapped inner Function_tuple. On the second format pass the parenthesized flag adds an extra (...) around tuple(...) — not((not((tuple(materialize(1), materialize(2)))))) — and the round-trip check fires.

Inside CODEC / STATISTICS / BACKUP_NAME argument lists, ASTFunction::formatImpl forces FormatStateStacked::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, ...)). In that context the outer parenthesized paren is always redundant — (tuple(a, b)) and tuple(a, b) denote the same value — so suppressing it in IAST::decideParensEmission keeps the round-trip stable.

The new clause mirrors the existing literal-tuple suppression a few lines above. The fix is gated on:

  • func->name == "tuple" (other operator-form functions like plus/equals need their parens for precedence)
  • func->arguments->children.size() > 1 (single-argument tuple(x) keeps its existing behaviour and round-trips cleanly)
  • !frame.allow_operators (plain expression contexts where the operator form (a, b) is canonical are unaffected — multi-element tuple literals there are already handled by the existing Field::Types::Tuple clause above)

This is a partial fix for chronic STID 1941-1bfa. It addresses two subvariants reported by @alexey-milovidov on PRs #100412 / #94517 / #104591:

  • CREATE TABLE ... CODEC(not(a, b)) (variadic-2 call on unary function in CODEC)
  • ALTER TABLE ... MODIFY STATISTICS ... TYPE concatAssumeInjective((...))

Other reported subvariants — DESCRIBE TABLE (SELECT ... COLUMNS(multiIf(...)) ...) and qualifier-chained SELECT db.t.COLUMNS(*) FROM ... — involve different parser/formatter paths (COLUMNS matcher / DESCRIBE wrapper) and need separate fixes; they are still tracked in the canonical task.

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

CI sighting on PR #100412 (one of 40+ affected PRs in the last 90 days plus master hits): 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

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

Fix a Logical error: 'Inconsistent AST formatting' server abort (STID 1941-1bfa) on queries like CREATE TABLE t (c0 Int CODEC(not((not(materialize(1), materialize(2)))), ZSTD)) ENGINE = Memory in debug / sanitiser builds. The formatter no longer emits redundant outer parens around a multi-argument tuple(...) function call that appears inside CODEC / STATISTICS / BACKUP_NAME argument lists (where the operator form (a, b) is disabled), keeping the format-parse-format round-trip stable.

Documentation entry for user-facing changes

  • Documentation is unchanged (no user-facing API or behaviour change beyond round-trip stability).

Version info

  • Merged into: 26.6.1.284

…_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
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (self-assessment per TASK.md Phase 4):

(a) Deterministic repro? Yes. CREATE TABLE t (c0 Int CODEC(not((not(materialize(1), materialize(2)))), ZSTD)) ENGINE = Memory aborts the server on master (debug build) with Logical error: 'Inconsistent AST formatting between 'ExpressionList' and 'ExpressionList' (STID: 1941-1bfa). Hits the round-trip check at src/Interpreters/executeQuery.cpp:1330. Single command, no settings dependency.

(b) Root cause explained? Yes. The first format emits tuple(materialize(1), materialize(2)) (function-call form because allow_operators=false inside CODEC). The re-parser sees (tuple(...)) (parens come from the outer not(...) argument) and RoundBracketsLayer::getResultImpl in src/Parsers/ExpressionListParsers.cpp:1375 sets parenthesized = true on the inner Function_tuple. On the second format pass, IAST::decideParensEmission emits the parenthesized flag's parens, adding one extra (...) layer: not((tuple(...))) vs the original not(tuple(...)). Diff is exactly one paren around tuple(...).

(c) Fix matches root cause? Yes. Suppresses the parenthesized flag's parens for multi-argument Function_tuple specifically when frame.allow_operators = false (the only context where the formatter falls back to function-call form tuple(...) for an operator-form-capable function). The fix lives at the exact site that decides paren emission (decideParensEmission), mirrors the existing literal-tuple suppression a few lines above, and stays within the formatter — no parser change.

(d) Test intent preserved? / New tests added? Yes, new test 04241_inconsistent_ast_codec_tuple_paren_round_trip_1941_1bfa.sql covers the original reproducer plus 8 round-trip variants (multiple arg counts, tuple vs (tuple) shapes, STATISTICS context, single-arg negative case to prove the fix didn't over-reach, real CODEC(Delta, LZ4) to prove ordinary declarations are unaffected, expression-context tuple usage to prove !frame.allow_operators gating is correct). 19 existing AST / CODEC / paren tests still pass with the fix.

(e) Both directions demonstrated? Yes. Before the fix the original CREATE TABLE reproducer aborts the server with SIGABRT (verified locally on b6844b26db6). After the fix the same statement returns UNKNOWN_CODEC (the proper error because not is not a codec family), and formatQuerySingleLine on the same shape returns a single-pass-stable formatted output. The new test was run with --test-runs 30 against the fixed binary — 30/30 pass.

(f) Fix is general, not a narrow patch? Yes within its scope, with documented limitations:

  • The same parser-side bug pattern (RoundBracketsLayer setting parenthesized = true on a function-call node) is checked against Function_array — but [] is parsed via ArrayLayer, not RoundBracketsLayer, so the asymmetry that breaks Function_tuple does not exist for Function_array. Verified locally: CREATE TABLE t (c0 Int CODEC(not((array(1, 2, 3))), ZSTD)) round-trips cleanly without the fix.
  • The fix covers two of the four STID 1941-1bfa subvariants flagged by @alexey-milovidov on PRs AST JSON serialization #100412 / Enable optimize_or_like_chain by default. #94517 / Add optimize_row_order_if_no_order_by (reopen #103919) #104591: CODEC(not(a, b)) and STATISTICS concatAssumeInjective((...)). The other two — DESCRIBE TABLE (SELECT ... COLUMNS(multiIf(...))) and qualifier-chained SELECT db.t.COLUMNS(*) FROM ... — involve different parser/formatter paths (COLUMNS matcher / DESCRIBE wrapper) and are tracked in the canonical task for separate fixes. This PR is intentionally scoped to one root cause to keep the diff minimal and reviewable.
  • Defensive gating: func->name == "tuple", args.size() > 1, and !frame.allow_operators together ensure (i) other operator-form functions like plus / equals keep their parens for precedence, (ii) single-argument tuple(x) is unaffected (already round-trips cleanly), and (iii) plain expression contexts where (a, b) is canonical are unaffected.

Session: cron:clickhouse-ci-task-worker:20260515-014500.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @evillique @alexey-milovidov @george-larionov — could you review this? It fixes the chronic STID 1941-1bfa Inconsistent AST formatting LOGICAL_ERROR for the CODEC(not(a, b)) / STATISTICS concatAssumeInjective((...)) subvariants by suppressing redundant outer parens around multi-arg Function_tuple in allow_operators=false contexts in IAST::decideParensEmission. Follow-up to PR #102547 / #104520 / #104626.

@clickhouse-gh

clickhouse-gh Bot commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [551bf44]

Summary: ✅


AI Review

Summary

This PR stabilizes format-parse-format round-tripping for multi-argument tuple calls inside contexts where allow_operators is disabled (CODEC, STATISTICS, BACKUP_NAME) by suppressing redundant outer parenthesized emission in decideParensEmission, and it adds focused stateless coverage for the reported STID variants. I did not find unresolved contract violations or new high-impact risks in the current diff.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 17, 2026
Issue ClickHouse#105396 reported the same `Inconsistent AST formatting` (STID 1941-1bfa)
firing on `RESTORE TABLE src AS dst FROM Memory(...)` queries. The `Memory(...)`
backup name is parsed by `parseBackupName` in `src/Parsers/ParserBackupQuery.cpp`
and tagged as `ASTFunction::Kind::BACKUP_NAME`, which is the third kind that
forces `frame.allow_operators = false` at `ASTFunction.cpp:298`. Descendants of
the backup name inherit this frame state, so a multi-arg `Function_tuple`
nested inside the engine argument list hits the exact same round-trip path as
the existing `CODEC` / `STATISTICS` reproducers.

The fix in `IAST::decideParensEmission` is gated on `!frame.allow_operators` and
therefore already covers the BACKUP_NAME case. This commit adds explicit
regression coverage for it so the issue ClickHouse#105396 failure shape stays caught.
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai merge with master

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim merged master into the PR branch as requested. New HEAD SHA: 551bf4473f77.

Merge was conflict-free. PR diff is unchanged (3 files, 113 insertions):

  • src/Parsers/IAST.cpp (decideParensEmission Function_tuple multi-arg suppression in !allow_operators contexts)
  • tests/queries/0_stateless/04241_inconsistent_ast_codec_tuple_paren_round_trip_1941_1bfa.sql (regression test)
  • tests/queries/0_stateless/04241_inconsistent_ast_codec_tuple_paren_round_trip_1941_1bfa.reference

src/Parsers/IAST.cpp blob was identical between the PR's merge-base and current master, so no behavioural changes from the rebase. CI should retrigger automatically.

@clickhouse-gh

clickhouse-gh Bot commented May 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.50% +0.00%

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

Full report · Diff report

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.

4 participants