Skip to content

Fix LOGICAL_ERROR in server AST fuzzer safety-limit stripping on desynced SETTINGS - #110394

Merged
alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-ast-fuzzer-strip-settings-desync
Sep 26, 2026
Merged

alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-ast-fuzzer-strip-settings-desync

Conversation

@groeneai

@groeneai groeneai commented Jul 14, 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

The server-side AST fuzzer strips its safety-limit settings (max_rows_to_read, max_execution_time, ...) from each fuzzed query so a fuzzed SETTINGS max_rows_to_read = 0 cannot lift the pinned resource caps. When stripping empties a SETTINGS clause, removeSettingsFromQuery detached the clause from its owner via IAST::reset, which hard-throws LOGICAL_ERROR "AST subtree not found in children" if the owner's settings slot is set but its pointer is not registered in children.

The AST fuzzer explicitly can produce such structurally-invalid ASTs (executeQuery.cpp only skips them at format time, and this strip runs before that guard), so the desync aborted the server in debug/sanitizer builds instead of being skipped. Found by BuzzHouse (amd_tsan):

stripFuzzerSafetyLimitSettings -> removeSettingsFromQuery (stripQuerySettings.cpp:140) -> IAST::reset (IAST.h:269).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109000&sha=8b77fe6ef18a638bcbc188de2e154324262cef13&name_0=PR&name_1=BuzzHouse%20%28amd_tsan%29

Fix: detach the emptied slot tolerantly (erase the child if present, then clear the slot) in the INSERT, ASTQueryWithOutput and ASTStorage branches, matching the already-tolerant SELECT (setExpression({})) and BACKUP (settings.reset()) branches. Adds a gtest that desyncs the settings slot from children for each affected carrier and asserts the strip no longer aborts.


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

Version info

  • Merged into: 26.10.1.782-master (included in 26.10 and later)

…nced SETTINGS

removeSettingsFromQuery detached an emptied SETTINGS clause via IAST::reset,
which hard-throws LOGICAL_ERROR "AST subtree not found in children" when the
owner's settings slot is set but its pointer is not registered in children.
The server-side AST fuzzer can produce exactly such structurally-invalid ASTs,
and this strip runs before the format-time try/catch that skips them, so the
desync aborted the server in debug/sanitizer builds.

Detach the slot tolerantly instead (erase the child if present, then clear the
slot) in the INSERT, ASTQueryWithOutput and ASTStorage branches, matching the
already-tolerant SELECT and BACKUP branches. Adds a gtest reproducing the
desync for each affected carrier.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. gtest RemoveSettingsFromQuery.ToleratesSettingsSlotDesyncedFromChildren desyncs the SETTINGS slot from children and calls removeSettingsFromQuery; aborts on pristine master at stripQuerySettings.cpp:140 -> IAST::reset (IAST.h:269), the exact CI stack (STID 1218-27e6).
b Root cause explained? IAST::reset(field) hard-throws LOGICAL_ERROR when field is set but its pointer is not in children. The server AST fuzzer produces structurally-invalid ASTs with the SETTINGS slot desynced from children; the strip runs before the format-time try/catch that skips such ASTs, so the throw aborts the server (debug/sanitizer).
c Fix matches root cause? Yes. Detach the slot tolerantly (erase child if present, then clear the slot) instead of IAST::reset, so a desynced node is detached rather than aborting.
d Test intent preserved / new tests added? New gtest added covering all three affected carriers (INSERT, ASTQueryWithOutput, ASTStorage). The 5 pre-existing RemoveSettingsFromQuery tests still pass (no weakening).
e Demonstrated both directions? Yes. Pristine source: test aborts with the CI LOGICAL_ERROR. With fix: all 6 RemoveSettingsFromQuery tests pass.
f Fix general, not a narrow patch? Yes. All three throwing detach branches (INSERT:107, ASTQueryWithOutput:140, ASTStorage:121) are made tolerant via a shared detachChild helper (ASTPtr + raw-pointer overloads); the SELECT and BACKUP branches were already tolerant.
g Generalizes across inputs? Covered every SETTINGS carrier that detaches: INSERT settings_ast, ASTQueryWithOutput settings_ast (SELECT-UNION/EXPLAIN/SHOW/CREATE AS SELECT), ASTStorage settings (raw ptr). SELECT/BACKUP already used tolerant paths.
h Backward compatible? N/A. Internal AST-fuzzer utility; no settings/format/on-disk/wire change.
i Invariants preserved? Yes. The tolerant detach removes the child if present (same as before for well-formed ASTs) and clears the slot; well-formed ASTs behave identically. Only the previously-aborting desync path now detaches cleanly.

