Skip to content

Bound the AST fuzzer oracle's sub-query output while it is formatted - #125414

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:ast-fuzzer-oracle-bound-output
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:ast-fuzzer-oracle-bound-output

Conversation

@groeneai

@groeneai groeneai commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Description

Related: #122508
Related: #117916

Asked by @ alexey-milovidov on #122508: AST fuzzer (amd_release, oracle) fails with OOM in dmesg, the server reaching ~53 GB RSS against a 40.33 GiB max_server_memory_usage:

In both runs the only active query was an oracle reference sub-query selecting a 1 MiB LowCardinality or constant FixedString from every row of a table.

The oracle formats each sub-query into an unbounded WriteBufferFromOwnString and checks MAX_ORACLE_OUTPUT_SIZE (10 MiB) only after the query finishes. The in-flight max_result_bytes counts in-memory chunk bytes, where such a column holds its value once per chunk, while every row formats to ~2 MiB of TabSeparated. The string grows through operator new, which is tracked but never refused while min_allocation_size_to_throw_on_memory_limit is 0 (#117916), so the memcg kills the server.

The oracle now collects the output in a WriteBuffer that throws TOO_MANY_BYTES as soon as it would exceed MAX_ORACLE_OUTPUT_SIZE. Both callers already treat TOO_MANY_BYTES as "skip this oracle", so the cap is unchanged and is only detected at 10 MiB instead of after tens of GiB; the dead post-execution check is removed. No test, as this is fuzzer-only code; the jobs above are the reproducer.

Validation (debug build, server in a 16 GiB cgroup, seeds such as SELECT DISTINCT i, d, toFixedString(toLowCardinality('0.000065535'), 1048575) FROM t WHERE d < '2020-01-05' with ast_fuzzer_runs = 1, ast_fuzzer_oracle = 1): on master this seed OOM-killed 3 of 3 fresh servers within ~44 s. With the fix the server survived 500 seed runs, in which all 122 such reference sub-queries stopped with TOO_MANY_BYTES, peak memory 2.6 GB; an 8.6 MB reference still passed TLP WHERE, and 04658_ast_fuzzer_oracle_tlp_aggregate_counter passed 20/20 with randomized settings.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 12, 2026 12:18
The oracle runs its sub-queries with `executeQuery(istr, ostr, ...)` into a
plain `WriteBufferFromOwnString` and compared the result with
`MAX_ORACLE_OUTPUT_SIZE` only after the query had finished. The only in-flight
cap, `max_result_bytes`, is checked by `LimitsCheckingTransform` against
in-memory chunk bytes: a `LowCardinality` or constant 1 MiB `FixedString` holds
its value once per chunk, while every row formats to ~2 MiB of TabSeparated
(each NUL is escaped as `\0`). The string grows through `operator new`, which
never refuses an allocation while `min_allocation_size_to_throw_on_memory_limit`
is 0 (ClickHouse#117916), so neither the fuzz context's `max_memory_usage` nor
`max_server_memory_usage` stops it, and the kernel memcg kills the server
("OOM in dmesg").

Seen in `AST fuzzer (amd_release, oracle)` on PR ClickHouse#122508 (sha 444c1ee, TLP
DISTINCT reference `SELECT DISTINCT i, date,
toFixedString(toLowCardinality('0.000065535'), 1048575) FROM
t_read_in_order__fuzz_0 ...`, ~53 GB RSS against a 40.33 GiB cap) and on
PR ClickHouse#113173 (sha cd98662, TLP WHERE reference).

Collect the output in a `WriteBuffer` that throws `TOO_MANY_BYTES` from
`nextImpl` as soon as the collected size would exceed the limit. Both callers
already map `TOO_MANY_BYTES` to "skipped", so the oracle contract is unchanged
and only the moment of detection moves; the post-execution size check is dead
and removed. `AutoCanceledWriteBuffer` cancels the buffer when a different
exception leaves it unfinalized.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the imprecise '(the output sits at exactly the cap)' parenthetical in makeOracleContext.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review (3 nits, none blocking).

# Sev Finding Verdict Evidence / action
1 💡 The makeOracleContext comment keeps "(the output sits at exactly the cap)", which mixes the in-memory max_result_bytes with the formatted-output cap AGREE parenthetical dropped in the comment-only trim commit
2 💡 executeAndCollectSortedRows and executeWithSettings repeat the same execute/collect block DISAGREE pre-existing; the new limit lives in one helper, and merging the bodies would conflict with #124547, which edits both
3 💡 ostr.str() is copied instead of moved DISAGREE the same bounded (10 MiB) copy as before, oracle-only

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261012-123000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Debug server in a 16 GiB cgroup, max_server_memory_usage 10 GB, CREATE TABLE t (i UInt64, d Date) ENGINE = MergeTree ORDER BY i with 100k rows, then the seed SET ast_fuzzer_runs = 1, ast_fuzzer_oracle = 1; SELECT DISTINCT i, d, toFixedString(toLowCardinality('0.000065535'), 1048575) FROM t WHERE d < '2020-01-05'. On master the server was OOM-killed on this seed on 3/3 fresh servers, ~44 s each.
b Root cause explained? The oracle formats each sub-query into an unbounded WriteBufferFromOwnString and checks MAX_ORACLE_OUTPUT_SIZE only after the query finishes. max_result_bytes counts in-memory chunk bytes, where a LowCardinality or constant 1 MiB FixedString is stored once per chunk, while each row formats to ~2 MiB of TSV. The string grows through operator new, which is tracked but never refused while min_allocation_size_to_throw_on_memory_limit is 0 (#117916), so the memcg kills the server.
c Fix matches root cause? Yes. The unbounded allocation is the oracle's own buffer, and it now throws TOO_MANY_BYTES from nextImpl at the existing cap. Engine-wide max_result_bytes / operator new semantics are untouched.
d Test intent preserved / new tests added? No new test: fuzzer-only code, and the failing CI jobs are the reproducer. The existing oracle test 04658_ast_fuzzer_oracle_tlp_aggregate_counter passes 20/20 with randomized settings.
e Both directions demonstrated? Master: 3/3 servers OOM-killed (kernel Memory cgroup out of memory, anon-rss 16.6 GB; the TLP DISTINCT reference was the only query). Fix: 500 seed runs, server alive, all 122 such reference sub-queries stopped with TOO_MANY_BYTES, cgroup peak 2.6 GB, 0 OOM events.
f Fix is general across code paths? Both functions that format oracle output into a string (executeAndCollectSortedRows, executeWithSettings) use the bounded buffer; executeAndCollectSortedUniqueRows delegates. executeScalar streams blocks, and the remaining WriteBufferFromOwnString uses format ASTs, not query output.
g Fix generalizes across inputs (params/datatypes/wrappers)? The cap is on formatted bytes, so it is independent of type: LowCardinality, constant, plain FixedString, long String, Array/Map literals. Output under the cap still compares: an 8.6 MB reference over 8+ buffer flushes passed TLP WHERE (100000 rows).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or on-disk change. The oracle only runs with the experimental ast_fuzzer_oracle, and over-cap results were already skipped.
i Invariants and contracts preserved? "Over the cap: skip, never compare partial results" is unchanged, and exactly at the cap still passes. A throw from nextImpl cancels the buffer in WriteBuffer::next; any other exception is cancelled by AutoCanceledWriteBuffer; str() finalizes only on success. Debug build: 0 LOGICAL_ERROR, 0 finalize/cancel errors, 0 <Fatal>.

Session id: cron:clickhouse-impl-slot-7:20261012-114500

@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5274e10]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
05350_comparison_tuple_elimination_shared_alias FAIL cidb
01513_optimize_aggregation_in_order_memory_long NOT_FAILED cidb
02884_create_view_with_sql_security_option NOT_FAILED cidb
02346_non_negative_derivative NOT_FAILED cidb

AI Review

Summary

This PR replaces the oracle's unbounded WriteBufferFromOwnString collectors with a capped WriteBuffer that throws TOO_MANY_BYTES once formatted sub-query output would exceed MAX_ORACLE_OUTPUT_SIZE, and it wires both row-collecting helpers to keep treating that condition as a skipped oracle run. The change matches the stated contract, removes the dead post-hoc size check, and I did not find a correctness, lifetime, or resource-management issue in the current diff.

Missing context / blind spots
  • ⚠️ Several CI jobs are still pending, so full-matrix build coverage is not available yet.
Final Verdict

✅ No blocking issues found.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Oct 12, 2026
@groeneai
groeneai requested review from nihalzp and qoega October 12, 2026 12:52
@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Oct 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5274e10

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05350_comparison_tuple_elimination_shared_alias not from this PR (it only changes the AST fuzzer oracle in QueryOracleChecker.cpp): NOT_FOUND_COLUMN_IN_BLOCK while executing Remote, the initiator expects __table1.n and the replica sends n; 121 of 121 reruns with the same settings passed #125195 (mine, open)
Mergeable Check, PR praktika rollups of the row above #125195 (mine, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261013-023009

@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

can be tested Allows running workflows for external contributors comp-fuzzing Fuzzers: BuzzHouse (the query generator in the client), the AST fuzzer (QueryFuzzer), and the lib... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant