Skip to content

Add JSON AST SQL parser and execution libFuzzer harnesses - #121057

Open
qoega wants to merge 43 commits into
ClickHouse:masterfrom
qoega:json-fuzz-group7-harness
Open

qoega wants to merge 43 commits into
ClickHouse:masterfrom
qoega:json-fuzz-group7-harness

Conversation

@qoega

@qoega qoega commented Sep 19, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

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

Add two structure-aware libFuzzer harnesses for the SQL parser and query executor: json_ast_sql_parser_fuzzer (round-trips JSON AST through the SQL parser) and json_ast_sql_execution_fuzzer (executes generated SQL in an in-process clickhouse local with a differential oracle across multiple execution variants). Both build only under ENABLE_FUZZING.

Documentation entry for user-facing changes

No documentation change needed.

Detailed description / Documentation

Adds the JSON-AST-based structure-aware SQL fuzzers that surfaced the fixes bundled in the sibling PRs (#121047, #121049, #121052, #121053, #121054, #121055, #121056), the tracking issues #120737-#120742, #121021-#121028, #121045, and the follow-up issues #120743, #120795, #121019, #121020.

Highlights:

  • src/Parsers/fuzzers/json_ast_sql_parser_fuzzer/ — libFuzzer harness that mutates a JSON AST, deserializes it back through formatQueryFromJSON, and either accepts the resulting SQL, exercises the parser with a strict re-parse round-trip (JSON_AST_FUZZER_STRICT=reparse), or flags divergences. Includes generated seed corpus, keyword and function vocabularies, and an ErrorCodes-based expected-error filter (INVALID_USAGE_OF_INPUT is expected, etc.).
  • programs/local/fuzzers/ + src/Parsers/fuzzers/json_ast_sql_execution_fuzzer/ — executes the generated SQL in an in-process clickhouse local. Runs the same query across several execution variants (default, forced JIT, parallel + spilling + alternative join algorithms, etc.) and reports a mismatch when the results differ. Includes settings/function vocabularies, per-query time and row caps, fast S3/network failure, deterministic-only oracle filtering (excludes now(), UUIDv7, arrayShuffle, formatRow, viewExplain, obfuscateQuery, etc.), FP rounding, and an aggregate-alias normalizer.
  • tests/fuzz/json_ast_sql_parser_fuzzer.{in,options} and tests/fuzz/json_ast_sql_execution_fuzzer.options — starter corpora and libFuzzer options.
  • Seed corpus is built from the functional test suite via src/Parsers/fuzzers/json_ast_sql_parser_fuzzer/generate_seed_corpus.py.

Both harnesses build under ENABLE_FUZZING only and add no runtime cost to non-fuzzing builds.

Note: tests/fuzz/json_ast_sql_execution_fuzzer.options relies on the clickhouse local --logger.level fix in the sibling PR #121053; without it, worker logs grow to hundreds of MB per hour.

Related PRs (sibling bug fixes from the same fuzzer campaign): #121047, #121049, #121052, #121053, #121054, #121055, #121056.

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

🤖 Generated with Claude Code


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

qoega and others added 30 commits September 19, 2026 19:03
…rser via the JSON AST

A libFuzzer target whose input is a binary protobuf message (`json_ast.proto`) mirroring the
native JSON AST representation. libprotobuf-mutator mutates it structurally; the target renders
it as JSON, deserializes it with `IAST::createFromJSON` under depth/element limits, formats the
AST as SQL, parses the SQL with `ParserQuery`, then formats and parses once more to exercise
round-trip stability.

Property keys and enumeration-like string values are protobuf enums, so mutations always yield
names the `readJSON` implementations know, while the value kind of a property is chosen through a
`oneof` (the same key has different kinds in different node types). Expected outcomes (rejected
JSON, rejected ASTs, syntax errors) are counted per stage; anything else, including
`LOGICAL_ERROR` and non-`DB::Exception` exceptions, aborts with the JSON and SQL printed.

Also adds `json_ast_seed_converter` (JSON <-> protobuf), `generate_seed_corpus.py` with a
coverage-oriented `seed_queries.sql` (191 statements), the committed binary seed corpus in
`tests/fuzz/json_ast_sql_parser_fuzzer.in`, libFuzzer options, a README covering the schema,
build, reproduction (`JSON_AST_FUZZER_DUMP`) and corpus minimization, and a note in the testing docs.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…cess clickhouse local

The structure-aware pipeline of `json_ast_sql_parser_fuzzer` (protobuf -> JSON AST -> `IAST` -> SQL)
is moved into `JSONASTFuzzerPipeline.{h,cpp}` in the shared `json_ast_fuzzer_proto` library, and a
second target executes the generated SQL instead of re-parsing it.

`programs/local/fuzzers/clickhouse_fuzzer.cpp` is split: the runner-thread harness (in-process
`clickhouse local`, SIGALRM forwarding, runner stack dump) becomes the `LocalFuzzerRunner` library,
with a `setup_queries` hook executed before the first input and an optional per-query error print
(`CLICKHOUSE_FUZZER_PRINT_QUERY_ERRORS=1`). `clickhouse_fuzzer` keeps its behaviour on top of it.

`json_ast_sql_execution_fuzzer` loads the fixture `json_ast_sql_execution_fuzzer_schema.sql`
(embedded at build time): a `MergeTree` table with ~40 columns over the scalar, nullable, array,
tuple, map, nested, `JSON`, `Dynamic`, `Variant`, decimal and IP types with skip indexes and a
projection, smaller tables for joins and window functions, `Log`, `Null`, `Join` and `Set` tables, a
view, a materialized view and a dictionary; it ends with `SET readonly = 2`. Only `SELECT`,
`EXPLAIN`, `SHOW` and `CHECK TABLE` statements are executed. The fixture's table and column names
are added to the `KnownString` vocabulary of `json_ast.proto`, so mutated queries reference real
objects and reach the analyzer, planner and processors. The target consumes the same seed corpus as
the parser fuzzer.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…fuzzed queries

Mutations of the seeds produce unbounded sources (`numbers()`, `generateRandom()`), which ran until
`max_execution_time` on every input and dominated the session. Pass `--max_rows_to_read`,
`--max_bytes_to_read` and a five second `--max_execution_time` to `clickhouse local`, use `Null`
output, and disable libFuzzer's per-input leak check: the one-time AWS SDK initialization behind the
`s3` table function is reported as a leak on the first input that uses it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…y cap, run mode notes

Measured on the accumulated corpus: a query costs ~0.3 s in the sanitizer build, but mutants that
call `mysql`, `remote` or `url` waited for the default connection timeouts and every timed-out query
cost the full `max_execution_time`, so sessions ran at three queries per second. Pass one to two
second connection, read and external-storage timeouts and cap a query at two seconds. Document that
`-jobs/-workers` should be preferred over `-fork` for this target (fork jobs reload the fixture and
replay the whole corpus).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…l settings in execution options

Add `FunctionName` (all functions and aggregate functions from `system.functions`) and
`SettingName` (settings with non-string values) enums to `json_ast.proto` as additional `Property`
value kinds, so a mutation of `Function.name` or of a `SETTINGS` entry produces a real name instead
of a random string; `json_ast_seed_converter` maps `name` properties onto them. Regenerate the seed
corpus and enable a few experimental features in the execution fuzzer options.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…utput

A string literal may carry arbitrary bytes into the JSON; treat the output as bytes and count an
undecodable document as a failure instead of aborting the whole run.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
A mutated `s3(...)` call pointing at a closed port made the query outlive the two second execution
time cap by more than a minute: cancellation waits for the S3 client, which retries the connection
hundreds of times by default. Pass single-attempt retry settings and short S3 timeouts.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…console fatal logging

Crash-only execution fuzzing found nothing in ~250k queries, so add a wrong-result oracle: every
deterministic `SELECT` (a conservative filter rejects randomness, time, ordering-dependent and
approximate aggregates, floats, `LIMIT`, window functions, ...) is executed twice more inside the same
`clickhouse local`, with the default plan and with the planner optimizations disabled and
`max_block_size = 1`, both single-threaded; the row count and an order-independent row hash must
match. Mismatches and error asymmetries are appended to `oracle_mismatches.log` with the SQL and the
JSON AST and counted; they do not stop the session. `LocalFuzzerRunner` gets `runOnRunnerThread` to
execute such tasks with the session context (on a dedicated thread with its own `ThreadStatus`).

`clickhouse local` installs its own fatal signal handler, which replaces libFuzzer's: an abort inside
a query ended the process silently and without an artifact. The options now enable console logging
of fatals, and the JSON and SQL of the input being executed are written to `json_ast_last_input.txt`
before every execution.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Calibration over 5441 fuzzed inputs (1467 oracle checks) produced no mismatch, so deterministic
functions that were excluded out of caution (date and time conversions, `dictGet`, `ARRAY JOIN`,
`hex`, `toTypeName`, `INTERVAL`, `JSON`/`Dynamic`/`Variant` types) are allowed again. Floating point
aggregation and the plan-dependent functions stay excluded.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…s viewExplain and arrayShuffle

`PullingPipelineExecutor::pull` returns false without throwing once the soft time limit is hit and
leaves it to the caller to raise `TIMEOUT_EXCEEDED`; the oracle compared the partial results of two
slow runs instead. `viewExplain` output legitimately depends on the settings, and a seeded
`arrayShuffle` is seeded per block (reported separately), so both are excluded from the oracle.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… spilling and other join algorithms

Every deterministic SELECT is now also executed with eight threads, seven-row blocks, two-level and
external aggregation and sorting, grace hash and partial merge joins and a few analyzer rewrites
disabled; the multiset of rows must still match the default plan.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…gregate aliases

`array_agg` (an alias of `groupArray`) slipped through the order-dependence filter. Compare in
lower case, add the aliases of the ordering-dependent and sampling aggregates, and match the SQL
keywords as whole words so that e.g. `formatDateTime` is not excluded by `FORMAT`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… in the oracle

Top-level Float32/Float64 (and Nullable of them) values are hashed rounded to nine significant
digits, so sums, averages and divisions are compared across the variants instead of being excluded;
queries whose nested types contain floats are skipped.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ilation

The default plan only compiles expressions after a few repetitions, so a single fuzzed query never
exercises the JIT. The new variant sets the compile thresholds to zero, forces short-circuit
evaluation and disables lazy materialization.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… names after every mutation

A libprotobuf-mutator post-processor replaces table names that are not in the fixture with fixture
tables, unknown column names with fixture columns and unknown function names with real functions,
leaving one mutation in ten untouched, so that mutants reach execution instead of failing on name
resolution. `JSON_AST_FUZZER_NO_FIXUP=1` disables it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…input, not only to mutations

Seeds mined from the test suite reference their own tables and columns; rewriting them deterministically
(seeded by the serialized input) before execution lets them resolve against the fixture.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…dent functions in the oracle filter

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The rewrite now picks columns of the fixture table the query references and keeps aliases defined
in the query, but measured on 600 seeds mined from the test suite it still increases the number of
failing queries (244 -> 296): lambda parameters, CTE names and aggregate combinators such as
`sumIf` are renamed too, and columns of the wrong type are chosen. It is therefore disabled by
default and enabled with `JSON_AST_FUZZER_FIXUP=1`, for experiments with a type-aware version.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…non-fixture objects

Replace `readonly = 2` with a statement policy: read-only statements always run; `CREATE`, `DROP`,
`ALTER`, `RENAME`, `INSERT`, `OPTIMIZE`, `DELETE`, `UPDATE`, index and SQL function statements run
when their target is not a fixture object (they may read from the fixture); `SYSTEM`, `SET`, `USE`,
`KILL`, `BACKUP`/`RESTORE`, database-level operations and `INTO OUTFILE` never. Every 200 modifying
statements the fuzzer drops the tables, databases and functions it created.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`generate_seed_corpus.py --from-tests DIR --shard I/N` extracts every distinct
statement of the `*.sql` functional tests (~90k) and converts a shard of them to
protobuf seeds, so the corpus can be generated in parallel. The README documents
the workflow and the `-merge=1` step that condenses the seeds before fuzzing.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…or limit-hitting baseline

A corpus replay showed that a quarter of all query errors were `TIMEOUT_EXCEEDED`
and another fifth `TOO_MANY_ROWS`; the oracle then ran three more variants of the
same query, each burning the full `max_execution_time`. The variants are compared
only when both sides finish and resource-limit errors are ignored anyway, so the
default plan now runs first and the variants are skipped when it hit a limit or
took more than 0.7 s. The exit statistics report how often that happened.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…se outcome

`ParserExplainQuery` validates the `input` table function of an explained `INSERT`
while parsing, so `EXPLAIN SYNTAX INSERT ... SELECT input(...) FROM input(...)` throws
`INVALID_USAGE_OF_INPUT` from the parser by design.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… oracle

`formatRow` with a format that has a prefix and suffix (`XML`, `JSON`) embeds the
format's statistics (`elapsed`, `rows_read`) into every row, so the row text depends
on timing and on the block size.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Aborts only when SQL accepted by the parser formats into SQL the parser rejects,
the rarest and most interesting of the three strict-mode outcomes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…stic functions in the oracle filter

`SELECT now FROM t` calls `now()`; the filter looked for `now(` only.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
An earlier commit on this branch deleted this file. Undo the deletion
so this PR builds standalone: the referenced factory entry in
`src/Parsers/ASTFromJSON.cpp` will keep the file live until the
JSON-AST hardening PR removes the entry.

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

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9a5e618]