Session id: cron:clickhouse-worker-slot-1:20260714-123500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @evillique — could you review? Small fix to the server-side AST fuzzer's safety-limit settings stripping (src/Parsers/stripQuerySettings.cpp, from #108212): IAST::reset aborted with a LOGICAL_ERROR when the fuzzer handed it an AST whose SETTINGS slot was desynced from children. Detaches tolerantly now, with a gtest per carrier.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dae698d]

Summary: ✅


AI Review

Summary

This PR hardens removeSettingsFromQuery so the server-side AST fuzzer can detach emptied SETTINGS clauses without throwing on desynced children, and adds focused parser tests for the affected carriers. The current merge view looks correct to me; I did not find any remaining correctness or evidence gaps in the code that would merge today.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit dae698d.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 81.10% 81.20% +0.10%

Changed lines: Changed C/C++ lines covered: 134/137 (97.81%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 14, 2026
Comment thread src/Parsers/tests/gtest_Parser.cpp Resolved
ASTStorage::settings is a bare ASTSetQuery* whose only owner is
ASTStorage::children. A fuzzer-mutated child list can drop that owning
intrusive_ptr while leaving the slot set, so the pointer may dangle.
removeSettingsFromQuery's ASTStorage branch dereferenced it
unconditionally, a use-after-free. Guard the deref with a pointer-value
check that the slot is still backed by children (never dereferencing the
possibly-dangling pointer); clear the slot otherwise.

The ToleratesSettingsSlotDesyncedFromChildren gtest erased the matching
child for the ASTStorage carrier without keeping an owning ASTPtr alive,
which freed the node and made the test itself a use-after-free rather
than a desynced-but-live slot. Keep an owning ASTPtr for every erased
settings node alive for the test body, so the test exercises the
desynced-not-freed path (and now the storage guard's backed-by-children
branch) without constructing a UAF.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A gtest that frees the ASTStorage settings node (drops the last owning intrusive_ptr from children while leaving the raw slot set) then calls removeSettingsFromQuery reproduces the UAF on demand: under ASan the pre-guard code aborts with heap-use-after-free READ of size 8 at the *storage->settings deref.
b Root cause explained? ASTStorage::settings is a bare ASTSetQuery * whose only owner is ASTStorage::children. The server AST fuzzer can mutate the child list so the owning intrusive_ptr is dropped while the raw slot stays set, leaving it dangling. The ASTStorage branch dereferenced *storage->settings unconditionally, so a fuzzer-supplied desynced-then-freed slot is a production use-after-free.
c Fix matches root cause? Yes. Before any deref, isBackedByChildren(*storage, storage->settings) does a pointer-value comparison against children (never dereferencing the possibly-dangling pointer). If backed, strip/prune as before; otherwise just clear the slot (the node is already gone from the tree, nothing re-serializes it).
d Test intent preserved / new tests? Yes. The existing ToleratesSettingsSlotDesyncedFromChildren now keeps an owning ASTPtr alive for each erased settings node, so it exercises the desynced-but-live path (and the storage guard's backed-by-children branch) instead of constructing a UAF. It still asserts no-throw and that the safety setting is gone.
e Demonstrated both directions? Yes, under ASan. Freed-slot case: aborts with heap-use-after-free without the guard, passes with it. All 6 RemoveSettingsFromQuery tests pass clean under ASan with the fix.
f Fix general, not a narrow patch? Yes. The other SETTINGS carriers were audited: INSERT and ASTQueryWithOutput hold the slot as an owning ASTPtr (settings_ast), so a dropped child keeps the node alive (no dangling deref possible); BACKUP holds settings outside children and resets it directly. ASTStorage was the only carrier holding the slot as a bare pointer owned solely by children, and it is now guarded.
g Generalizes across inputs? The guard is input-agnostic: it depends only on whether the raw slot is present in children, so it covers any fuzzed ASTStorage regardless of engine, settings contents, or how the child list was mutated (dropped, reordered, replaced).
h Backward compatible? Yes. No setting default, on-disk/wire format, or user-visible behavior changes. This only hardens an internal fuzzer-path transform against a structurally-invalid AST; a well-formed AST (slot always backed by children) takes the identical path as before.
i Invariants and contracts preserved? Yes. The invariant relied on is "a raw child slot must be backed by children before it is dereferenced"; the new check enforces exactly that and never dereferences a pointer it has not confirmed is live. On the not-backed path the slot is nulled, keeping the settings/children relationship consistent for later formatting.

Session id: cron:clickhouse-worker-slot-4:20260714-135900

Comment thread src/Parsers/stripQuerySettings.cpp Resolved
…nced

The prior fix blanket-cleared ASTStorage::settings whenever its slot was not
backed by the storage's own children. That is too aggressive for a live-but-
desynced node: ASTStorage::formatImpl serializes *storage->settings directly,
so clearing the slot drops surviving engine settings (e.g. index_granularity)
instead of stripping only the safety cap.

Decide deref-safety by whole-tree reachability from the root instead. A node
reachable through children from the still-alive root is kept alive by that
owning intrusive_ptr chain, so it is safe to dereference and strip in place,
preserving its surviving settings; this also recognises a node the fuzzer
relocated elsewhere in the same tree. A slot not reachable from the root has
no live owner (possibly freed) and is cleared without dereferencing, which is
safe because such a node is out of the tree and never re-serialized. The
reachable set is captured once up front (never touching *ptr).

Add a gtest for a reachable-but-storage-desynced ASTStorage with a mixed
clause: index_granularity survives, only max_rows_to_read is stripped.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. gtest KeepsSurvivingEngineSettingOnReachableDesyncedStorage: CREATE ... SETTINGS max_rows_to_read = 0, index_granularity = 1024, storage settings node relocated out of storage->children but kept reachable via create->children. FAILS deterministically on f69345c.
b Root cause explained? Yes. ASTStorage::formatImpl (ASTCreateQuery.cpp:131) serializes *storage->settings via the raw pointer. The prior else blanket-cleared the slot whenever it was not in storage's own children, which also fires for a live-but-desynced node, dropping surviving engine settings instead of stripping only the safety cap. isBackedByChildren cannot distinguish freed from live-relocated.
c Fix matches root cause? Yes. Deref-safety is decided by whole-tree reachability from the root (collectReachableNodes): reachable = live owning chain = strip in place (keep surviving settings); not-reachable = no live owner (possibly freed) = clear without dereferencing.
d Test intent preserved / new tests added? Yes. Existing tolerance/strip tests unchanged and still pass; new mixed-clause test added that asserts index_granularity survives and only max_rows_to_read is stripped.
e Demonstrated in both directions? Yes. New test FAILS on f69345c (dropped a live storage SETTINGS node), PASSES with the fix. All 7 RemoveSettingsFromQuery tests pass (debug + ASan).
f Fix general, not a narrow patch? Yes. Reachability generalises the liveness check to any relocated-in-tree node, not just storage's own children. Other carriers (SELECT/INSERT/ASTQueryWithOutput hold owning ASTPtr; BACKUP is out of children) were audited and are unaffected.
g Generalizes across inputs? Yes. Reachability is type-agnostic; covers all-safety clauses (cleared/pruned), mixed clauses (stripped in place), freed slots (cleared, no UAF), and relocated-live nodes.
h Backward compatible? N/A. Internal fuzzer-only strip path; no user-facing behavior, setting, or on-disk/wire format change.
i Invariants and contracts preserved? Yes. collectReachableNodes never dereferences a slot pointer (pointer-value only); the reachable set is captured before any mutation so detaches cannot shrink it mid-walk; a not-reachable slot is out of the tree and never re-serialized, so clearing it changes no output. No UAF under ASan.

Session id: cron:clickhouse-worker-slot-2:20260714-153900

Comment thread src/Parsers/stripQuerySettings.cpp Resolved
…reachability

collectReachableNodes judged the bare storage->settings slot live by
pointer-value membership in a whole-tree address set. QueryFuzzer::fuzzMain
mutates the tree in place and keeps allocating before the strip runs, so a
freed slot's address can be reused by an unrelated live node; the address
test then reports the dangling slot as live and we dereference freed memory.

Replace it with findOwningChild: search storage->children (the slot's sole
owner) for an owning ASTPtr with the same address that casts to ASTSetQuery.
An owning child is the node's keep-alive, so a match proves the slot is the
same live node and address reuse cannot spoof it. Strip that node in place
(preserving surviving engine settings); otherwise fail closed and clear the
slot without dereferencing. In production children is the sole owner, so an
unbacked slot means freed and clearing loses no real settings.

Retarget the gtest to assert the fail-closed contract: a slot not backed by
an owning child in storage->children is cleared, not stripped in place.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. ClearsStorageSettingsSlotNotBackedByAnOwningChild deterministically FAILS on 67a23c2 (create->storage->settings kept, 0x...) and PASSES with the fix (slot cleared). A throwaway genuinely-freed-slot case ran clean under ASan.
b Root cause explained? collectReachableNodes recorded raw pointer VALUES over the whole tree; reachable_nodes.contains(storage->settings) was an address match. QueryFuzzer::fuzzMain mutates the tree in place and keeps allocating before the strip runs, so a freed slot's address can be reused by an unrelated live node -> the address test reports the dangling slot as "live" -> deref of freed memory. Any address-membership proof (whole-tree or owning-ptr) has this flaw.
c Fix matches root cause? Yes. Removed the address set entirely. findOwningChild searches storage->children (the slot's sole owner) for an owning ASTPtr whose .get() equals the slot and casts to ASTSetQuery. An owning child IS the node's keep-alive, so a match proves it is the same node and was never freed; a reused address cannot match because storage->children no longer holds the freed node. No owning child -> fail closed, clear without deref.
d Test intent preserved / new tests added? Yes. Retargeted the gtest to the sound fail-closed contract (a slot not backed by an owning child of storage is cleared, not stripped in place). In-place stripping preserving surviving engine settings for an in-children node is still covered by StripsSettingsCarriersOutsideChildrenWalk. The desync-tolerance and prune tests are unchanged.
e Both directions demonstrated? Yes. New test FAILS on 67a23c2, PASSES with the fix (rebuilt each direction). All 7 RemoveSettingsFromQuery tests pass on debug and ASan.
f Fix is general across code paths? Yes. ASTStorage is the only bare-pointer SETTINGS carrier. INSERT (settings_ast) and ASTQueryWithOutput (settings_ast) hold owning ASTPtrs, so a dropped child keeps the node alive and they never touch a raw slot; BACKUP holds settings outside children entirely. Only the ASTStorage branch needed the owning-child proof.
g Fix generalizes across inputs? Yes. The proof is by node identity, independent of the settings' names/values/types; the mixed-clause (max_rows_to_read = 0, index_granularity = 1024) and all-safety cases are both covered. No datatype/wrapper dimension applies (the slot is an ASTSetQuery node, not a column value).
h Backward compatible? Yes. Internal AST-fuzzer safety-limit strip path only; no user-visible behavior, no setting/format/metadata change, no SettingsChangesHistory impact.
i Invariants and contracts preserved? Yes. Invariant: never dereference storage->settings unless proven live via an owning ASTPtr in storage->children. findOwningChild compares pointer values only and never touches *raw; the live branch derefs the OWNING child (guaranteed alive), not the raw slot; the fail-closed branch clears without deref. ASTStorage::formatImpl never re-serializes a dangling slot because it is nulled.

Session id: cron:clickhouse-worker-slot-1:20260714-170800

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 841ee37

The one failure below is a pre-existing trunk flaky, not caused by this PR's diff (stripQuerySettings.cpp + gtest_Parser.cpp only).

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 01730_distributed_group_by_no_merge_order_by_long flaky, trunk (10 master + 15+ unrelated PRs/30d; Code 241 MEMORY_LIMIT in AggregatingTransform) #109847 (azat, open)
CH Inc sync private fork mirror CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260714-223000

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 123/126 (97.62%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 686e3a3

Every failure below has an owner: a fixing PR, or a full-effort fix task whose
fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky on this lane: secondary replicas are built without setQueryId, so the per-table max_concurrent_queries throttle sees several random query ids for one statement and the query competes against itself #112385 (ours, open)

Session id: cron:our-pr-ci-monitor:20260729-083000

The run on 65addb3 never executed: praktika's
Config Workflow spent its whole 600s budget on CI-database read timeouts (9
"Read timed out" attempts against play.clickhouse.com), was SIGTERMed ("Job
timed out: [Config Workflow], timeout [600], exit code [-15]") and then set the
173 dependee jobs to dropped instead of dispatching them. No build or test job
ran. That run is already on its second attempt, which the hourly retry workflow
does not re-run, and a fork cannot reach the rerun endpoint, so a fresh head sha
is the only remaining lever.

This commit is empty (tree byte-identical to its parent) and only mints that
head. No source change.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/Parsers/stripQuerySettings.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dae698dd2 with master 29dbd618d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 6 s compile time in total, 7 of them have a recent master baseline.

Job report

…ests

The comment justifying the ASTStorage else-branch claimed storage->children is
the sole owner of the settings slot in production, so an unbacked slot always
means freed. Nothing guarantees that. The only caller strips right after
QueryFuzzer::fuzzMain returns, and master's fuzzer holds an owning ASTPtr for
every node it visited (debug_visited_nodes became unordered_map<const IAST *,
ASTPtr>, cleared only at the start of the next fuzzMain, after this branch
forked). An unbacked slot can therefore still be live, and clearing it then
drops that clause whole instead of stripping only the pinned safety caps.

The behaviour does not change, because an owning child in storage->children
remains the only proof reachable from here that the raw slot still points at
that same node. Every address-based alternative fails on the same case: a
whole-tree reachable set, an owning-pointer address set, and the fuzzer's own
address-keyed map (whose entries are erased and re-inserted as nodes get
replaced) can all be satisfied by an unrelated node that reused a freed
address, and acting on that would dereference freed memory or mutate the wrong
node. So an unbacked slot is still cleared unread; what changes is that the
comment states the real contract (liveness unprovable, not disproved) and names
the cost of the safe direction.

Both tests get a real oracle for that cost.

ClearsStorageSettingsSlotNotBackedByAnOwningChild already used a mixed clause
(max_rows_to_read = 0, index_granularity = 1024) on a kept-alive unbacked slot;
it now also asserts index_granularity is absent from the output. With the
else-branch stripping in place instead of clearing, that assertion fails with
SETTINGS index_granularity = 1024 still serialized.

ToleratesSettingsSlotDesyncedFromChildren could not see whether the slot was
detached at all: its setup removes the settings node from children, and both
remaining checks (no-throw and settingNamePresent) walk children, so a
transform that erased the child but left the owning field set passed. The owner
formatters print from that field, so such a query re-serializes as a bare
SETTINGS and the fuzzer skips it instead of running it under the caps. The test
now asserts each desynced carrier's own slot is null and re-parses the
formatted result. Measured with detachChild(IAST &, ASTPtr &) no longer
resetting the field: the old test passes, the new one fails with "query slot
not detached".

It also asserts that the unbacked node comes out untouched, which is the half of
"never dereferenced" a test can pin without constructing a use-after-free
itself.

The refuted-alternative narration moves out of findOwningChild and the test
header into this message, where it belongs.

Co-Authored-By: Claude Opus 5 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Sep 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 26, 2026
Merged via the queue into ClickHouse:master with commit 199f114 Sep 26, 2026
174 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 26, 2026
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-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. groeneai-origin-unknown PR origin: unclassified (legacy task) pr-ci 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