Repository navigation
AST JSON serialization - #100412
AST JSON serialization#100412
Conversation
|
Workflow [PR], commit [a61319a] Summary: ✅
AI ReviewSummaryThis PR adds JSON AST serialization/deserialization, the Findings
Tests
Final VerdictStatus: Minimum required actions: validate |
…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.
# 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"); |
There was a problem hiding this comment.
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"); |
There was a problem hiding this comment.
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 4627/5440 (85.06%) · Uncovered code |
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).
…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.
…_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.
…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]>
…-clickhouse-json-dialect-clean Tests for the `clickhouse_json` dialect (follow-up to ClickHouse#100412)
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]>
…rammatically` to aspell dictionary CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100412&sha=b15b5a9f9280d5dddf9542f5d447f802f522e704&name_0=PR&name_1=Style%20check PR: ClickHouse#100412 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
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]>
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]>
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]>
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]>
Changelog category (leave one):
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()andformatQueryFromJSON()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_jsonmode (guarded byallow_experimental_json_ast_dialect) that accepts JSON AST directly;executeQuery,ClientBase, andLocalConnectionroute parsing throughIAST::createFromJSONwith newmax_ast_depth/max_ast_elementslimits and aSET-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 inASTFromJSON, 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.