Summary: ❌

job_name test_name status info comment
Style check FAIL
cpp FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added pr-build Pull request with build/testing/packaging improvement comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). labels Sep 19, 2026
qoega and others added 6 commits September 21, 2026 23:07
…at the end of a session

libFuzzer ends a session with `exit`, whose static destructors raced the still
running `clickhouse local` threads and aborted the process at the deadline.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…e oracle

Random by design, and slow enough under sanitizers to time out when run five times.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ceptions as query errors

`executeQuery` lets them through and the server reports them as `POCO_EXCEPTION`
or `STD_EXCEPTION`; the oracle thread terminated the process on them instead.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…e resource limits

A fuzzed `SETTINGS max_memory_usage = 0` let `generateRandom` request a 64 GiB block
and took a worker down; statements mentioning a resource-limit setting are skipped.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… in the oracle filter

`SELECT localtime` is `now()`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…try settings are not executed

Co-Authored-By: Claude Fable 5.1 <[email protected]>
qoega and others added 4 commits September 22, 2026 19:06
libFuzzer ends a session with `exit` on its own thread. Function-local
singletons created during the run (for example `S3::ClientCacheRegistry`) are
destroyed before the runner's `atexit` handler, so letting `clickhouse local`
run `LocalServer::cleanup` from that handler dereferenced destroyed objects:
UBSan `applying non-zero offset 8 to null pointer` in
`ClientCacheRegistry::unregisterClient` from `~S3ObjectStorage` while the
tables created by the inputs were dropped, an abort and an empty-input
`crash-da39a3ee...` artifact at the end of every session that had created an
S3 table. Reproduced with `-max_total_time=45` on the execution fuzzer.

The runner is idle at that point; the handler now flushes and leaves with
`_exit`. Targets register their statistics printers after
`LocalFuzzerRunner::initialize`, so they still run (the execution fuzzer is
reordered accordingly and its own `_exit` handler is gone). The temporary
directory of `clickhouse local` (a few hundred KB) is left behind, as it was
already after a `-rss_limit_mb` stop.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The fuzzer executed `SELECT * FROM deltaLake('https://.../delta_lake/hits/',
...)`, which reaches a real S3 endpoint and, on a bogus table, panics inside
the Rust `delta_kernel` FFI. ASan reports the Rust unwinder's register-context
`memset` as a `stack-buffer-underflow` in `_Unwind_Resume` (a false positive
over the custom unwinder, as the report's own HINT notes), aborting the
session.

The harness configures no object storage, external server or database, so
every external or network table function only makes an unwanted outbound
request, blocks on the network timeout, or trips this false positive, without
exercising the SQL layer. Skip any statement mentioning one
(`usesExternalTableFunction`): data-lake (`deltaLake`/`iceberg*`/`hudi`),
object storage (`s3`/`gcs`/`azureBlobStorage`/`hdfs`/...), `url`/`remote`/
`cluster`, external databases and streaming engines, `file`. The oracle
already excluded `url`/`s3`/`remote`/`cluster`; this covers the main
execution path and the data-lake functions.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…nput timeout

`cleanupFuzzerObjects` drops every non-fixture object with one `DROP ... SYNC`
each. Running it once per 200 modifying statements let up to 200 objects
accumulate; on the ASan build a single cleanup ran for 166 s and tripped
libFuzzer's 120 s per-input timeout (the timeout stack is entirely inside the
cleanup's DROP loop). Drop every 40 modifying statements instead, so a cleanup
stays well under the budget.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…annot time out

Even with small cleanup batches, a single `DROP ... SYNC` can block in the
storage's `shutdown` (it joins the engine's background threads): a
`Distributed` table flushing to an unreachable host, a `Kafka`/`RabbitMQ`/
`NATS` consumer, a dictionary reloading from a dead source. One such drop ran
for 155 s and tripped libFuzzer's 120 s per-input timeout, with the whole
stack inside `cleanupFuzzerObjects`.

