Skip to content

AST JSON serialization - #100412

Merged
alexey-milovidov merged 320 commits into
masterfrom
ast-json-serialization
Jul 30, 2026
Merged

alexey-milovidov merged 320 commits into
masterfrom
ast-json-serialization

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 23, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • New Feature

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

Add new functions to serialize and deserialize AST as JSON.


Note

Medium Risk
Introduces a new query parsing path that deserializes ASTs from JSON in both server and clients; although gated by an experimental setting, it touches core parsing/execution and adds substantial new serialization/deserialization logic that could impact correctness and resource limits.

Overview
Adds JSON round-trippable AST support: new parseQueryToJSON() and formatQueryFromJSON() SQL functions convert between SQL and a JSON AST form (with optional best-effort preservation of original comments/whitespace when formatting).

Introduces an experimental dialect = clickhouse_json mode (guarded by allow_experimental_json_ast_dialect) that accepts JSON AST directly; executeQuery, ClientBase, and LocalConnection route parsing through IAST::createFromJSON with new max_ast_depth/max_ast_elements limits and a SET-query escape hatch to switch dialects back.

Implements JSON (de)serialization (writeJSON/readJSON) for many AST node types and adds a central JSON AST factory/deserializer in ASTFromJSON, including depth/element counting and improved validation for malformed JSON ASTs.

Reviewed by Cursor Bugbot for commit 16e5854. Bugbot is set up for automated code reviews on this repo. Configure here.

@clickhouse-gh

clickhouse-gh Bot commented Mar 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a61319a]

Summary: ✅


AI Review

Summary

This PR adds JSON AST serialization/deserialization, the clickhouse_json dialect, and the parseQueryToJSON / formatQueryFromJSON helpers. The remaining issues are boundary-validation gaps in parser-owned fields: malformed clickhouse_json can still build EXPLAIN, BACKUP, and SYSTEM UNLOCK_SNAPSHOT ASTs that format into parser-impossible or semantically different SQL instead of failing with BAD_ARGUMENTS, so I would request changes before merge.

Findings

⚠️ Majors

  • [src/Parsers/ASTExplainQuery.cpp:39] ASTExplainQuery::readJSON still accepts an arbitrary query child. ParserExplainQuery only accepts query shapes that depend on kind (EXPLAIN QUERY TREE is SELECT-only, EXPLAIN TABLE OVERRIDE has no query, and the other kinds accept only top-level query nodes), so malformed JSON can pass deserialization and formatQueryFromJSON then emits EXPLAIN 1 / EXPLAIN QUERY TREE CREATE TABLE ..., which the SQL parser cannot round-trip back.
  • [src/Parsers/ASTBackupQuery.cpp:635] cluster_host_ids is a parser-owned special setting, but readJSON restores it as an arbitrary AST. Malformed JSON can therefore format as SETTINGS cluster_host_ids = 1; reparsing falls through to the generic ASTSetQuery path instead of reconstructing query.cluster_host_ids, so the AST->JSON->SQL round-trip changes semantics instead of failing at the JSON boundary.
  • [src/Parsers/ASTSystemQuery.cpp:913] backup_source for SYSTEM UNLOCK_SNAPSHOT is restored generically. The parser only accepts a backup-name function there, so malformed JSON can format into parser-impossible SQL (FROM 1, FROM (SELECT 1), etc.) rather than being rejected during deserialization.
Tests
  • ⚠️ Add focused negative coverage for non-query ExplainQuery.query, malformed cluster_host_ids, and malformed backup_source; the current AST-JSON suite covers many special slots, but not these remaining parser-owned shapes.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: validate ASTExplainQuery.query against the ExplainKind-specific parser contract, and tighten cluster_host_ids / backup_source to the shapes their SQL parsers actually produce, with regression tests for each rejection path.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 23, 2026
Comment thread src/Parsers/ASTJSONHelpers.cpp Resolved
Comment thread src/Parsers/ASTJSONReadHelpers.cpp Resolved
Comment thread src/Parsers/IAST.cpp Resolved
Comment thread src/Functions/parseQueryToJSON.cpp Resolved
Comment thread src/Client/ClientBase.cpp Resolved
Comment thread src/Client/LocalConnection.cpp Resolved
Comment thread src/Functions/formatQueryFromJSON.cpp Resolved
Comment thread src/Functions/parseQueryToJSON.cpp Resolved
Comment thread src/Parsers/ASTFromJSON.cpp Resolved
Comment thread src/Parsers/ASTAssignment.h Resolved
Comment thread src/Parsers/ASTSQLSecurity.cpp Resolved
Comment thread src/Parsers/SelectUnionMode.cpp Resolved
Comment thread src/Parsers/ASTDictionary.cpp Resolved
Comment thread src/Parsers/ASTSetQuery.cpp Resolved
Comment thread src/Parsers/ASTSetQuery.cpp Resolved
Comment thread src/Parsers/ASTRenameQuery.cpp Resolved
Comment thread src/Parsers/ASTTTLElement.cpp Resolved
Comment thread src/Parsers/ASTViewTargets.cpp Resolved
Comment thread src/Parsers/ASTSelectWithUnionQuery.cpp Resolved
Comment thread src/Parsers/ASTJSONReadHelpers.h Resolved
Comment thread src/Parsers/ASTAlterQuery.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Parsers/ASTFromJSON.cpp Resolved
Comment thread src/Parsers/ASTSetQuery.cpp Resolved
Comment thread src/Parsers/ASTSetQuery.cpp Resolved
Comment thread src/Parsers/ASTSetQuery.cpp Resolved
@alexey-milovidov
alexey-milovidov marked this pull request as ready for review March 29, 2026 15:48
…al` in JSON

`writeJSON` always emits these leaf scalars, but the readers defaulted a missing key to
an empty string or zero. A missing `min_attr_name`/`max_attr_name` formatted a
parser-impossible `RANGE(...)`, a missing `layout_type` formatted `LAYOUT()`, a missing
lifetime bound silently became `LIFETIME(MIN 0 MAX 0)`, and a missing `seconds`/`months`
turned a `REFRESH` schedule into `0 SECOND` instead of failing closed.

Require these keys (and reject empty identifiers), and reject layout parameters without
brackets, which `ParserDictionaryLayout` rejects too.
…lyzer

`QueryNormalizer` treats `max_ast_depth = 0` as a literal limit of zero rather than as
"no limit", so with the old analyzer every query in the test fails with `TOO_DEEP_AST`
before it can exercise the JSON deserialization depth guards.
Comment thread src/Parsers/ASTSubquery.cpp Resolved
@alexey-milovidov alexey-milovidov self-assigned this Jul 29, 2026
robot-clickhouse and others added 4 commits July 29, 2026 17:08
# Conflicts:
#	src/Parsers/ASTSelectWithUnionQuery.cpp
`ParserSubquery` only ever stores an `ASTSelectWithUnionQuery` as the single child
of an `ASTSubquery`: the plain form comes from `ParserSelectWithUnionQuery`, which
never yields another node type, and the `EXPLAIN` / `VALUES` forms are rewritten
into `SELECT * FROM viewExplain(...)` / `SELECT * FROM SQLStandardValues(...)`,
which are select-with-union queries as well.

`ASTSubquery::readJSON` validated only the number of children, so a malformed
`clickhouse_json` payload could store any node type there. `interpretSubquery`
forwards `children.at(0)` to `InterpreterSelectWithUnionQuery`, whose constructor
dereferences `query_ptr->as<ASTSelectWithUnionQuery>()` without a null check, so
such a payload reached a null dereference with the old analyzer (the new analyzer
rejects it in `buildSelectOrUnionExpression` with `UNSUPPORTED_METHOD`).

Read the children through `readChildrenOfType<ASTSelectWithUnionQuery>` instead,
so the payload is rejected with `BAD_ARGUMENTS` at the deserialization boundary.

Addresses the AI review finding on `src/Parsers/ASTSubquery.cpp`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Merging `master` moved this branch onto 26.8, which is where
`allow_experimental_json_ast_dialect` is already recorded in the settings history,
so `parseQueryToJSON` and `formatQueryFromJSON` must report the same version.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The last statement of `04656_ast_json_subquery_child_query_shape` substituted the
subquery's child through `replace` and expected `BAD_ARGUMENTS`, but it anchored the
substitution on `"union_mode":"UNION_ALL"`. The parser never assigns `union_mode` - it
leaves the default `UNION_DEFAULT` and records `UNION ALL` in `list_of_modes`, and only
interpreter-stage passes such as `NormalizeSelectWithUnionQueryVisitor` set it. The
anchor therefore matched nothing, the payload reached `formatQueryFromJSON` unmodified,
and the statement succeeded instead of failing.

Anchor the substitution on the `Subquery` node itself, which does not depend on union
modes, and assert the anchor separately so that a change to the serialization fails
loudly instead of quietly turning the check into a no-op.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100412&sha=47e3c9113c5f0152b879999d4fec0a9231e5c336&name_0=PR&name_1=Fast%20test
Related: #100412

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
settings = r.readChildOfType<ASTSetQuery>("settings");
if (settings)
children.push_back(settings);
cluster_host_ids = r.readChild("cluster_host_ids");

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.

cluster_host_ids is not a free-form child. ParserBackupQuery::parseClusterHostIDs only accepts [...] or array(...), and it stores that AST separately from ordinary SETTINGS changes. Restoring it through generic readChild means malformed JSON like "cluster_host_ids":{"type":"Literal","value":{"field_type":"UInt64","value":1}} still passes here, formatQueryFromJSON emits SETTINGS cluster_host_ids = 1, and reparsing that text no longer reconstructs query.cluster_host_ids: ParserBackupQuery::parseSettings falls through to the generic ASTSetQuery path, so BackupSettings::fromBackupQuery stops treating it as the special host-id map.

Please validate this slot against the parser-owned shape up front (the same array / array(...) forms that parseClusterHostIDs accepts) and reject everything else with BAD_ARGUMENTS.

if (r.has("offset_to_drop"))
offset_to_drop = r.getUInt("offset_to_drop");
backup_name = r.getString("backup_name");
backup_source = r.readChild("backup_source");

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.

backup_source here is parser-owned too: ParserSystemQuery only fills it for SYSTEM UNLOCK_SNAPSHOT ... FROM <backup>, and the FROM target is parsed with ParserIdentifierWithOptionalParameters (an ASTFunction, not an arbitrary AST). Restoring it through generic readChild still accepts malformed payloads, so formatQueryFromJSON can emit parser-impossible SQL such as SYSTEM UNLOCK_SNAPSHOT 'snap' FROM 1 or ... FROM (SELECT 1) instead of rejecting the JSON at the boundary.

Please require the parser-produced backup-name shape here before accepting the child.

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 4627/5440 (85.06%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 30, 2026
Merged via the queue into master with commit 862deaa Jul 30, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the ast-json-serialization branch July 30, 2026 08:28
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 30, 2026
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Aug 5, 2026
The reviewer noted that with the gate on, the only HTTP request in
`04057_dialect_clickhouse_json.sh` was the plain-SQL `SET` escape hatch, so a
regression in the `clickhouse_json` branch of `executeQueryImpl` - in particular
in its `BAD_ARGUMENTS` validation - could leave the test green. The objection
was previously declined only because `dialect = 'clickhouse_json'` did not exist
on `master`; now that ClickHouse#100412 has been merged, the coverage can be added here.

Four gate-on HTTP requests are added: a round-trip `parseQueryToJSON` body that
must execute, and malformed JSON, an empty object and an unknown `type`, which
must each be rejected server-side with `BAD_ARGUMENTS`. The three error bodies
are rejected by the client's own parse in the existing cases, so they never
reached the server's validation before.

The whole test passes locally against `master` (6/6 runs with randomized
settings, plus the new cases 3/3).
vanchaklar pushed a commit to vanchaklar/ClickHouse that referenced this pull request Aug 7, 2026
…ect`

The `allow_experimental_` prefix is the pre-tier way of gating a feature. The `EXPERIMENTAL` tier in the setting declaration already carries that information (it is exposed as `tier` in `system.settings`), so the prefix duplicates it in the one place that is expensive to change later: the name. When the feature graduates, a prefixed name has to be renamed and the old spelling carried as an alias forever, which is why the tree already holds `allow_experimental_analyzer` -> `enable_analyzer`, `allow_experimental_nullable_tuple_type` -> `enable_nullable_tuple_type` and `allow_experimental_database_iceberg` -> `allow_database_iceberg`.

The setting was added in ClickHouse#100412 and has not shipped in any release: its `SettingsChangesHistory` entry is in the unreleased `26.8` block, so this is a plain rename with no alias and no compatibility entry.

The name also loses the `allow_` prefix, so it is no longer in scope for the `allow_*` coverage check in `ci/jobs/scripts/check_style/check_cpp.sh`, which verifies that every `allow_*` setting is either enabled by `enableAllExperimentalSettings` or listed as an exception. Its exception line is therefore removed: keeping it would leave the name in the exception list while it no longer exists in `Settings.cpp`, which the check reports. This gate has nothing to do with re-creating tables in `DatabaseReplicated::recoverLostReplica`, which is why it was an exception rather than an entry in `enableAllExperimentalSettings`.

The autogenerated settings reference pages still spell the old name; they are regenerated from the binary by the nightly docs job.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 8, 2026
…_engine

Master renamed `allow_experimental_json_ast_dialect` to
`enable_json_ast_dialect` in 3a5c031 (ClickHouse#113480). That commit updated
every in-tree caller, but this test is not on master yet, so the merge of
master into this branch was textually clean while leaving the test setting a
name that no longer exists: `SET` would fail with UNKNOWN_SETTING and case (s)
of the test - the engine clause round-tripping through the `clickhouse_json`
AST dialect - would never run.

The rename carries no alias: the setting was added in ClickHouse#100412 and its
SettingsChangesHistory entry is still in the unreleased 26.8 block, so the old
spelling is simply gone.
nagyist pushed a commit to nagyist/ClickHouse that referenced this pull request Aug 10, 2026
…son_ast_dialect`

Per @alexey-milovidov directive on ClickHouse#100412 (2026-05-07): "We should have
tests for `allow_experimental_json_ast_dialect` and `dialect = 'clickhouse_json'`".

Adds `tests/queries/0_stateless/04057_dialect_clickhouse_json.sh` covering:

* Default values of both settings.
* The experimental gate is checked at parse time, on both client-side
  TCP path (`ClientBase::parseQuery`) and server-side HTTP path
  (`executeQueryImpl`). With the gate off, both paths reject queries
  under `dialect = 'clickhouse_json'` with `SUPPORT_IS_DISABLED` and
  the error message points to the gate setting.
* Hand-written JSON-AST execution (`SELECT 1`).
* Round-trip via `parseQueryToJSON`: the JSON output of common SQL
  shapes (arithmetic, aliases, `FROM numbers` + `WHERE`/`ORDER BY`,
  `GROUP BY` + aggregates) is submitted under the dialect and produces
  the same result as the SQL form.
* Server-side escape hatch: a query starting with `SET` is parsed as
  plain SQL even under `dialect = 'clickhouse_json'`, so users can
  switch the dialect back without sending a JSON-AST `SET`.
* Error paths: malformed JSON, empty `{}`, and unknown `type` all
  raise `BAD_ARGUMENTS`.

Verified locally: 50/50 passes with full random settings.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
nagyist pushed a commit to nagyist/ClickHouse that referenced this pull request Aug 10, 2026
…-clickhouse-json-dialect-clean

Tests for the `clickhouse_json` dialect (follow-up to ClickHouse#100412)
alexey-milovidov added a commit that referenced this pull request Aug 12, 2026
The skill is driven headless by `utils/continue-all-prs.sh`, where an
`AskUserQuestion` (or a "note it for the user to decide") can't be answered and
just strands the PR - e.g. it declined to advance
#100412 instead of merging and
pushing.

Make the skill run unattended:
- Remove `AskUserQuestion` from `allowed-tools`; a missing PR number now errors
  out instead of prompting.
- Resolve merge conflicts autonomously (best judgment, recorded in the merge
  commit) and never wait for input; treat a `CONFLICTING`/unknown mergeability
  state as a reason to merge.
- Pushing after committing conflict resolutions or fixes is mandatory and must
  not be deferred or gated on a question.
- For a reviewer suggestion that seems wrong, make the best-judgment change or
  post a reasoned reply and continue, rather than deferring to the user.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The previous merge from master left an unresolved conflict marker that
caused style check, fast test, and `arm_tidy` builds to fail. Keep both
sides of the conflict: this PR's `allow_experimental_json_ast_dialect`
entry and master's `use_skip_indexes_for_top_k` /
`use_top_k_dynamic_filtering` entries.

CI report: ClickHouse#100412

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The `clickhouse_json` dialect deserializes AST nodes from JSON via `readJSON`.
Several nodes carry fields that the SQL parser only ever sets in mutually
exclusive combinations, but `readJSON` restored them as independent inputs.
That let a JSON AST hold a parser-impossible state whose displayed SQL diverges
from the operation actually executed:

- `ASTCheckTableQuery`: `partition` and `part_name` come from the exclusive
  `PARTITION <expr>` / `PART '<name>'` clauses. With both set, `formatQueryImpl`
  prints two clauses while `getPartitionOrPartitionID` returns only `partition`.
- `ASTKillQueryQuery`: `sync` and `test` come from the exclusive `SYNC` / `ASYNC`
  / `TEST` modes. For `KILL PART_MOVE_TO_SHARD`, `sync && test` displays as `TEST`
  while `InterpreterKillQueryQuery` checks `sync` first and runs the unsupported
  sync variant.
- `ASTSystemQuery`: for `SYSTEM DROP REPLICA ... FROM ZKPATH`, the parser derives
  `zk_name` and `replica_zk_path` from `full_replica_zk_path` (one invariant).
  `formatImpl` prints `full_replica_zk_path` while `dropReplica` /
  `dropDatabaseReplica` operate on `replica_zk_path` / `zk_name`, so independent
  values let the displayed and executed ZooKeeper paths disagree.

`readJSON` now rejects these shapes with `BAD_ARGUMENTS` at the JSON boundary
(re-deriving the ZooKeeper fields with the same `zkutil` helpers the parser uses),
so malformed `clickhouse_json` fails closed instead of executing a different query
than it displays.

Addresses review feedback:
ClickHouse#100412 (review)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Manerone added a commit that referenced this pull request Oct 1, 2026
Resolve the conflicts of the cherry-pick of #122673 to 26.7. The branch has
neither `isSecretKey` from #112070 nor the AST JSON serialization from #100412,
so hide `headers` and `header` through a local `isSecretKey` helper used by
`ASTPair::formatImpl` and `ASTPair::hasSecretParts`, and drop the `readJSON`
change, the documentation change and the `clickhouse_json` test.

Original pull request: #122673

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Manerone added a commit that referenced this pull request Oct 1, 2026
Resolve the conflicts of the cherry-pick of #122673 to 26.3. The branch has
neither `isSecretKey` from #112070 nor the AST JSON serialization from #100412,
so hide `headers` and `header` through a local `isSecretKey` helper used by
`ASTPair::formatImpl` and `ASTPair::hasSecretParts`, and drop the `readJSON`
change, the documentation change and the `clickhouse_json` test.

26.3 does not accept an array literal as a dictionary source parameter, so
remove the `d_05141_array` case from the test: it would be a syntax error, and
unparsable queries are logged as written.

Original pull request: #122673

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature 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