Skip to content

JSON AST reader/writer round-trip fixes: Float64, Tuple, BACKUP/RESTORE, TTL, DESCRIBE, JSON type args - #121585

Open
qoega wants to merge 8 commits into
ClickHouse:masterfrom
qoega:json-fuzz-group11-json-ast-round-trip
Open

qoega wants to merge 8 commits into
ClickHouse:masterfrom
qoega:json-fuzz-group11-json-ast-round-trip

Conversation

@qoega

@qoega qoega commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

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 to CHANGELOG.md):

Round-trip fixes for parseQueryToJSON / formatQueryFromJSON (clickhouse_json dialect): large Float64 literals stay readable, Tuple(...) types with partially named elements deserialize, BACKUP/RESTORE ... AS t rename into the current database survives the round trip, and TTL expr GROUP BY without grouping keys is accepted on read. Also extends the JSON AST reader to accept DESCRIBE and the JSON(...) type arguments.

Documentation entry for user-facing changes

No documentation change needed.

Detailed description / Documentation

Five commits, each one JSON AST reader/writer pair, from the JSON-AST fuzzer's new round-trip stage. Each has a matching 05248-05251 stateless test.

Note: the fuzzer's own json_ast_sql_parser_fuzzer/json_ast.proto change from the DESCRIBE-support commit stays with the fuzzer harness PR (#121057) and is not part of this PR.

Closes: #121580
Closes: #121581
Closes: #121582
Closes: #121583

cc @groeneai — fuzz-lab find (JSON AST fuzzer)

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/121585]

qoega and others added 5 commits September 22, 2026 16:25
`writeFieldJSON` wrote a `Float64` field with `writeFloatText`, which prints
values such as `9.99e19` in positional notation (`99900000000000000000`). The
JSON reader takes a number without `.` or an exponent for an integer and
fails when it does not fit 64 bits, so `formatQueryFromJSON` could not read
the output of `parseQueryToJSON('SELECT 9.99e19')`:

    Code: 36. DB::Exception: Failed to parse JSON for AST deserialization:
    Syntax error: Not a valid unsigned integer: '99900000000000000000'

Append `.0` when the shortest representation has no `.`, `e` or `E`, so the
token is always lexed as a floating point number. Covered by the test added
with the `DescribeQuery` JSON support (05248).

Found while converting the functional-test statements into a seed corpus for
`json_ast_sql_parser_fuzzer` (finding 25 of the JSON AST fuzzing campaign).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`parseQueryToJSON` rejected `ASTDescribeQuery` (`DESCRIBE`/`DESC`) and
`ASTObjectTypeArgument`/`ASTObjectTypedPathArgument` (the arguments of the
`JSON(...)` type in column definitions and `CAST`). Measured over the
statements of the functional tests, these were the two largest classes of
unsupported syntax (523 and 286 statements), so neither the parser fuzzer nor
the execution fuzzer could ever generate them.

- `DescribeQuery`: `temporary`, child `table_expression`, output options.
- `ObjectTypedPathArgument`: `path` and child `data_type`.
- `ObjectTypeArgument`: exactly one of `path_with_type`, `skip_path`,
  `skip_path_regexp`, `parameter`; anything else is `BAD_ARGUMENTS`.
- Registered in the AST factory and in `json_ast.proto` (node types 94-96,
  keys 403-407) so the structure-aware fuzzers generate them.

Test 05248 round-trips `DESCRIBE` variants, `JSON(...)` type arguments and the
large `Float64` literals from the previous commit.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`ParserDataType` accepts a tuple type that names only some of its elements,
such as `Tuple(CPU, double, Memory double)` (`DataTypeFactory` rejects the
mix later, at execution). `ASTTupleDataType::writeJSON` wrote the unnamed
elements as empty strings and `readJSON` threw for any empty name, so
`formatQueryFromJSON` refused the output of `parseQueryToJSON`:

    Code: 36. DB::Exception: ASTTupleDataType element name must not be empty
    during AST JSON deserialization

Treat an empty entry as an unnamed element, like the formatter does; the
"one name per element" check stays.

Found by the JSON round-trip stage of `json_ast_sql_parser_fuzzer` (finding 26
of the JSON AST fuzzing campaign).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`BACKUP TABLE d.t AS t` (and `RESTORE ... AS t`) stores the target as
`new_table_name = "t"`, `new_database_name = ""`; the current database is
substituted at execution. `ASTBackupQuery::writeJSON` omitted the empty new
database name and `readJSON` defaults a missing one to the old database, so
`formatQueryFromJSON(parseQueryToJSON(...))` dropped the `AS` clause. For
`RESTORE` that changes the destination table.

Write a new name whenever it differs from the old one, including the empty
database.

Found by the JSON round-trip stage of `json_ast_sql_parser_fuzzer` (finding 27
of the JSON AST fuzzing campaign).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`ParserTTLElement` parses the keys of `TTL expr GROUP BY` with
`ParserExpressionList`, which accepts an empty list, and `MergeTree` accepts
such a table. `ASTTTLElement::readJSON` rejected an empty `group_by_key` in
`GROUP_BY` mode as a shape the parser could not produce, so
`formatQueryFromJSON` refused the output of `parseQueryToJSON` for
`ALTER TABLE t MODIFY TTL d GROUP BY`:

    Code: 36. DB::Exception: TTL GROUP BY requires a non-empty 'group_by_key'
    during AST JSON deserialization

Accept the empty list; keys or assignments on the other TTL modes are still
rejected.

Found by the JSON round-trip stage of `json_ast_sql_parser_fuzzer` (finding 28
of the JSON AST fuzzing campaign).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@qoega qoega added the fuzz Problem found by one of the fuzzers label Sep 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [12c788d]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, parallel) FAIL
05474_parquet_corpus_writers FAIL cidb
05474_parquet_corpus_writers FAIL cidb
05474_parquet_corpus_writers FAIL cidb
Stateless tests (arm_binary, parallel) FAIL
05474_parquet_corpus_writers FAIL cidb
05474_parquet_corpus_writers FAIL cidb
05474_parquet_corpus_writers FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (amd_illumos) DROPPED
Build (ppc64le) DROPPED

AI Review

Summary

The PR fixes JSON AST round trips for floating-point literals, tuples, backup renames, and TTL clauses, and adds support for DESCRIBE and JSON type arguments. Request changes: integration with current master silently loses the SHARED modifier on typed JSON paths.

Findings

⚠️ Majors

  • src/Parsers/ASTObjectTypeArgument.cpp:106: ASTObjectTypedPathArgument::writeJSON omits shared, and readJSON leaves it false. Reproduced with the PR's CI binary: CREATE TABLE t (j JSON(SHARED a UInt64)) ENGINE = MergeTree ORDER BY tuple() round-trips to a declaration containing JSON(a UInt64). Nested declarations are also affected. Executing the JSON representation therefore changes the requested schema and stores typed paths in separate files instead of typed shared storage. Serialize and restore shared, defaulting to false for older payloads.
Tests
  • ⚠️ Add focused round-trip cases for direct and nested SHARED typed paths against current master; the existing cases omit this modifier.
Final Verdict

Status: ⚠️ Request changes. Preserve shared in both serialization directions and add the regression coverage above.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. labels Sep 22, 2026
qoega added a commit to qoega/ClickHouse that referenced this pull request Sep 24, 2026
Sibling PR ClickHouse#121585 → group 11 already had 05248-05251; the finding 30
fix (JIT number to Decimal) in PR-in-preparation claims 05252
(05252_jit_number_to_decimal_overflow). Move the sweep further out
of the way.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ding 28 fix)

The finding-28 fix accepts an empty `group_by_key` on a `GROUP_BY` TTL,
matching `MergeTree` which accepts `TTL d GROUP BY` with no keys
(aggregates the whole part). Drop that case; keep the reverse case
(adding `group_by_key` to a `DELETE` TTL is still rejected).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Comment thread src/Parsers/ASTDescribeQuery.cpp Resolved
Comment thread src/Parsers/ASTObjectTypeArgument.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 12c788d6d with master cfe4dae6d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

14 object files changed (+560.89 KiB total), 1 added.

Object file Master PR Δ
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ASTDescribeQuery.cpp.o new 303.42 KiB +303.42 KiB
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ASTObjectTypeArgument.cpp.o 67.74 KiB 321.06 KiB +253.32 KiB (+373.94%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserDescribeTableQuery.cpp.o 94.61 KiB 62.12 KiB -32.49 KiB (-34.34%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ASTJSONHelpers.cpp.o 37.84 KiB 68.13 KiB +30.29 KiB (+80.06%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

24 translation units recompiled, 87 s compile time in total, 23 of them have a recent master baseline.

Job report

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Oct 22, 2026
…alization

`ParserTTLElement` accepts `WHERE` only after `DELETE`, and `TTLDescription`
applies it only for `DELETE`, but `ASTTTLElement::readJSON` restored
`where_expr` for every mode. A `clickhouse_json` `CREATE TABLE ... TTL d TO DISK
'default'` carrying a `where_expr` was therefore accepted, the `WHERE` was
ignored, and `formatImpl` stored `TTL d TO DISK 'default' WHERE x`, which fails
to parse at the next start (`Code: 62`), so the database does not load. Same for
`RECOMPRESS` and `GROUP BY`; `formatQueryFromJSON` returned the same
unparsable SQL.

Reject `where_expr` unless the mode is `DELETE`, like the existing per-mode
checks for the codec, destination and `GROUP BY` fields in the same function.
The check sits at the read site so it does not textually overlap ClickHouse#108069 (which
adds the same check for its new `CLEAR INDEX` mode) or ClickHouse#121585.

Requested in ClickHouse#108069 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Parsers/ASTObjectTypeArgument.cpp Resolved
…DESCRIBE TEMPORARY

Three parser-impossible shapes that the new JSON AST round-trip readers
accepted:

* `ASTObjectTypedPathArgument` 'data_type' used `IAST::as<ASTDataType>()`,
  which matches `typeid` exactly and rejects the `ParserDataType` subclasses
  `ASTTupleDataType` and `ASTEnumDataType`. Round-tripping
  `CREATE TABLE t (j JSON(a Tuple(UInt64, String))) ENGINE = Memory`
  (and the `Enum8` counterpart) threw `BAD_ARGUMENTS` on read even though
  write produced a valid payload. Use `dynamic_cast<const ASTDataType *>`
  to accept the whole hierarchy, mirroring `ASTColumnDeclaration::readJSON`.

* `ASTDescribeQuery` accepted `temporary = true` alongside any
  `table_expression`, but `ParserDescribeTableQuery` sets the flag only in
  the `DESCRIBE TEMPORARY TABLE <name>` branch after confirming the table
  expression is a bare name. A payload setting `temporary` with a subquery
  or table-function `table_expression` formats as
  `DESCRIBE TEMPORARY TABLE (SELECT ...)` / `... TABLE numbers(1)`, which
  the SQL parser cannot read back. Require `database_and_table_name` when
  `temporary` is true.

* `ASTObjectTypeArgument` accepted any `ASTLiteral` for `skip_path_regexp`
  and any `ASTFunction` for `parameter`. `ObjectArgumentParser` parses the
  regexp with `ParserStringLiteral` and builds the parameter with
  `makeASTOperator("equals", identifier, number)`. A numeric
  `skip_path_regexp` would format as `SKIP REGEXP 42`, and an arbitrary
  `parameter` function would format as `JSON(<garbage>)`. Validate those
  shapes at the JSON boundary: a `String`-typed `ASTLiteral` for the regexp
  and an `equals` operator with exactly `(ASTIdentifier, numeric ASTLiteral)`
  arguments for the parameter.

Add stateless regression rows to the test file this PR owns
(04350_ast_json_parser_impossible_field_combinations): two valid typed-path
round-trips (`Tuple(UInt64, String)` and `Enum8('a'=1)`), one malformed
`temporary=true + subquery` payload, and two malformed `ObjectTypeArgument`
payloads (numeric `skip_path_regexp` and non-`equals` `parameter`).

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

qoega commented Nov 1, 2026

Copy link
Copy Markdown
Member Author

Review follow-up landed as 12c788d6d08. Addresses all three AI-reviewer majors (dated 2026-09-25, with the typed-path item re-posted 2026-10-22) in one commit.

Major 1 — typed JSON paths rejected Tuple / Enum. ASTObjectTypedPathArgument::readJSON was using IAST::as<ASTDataType>(), which does typeid exact matching, so ASTTupleDataType and ASTEnumDataType (both produced by ParserDataType) failed the check even though they are the normal shapes. Replaced with dynamic_cast<const ASTDataType *>(child.get()), mirroring ASTColumnDeclaration::readJSON. SELECT formatQueryFromJSON(parseQueryToJSON('CREATE TABLE t (j JSON(a Tuple(UInt64, String))) ENGINE = Memory')) now round-trips, and the same for Enum8('a'=1).

Major 2 — DESCRIBE TEMPORARY TABLE <non-name> deserialized. ASTDescribeQuery::readJSON accepted any ASTTableExpression as the table-expression child even when temporary was true, so a subquery or table function alongside "temporary": true deserialized cleanly and formatting emitted parser-invalid SQL (DESCRIBE TEMPORARY TABLE numbers(1)). After the existing type check, now also require table_expression->database_and_table_name whenever temporary is set; otherwise BAD_ARGUMENTS. Matches ParserDescribeTableQuery.cpp:141-148.

Major 3 — ASTObjectTypeArgument::readJSON accepted malformed shapes.

  • skip_path_regexp: swapped readChildOfType<ASTLiteral> for the existing readStringLiteralChild helper, so only String-typed literals are accepted (previously SKIP REGEXP 1 was formattable).
  • parameter: kept readChildOfType<ASTFunction> and added a parser-shape check requiring name == "equals", isOperator(), a 2-child ASTExpressionList of (ASTIdentifier, numeric ASTLiteral where field type is UInt64/Int64/Float64) — matching what ObjectArgumentParser produces.
  • path_with_type already dispatches through ASTObjectTypedPathArgument, whose inner data_type is validated by Major 1.

Regression cases in 04350_ast_json_parser_impossible_field_combinations.{sql,reference}:

  • Typed Tuple(UInt64, String) and Enum8('a'=1) round-trips (controls that previously failed).
  • DESCRIBE (SELECT 1) with temporary flipped to true in the JSON → BAD_ARGUMENTS.
  • Numeric skip_path_regexp → rejected.
  • plus(...) as parameter → rejected.

{
JSONObjectWriter w(out, "ObjectTypedPathArgument");
w.writeString("path", path);
w.writeChild("data_type", type);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Preserve the SHARED modifier on typed JSON paths

When merged with current master, ASTObjectTypedPathArgument also carries shared, but this writer emits only path and data_type and the reader leaves shared = false. With this PR's Fast test binary, SELECT formatQueryFromJSON(parseQueryToJSON('CREATE TABLE t (j JSON(SHARED a UInt64)) ENGINE = MergeTree ORDER BY tuple()')) returns a declaration containing JSON(a UInt64). Nested typed paths lose the modifier too.

This silently changes the requested storage layout: The createObject factory in DataTypeObject.cpp uses this flag to select typed shared storage, so executing the JSON representation creates a different schema and uses separate files for every affected path. Please serialize and restore shared (defaulting to false for existing payloads), and add a round-trip regression for direct and nested SHARED paths against current master.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. fuzz Problem found by one of the fuzzers pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

2 participants