Run the drops on a worker that holds its own copy of the context and give up
after a bounded 30 s wait: a stuck cleanup detaches the worker, leaks its
objects into the rest of the session (which ends soon on its time or RSS
limit, each worker process starting from a fresh fixture) and is not attempted
again, instead of aborting the session.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-testing Test content only (no production code). and removed comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). labels Sep 22, 2026
qoega and others added 3 commits September 25, 2026 09:20
…in the oracle

stochasticLinearRegression/stochasticLogisticRegression (and their State
combinators) run SGD, whose serialized state depends on the aggregation and
thread order, so the single-threaded default and the parallel/external variant
legitimately differ (the state also carries NaN weights when it does not
converge). Add "stochastic" to the oracle's non-deterministic exclusion list.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…s in the oracle

optimize_group_by_function_keys (on by default) drops a GROUP BY key that is a
function of other keys. When such a redundant key throws (e.g.
`(number%2) % (number%3)` divides by zero), the default plan never evaluates it
and succeeds, while the flipped variant keeps the key and raises. That is a
valid optimization eliminating a throwing subexpression, not a bug, but it made
the oracle report a plan-dependent error asymmetry. Disable it in the baseline
and parallel variants (flipped already had it off, jit inherits the baseline)
so all four agree.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
arrayWithConstant/arrayResize/replicate with a huge caller-supplied size are
constant-folded at plan time, which ignores max_execution_time and
max_memory_usage, so a single call (e.g. arrayWithConstant(96142475, [])) runs
for minutes and trips the per-input timeout. range/timeSeriesRange are already
bounded by function_range_max_elements_in_block; these have no such setting, so
skip statements that mention them.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-fuzzing Fuzzers: BuzzHouse (the query generator in the client), the AST fuzzer (QueryFuzzer), and the lib... and removed comp-testing Test content only (no production code). labels Nov 19, 2026

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-fuzzing Fuzzers: BuzzHouse (the query generator in the client), the AST fuzzer (QueryFuzzer), and the lib... fuzz Problem found by one of the fuzzers pr-build Pull request with build/testing/packaging improvement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant