Skip to content

Fix inconsistent AST formatting for INSERT with SAMPLE and OFFSET - #102547

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
zoomxi:fix-ast-inconsistent
Apr 28, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
zoomxi:fix-ast-inconsistent

Conversation

@zoomxi

@zoomxi zoomxi commented Apr 13, 2026

Copy link
Copy Markdown
Contributor

This PR fixes an AST formatting inconsistency discovered by BuzzHouse fuzzer. When an INSERT query contains a SELECT with both SAMPLE and a query-level OFFSET (without LIMIT), the formatter incorrectly used FROM-first syntax (FROM t SAMPLE x SELECT ... OFFSET y), which caused the re-parsed query to fail with a syntax error due to ambiguity with INSERT ... FROM INFILE syntax.

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 inconsistent AST formatting for INSERT with SAMPLE and query-level OFFSET. Closes #102523.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Apr 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2e8a52f]

Summary: ✅


AI Review

Summary

This PR fixes formatter round-trip behavior for INSERT ... SELECT queries where SAMPLE and standalone query-level OFFSET can trigger ambiguous SQL when FROM-first formatting is used. The change introduces a formatter frame flag to suppress FROM-first formatting for the immediate SELECT under INSERT, while preserving nested subquery behavior via targeted reset in ASTSelectQuery, and adds focused stateless coverage for top-level and nested cases. I did not find correctness, safety, or performance issues that require changes.

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-bugfix Pull request with bugfix, not backported by default label Apr 15, 2026
Comment thread src/Parsers/ASTInsertQuery.cpp Resolved
@zoomxi
zoomxi force-pushed the fix-ast-inconsistent branch from be0591f to 51a7a8a Compare April 16, 2026 08:57
@zoomxi
zoomxi force-pushed the fix-ast-inconsistent branch from 51a7a8a to 95756d5 Compare April 17, 2026 01:54
@azat azat self-assigned this Apr 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.50% +0.00%

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

Full report · Diff report

@zoomxi

zoomxi commented Apr 28, 2026

Copy link
Copy Markdown
Contributor Author

@azat CI is green now. Could you please take some time to review this PR when you're free? Thanks!

@alexey-milovidov alexey-milovidov self-assigned this Apr 28, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Apr 28, 2026
Merged via the queue into ClickHouse:master with commit a9bc4b8 Apr 28, 2026
165 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 28, 2026
@zoomxi
zoomxi deleted the fix-ast-inconsistent branch April 29, 2026 01:44
bool format_from_first = sampleSize() && limitOffset() && !limitLength();
/// Note: FROM-first syntax is disabled for SELECTs inside INSERT to avoid
/// parsing ambiguity with INSERT ... FROM INFILE syntax.
bool format_from_first = sampleSize() && limitOffset() && !limitLength() && !frame.disable_from_first_syntax;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks wrong and breaks the whole point of the previous fix #100579

:) EXPLAIN AST INSERT INTO t (FROM system.one SAMPLE 0.5 SELECT 1 OFFSET 10)

EXPLAIN AST
INSERT INTO t SELECT 1
FROM system.one
SAMPLE 5 / 10
OFFSET 10

Query id: 9371f344-f131-4345-a873-e34bb6be0b3e

    ┌─explain──────────────────────────────────────┐
 1. │ InsertQuery   (children 2)                   │
 2. │  Identifier t                                │
 3. │  SelectWithUnionQuery (children 1)           │
 4. │   ExpressionList (children 1)                │
 5. │    SelectQuery (children 3)                  │
 6. │     ExpressionList (children 1)              │
 7. │      Literal UInt64_1                        │
 8. │     TablesInSelectQuery (children 1)         │
 9. │      TablesInSelectQueryElement (children 1) │
10. │       TableExpression (children 2)           │
11. │        TableIdentifier system.one            │
12. │        SampleRatio 5 / 10                    │
13. │     Literal UInt64_10                        │
    └──────────────────────────────────────────────┘

13 rows in set. Elapsed: 0.001 sec.

:) EXPLAIN AST INSERT INTO t (SELECT 1
FROM system.one
SAMPLE 5 / 10
OFFSET 10)

EXPLAIN AST
INSERT INTO t SELECT 1
FROM system.one
SAMPLE 5 / 10 OFFSET 10

Query id: c7e11ee7-ffed-4f54-8b76-78565223ca61

    ┌─explain──────────────────────────────────────┐
 1. │ InsertQuery   (children 2)                   │
 2. │  Identifier t                                │
 3. │  SelectWithUnionQuery (children 1)           │
 4. │   ExpressionList (children 1)                │
 5. │    SelectQuery (children 2)                  │
 6. │     ExpressionList (children 1)              │
 7. │      Literal UInt64_1                        │
 8. │     TablesInSelectQuery (children 1)         │
 9. │      TablesInSelectQueryElement (children 1) │
10. │       TableExpression (children 3)           │
11. │        TableIdentifier system.one            │
12. │        SampleRatio 5 / 10                    │
13. │        SampleRatio 10                        │
    └──────────────────────────────────────────────┘

13 rows in set. Elapsed: 0.001 sec.

And this extra flag looks hacky, can we just do not remove brackets instead?

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-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.

Logical error: 'Inconsistent AST formatting: the query: (STID: 1941-1bfa)

5 participants