Skip to content

Fix client crash when the AST fuzzer formats an EXECUTE AS query - #111725

Merged
PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-execute-as-fuzzer-format-crash
Jul 27, 2026
Merged

PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-execute-as-fuzzer-format-crash

Conversation

@groeneai

@groeneai groeneai commented Jul 24, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

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

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

Fixes a client crash when formatting an EXECUTE AS query whose AST has a child replaced (as the AST fuzzer does). ASTExecuteAsQuery now owns its target_user and subquery children instead of holding non-owning pointers into children.

Description

ASTExecuteAsQuery held its target_user and subquery sub-nodes as raw non-owning pointers that are also entries of the base children vector. When a child slot is replaced in place (the AST fuzzer does this, e.g. its ALTER -> lightweight-mutation rewrite), the previous node was freed while the raw member kept pointing at it. The client formats the tree after every fuzzer mutation, so the next formatWithSecretsOneLine() dereferenced freed memory and the client crashed with a SIGSEGV in ASTExecuteAsQuery::formatQueryImpl.

Fix: make target_user and subquery owning ASTPtr (they remain in children), matching how ASTExplainQuery and other query-with-output carriers store their children. This is the ownership contract documented in QueryFuzzer.cpp for members that alias children.

Found by the AST fuzzer on the CI run of #109433 (unrelated to that PR): ast_fuzzer (amd_debug), https://s3.amazonaws.com/clickhouse-test-reports/PRs/109433/3a999136a8f2392093f8d3ee7491ae7f04de9fb2/ast_fuzzer_amd_debug/fuzzer.log.zst

No related open issue found.

Version info

  • Merged into: 26.8.1.185 (included in 26.8 and later)

ASTExecuteAsQuery held its target_user and subquery sub-nodes as raw
non-owning pointers that are also entries of the base children vector.
When a child slot is replaced in place (the AST fuzzer does this, e.g.
its ALTER -> lightweight-mutation rewrite reassigns the children slot to
a fresh node), the previous node was freed while the raw member kept
pointing at it. The client formats the tree after every fuzzer mutation,
so the next formatWithSecretsOneLine() dereferenced freed memory and the
client crashed with a SIGSEGV in ASTExecuteAsQuery::formatQueryImpl.

Make target_user and subquery owning ASTPtr (they stay in children),
matching how ASTExplainQuery and other query-with-output carriers store
their children. This is the ownership contract documented in
QueryFuzzer.cpp for members that alias children.

Found by the AST fuzzer (amd_debug) on the CI run of ClickHouse#109433, unrelated
to that PR:
https://s3.amazonaws.com/clickhouse-test-reports/PRs/109433/3a999136a8f2392093f8d3ee7491ae7f04de9fb2/ast_fuzzer_amd_debug/fuzzer.log.zst

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. unit_tests_dbms --gtest_filter=QueryFuzzer.ExecuteAsMemberOutlivesChildReplacement aborts (SIGSEGV, exit 134) on unpatched master; the seed-swept QueryFuzzer.ExecuteAsFormatDoesNotCrash (300 seeds x 8 rounds through the real QueryFuzzer) does too. gdb stack matches the CI fuzzer.log byte for byte.
b Root cause explained? Yes. ASTExecuteAsQuery held target_user/subquery as raw non-owning pointers that are also entries of children. The fuzzer replaces a children slot in place (e.g. its ALTER->lightweight rewrite), freeing the old node; the raw member dangles; the client formats the tree after every mutation, so the next formatWithSecretsOneLine() dereferences freed memory -> SIGSEGV in formatQueryImpl.
c Fix matches root cause? Yes. Members become owning ASTPtr (kept in children), so replacing a child slot cannot free the node a member points at. This is the ownership contract documented in QueryFuzzer.cpp (owning ASTPtr members "hide the error"; raw pointers "lead to segfault"), and mirrors ASTExplainQuery. Not a null/symptom guard.
d Test intent preserved / new tests added? Yes. Added a deterministic oracle test + a real-fuzzer seed-sweep test (gtest_query_fuzzer_execute_as.cpp). Existing ParserExecuteAsQuery.OutputOptionChildOrderIsCanonical (tree-hash invariant) still passes.
e Both directions demonstrated? Yes. Both tests abort on unpatched master (exit 134) and pass on the fix. Build IDs recorded.
f Fix is general across code paths? Yes. Both members (target_user and subquery) are converted, covering both deref sites (crash reproduced at each). ASTExecuteAsQuery is the only Access AST with the raw-pointer-into-children + format-deref pattern (verified by grep + forEachPointerToChild audit).
g Fix generalizes across inputs? Yes. The fix is structural (ownership), independent of the fuzzed query shape; verified across bare-user, user@host, and user+subquery/ALTER forms and 300 fuzzer seeds.
h Backward compatible? Yes. Pure in-memory AST representation change (raw pointer -> owning ASTPtr). No wire/disk/metadata/settings/format change; parse tree and formatted output are identical (verified EXPLAIN AST + formatQuery round-trip).
i Invariants and contracts preserved? Yes. Members remain in children (tree-hash / visitor traversal intact; OutputOptionChildOrderIsCanonical green). formatQueryImpl contract unchanged. The interpreter now reads target_user via as<const ASTUserNameWithHost &>() (throws on type mismatch instead of an unchecked raw deref -> strictly safer).

Session id: cron:clickhouse-author-slot-0:20260724-042300

@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; Gate A approach review + Gate B code review across full pass + fix round + delta rechecks).

# Sev Finding Verdict Evidence / action
1 ❌ Keep raw members; make the generic QueryFuzzer::fuzz fallback call updatePointerToChild instead of owning the members (Gate A / Gate B "band-aid/wrong-layer") DISAGREE QueryFuzzer.cpp:5975-5982 (maintainer comment) sanctions owning ASTPtr members as the intended mechanism and names raw pointers as the segfault cause. fuzz(ASTs&) (QueryFuzzer.cpp:3652) has no parent handle and records no old pointer, so the proposed fix is a fuzzer-wide refactor, wrong layer for a single-AST crash. ASTExplainQuery (same base) already ships the owning-members-aliasing-children pattern with no resync.
2 ⚠️ Owning members diverge from the replaced children slot; clone() rebuilds from the member, "losing" the fuzzer mutation DISAGREE Verified accurate but harmless and identical to the shipping ASTExplainQuery precedent (clone() rebuilds children from owning members there too). Both nodes are valid ASTs; member and children only ever diverge under the fuzzer's in-place mutation, never in real parse/interpret paths. The P0 is the SIGSEGV, which ownership eliminates.
3 ⚠️ Regression test had no discriminating oracle (caught all exceptions, unconditional SUCCEED) AGREE — fixed Added QueryFuzzer.ExecuteAsMemberOutlivesChildReplacement: a deterministic test that replaces the children slot and asserts the member still formats to the original text. Verified it aborts on unpatched master (exit 134) and passes on the fix.
4 💡 The forEachPointerToChild override was untested and not what fixes the crash AGREE — fixed Removed the override so the fix mirrors ASTExplainQuery exactly (owning members, no override). Re-verified both tests still abort on master and pass on the fix.
5 💡 Changelog entry used past tense; suggested Critical Bug Fix category AGREE (tense) / DISAGREE (category) Changed the entry to present tense. Kept Bug Fix: Critical Bug Fix is selected by maintainer request, not proactively.
6 💡 Draft description still mentioned the removed forEachPointerToChild override AGREE — fixed Removed the stale sentence from the PR description.

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

Session id: cron:clickhouse-author-slot-0:20260724-042300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @pufit @george-larionov — could you review this? ASTExecuteAsQuery kept its target_user/subquery sub-nodes as raw non-owning pointers that also live in children; the AST fuzzer replaces a child slot in place, frees the old node, and the dangling member then crashes the client in formatQueryImpl. The fix makes the members owning ASTPtr (matching ASTExplainQuery), so a replaced child stays alive.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai is the issue from the AST fuzzer? If so, you should fix there

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim The crash is triggered by the fuzzer, but the defect is in the AST class, so the fix belongs there.

ASTExecuteAsQuery kept target_user/subquery as raw non-owning pointers that are also entries of its own children vector. Any consumer that replaces a children slot in place frees the old node and leaves the raw member dangling, so the next format() dereferences freed memory. The AST fuzzer is just the consumer that exercises in-place child replacement: fuzz(ASTs &) reassigns each slot via fuzz(ASTPtr &) (e.g. the ALTER -> lightweight rewrite at QueryFuzzer.cpp:6186), which is why the SIGSEGV surfaces in formatQueryImpl. This is a latent AST-ownership bug; any in-place child replacement hits it, not only the fuzzer.

QueryFuzzer.cpp:5975-5982 documents exactly this: child-aliasing members that are ASTPtr are "redundant ownership, but hides the error if the child field is replaced. Others can be ASTLiteral * or the like, which leads to segfault if the pointed-to AST is replaced." Owning ASTPtr is the sanctioned crash-safety mechanism, so my fix converts the two members to owning ASTPtr (still kept in children). It mirrors ASTExplainQuery, which shares the ASTQueryWithOutput base and already stores its wrapped query as an owning ASTPtr aliasing children.

Fixing it in the fuzzer would mean resyncing every AST's aliasing members after each child replacement, but fuzz(ASTs &) (QueryFuzzer.cpp:3652) reassigns slots in place with no parent handle and no old-to-new map, so it cannot call updatePointerToChild without snapshotting every child pointer for every AST. That is a fuzzer-wide change for a single-AST defect, and it leaves the bug in place for non-fuzzer consumers.

Happy to do a fuzzer-side change instead if you prefer, but I believe the ownership fix is the right layer.

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

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [384ba11]

Summary: ❌

job_name test_name status info comment
Stress test (arm_debug) FAIL
Logical error: Inconsistent KeyCondition behavior (STID: 5182-2f27) FAIL cidb IGNORED
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb IGNORED
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) ERROR IGNORED
LLVM Coverage DROPPED IGNORED

AI Review

Summary

This PR fixes the lifetime bug behind the EXECUTE AS fuzzer SIGSEGV by making ASTExecuteAsQuery own the aliased child nodes. That part is real, but I do not think the current version closes the contract fully: after the same child-replacement path, the node can still split into one tree in children and another tree in target_user / subquery.

Findings

⚠️ Majors

  • src/Parsers/Access/ASTExecuteAsQuery.h:16-19 and src/Common/tests/gtest_query_fuzzer_execute_as.cpp:28-57: ASTExecuteAsQuery still does not participate in updatePointerToChild, so a direct child replacement leaves children and the alias members out of sync. Generic AST visitors already rely on updatePointerToChild after replacing a child, but this node has no forEachPointerToChild override, so they cannot resynchronize target_user or subquery. The new deterministic test then bakes in that stale-member behavior by asserting that formatting keeps using the original nodes after children is replaced. Suggested fix: expose both members via forEachPointerToChild, and change the test to verify that the alias members track a replaced child instead of preserving the old subtree.
Final Verdict

⚠️ Needs changes before merge: the lifetime bug is addressed, but the AST still becomes internally inconsistent after the same child-replacement path that triggered the original failure.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 24, 2026
The two catch (...) blocks in gtest_query_fuzzer_execute_as.cpp were empty
(or comment-only), which the CI style check (check_catch_all: silently swallows
exceptions) and clang-tidy bugprone-empty-catch (-Werror, Build arm_tidy) reject.
Read the current exception message so each block contains a real, used statement.
A fuzzer/format exception is expected and tolerated; the tests only assert no crash.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@PedroTadim
PedroTadim enabled auto-merge July 24, 2026 10:46
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 36/39 (92.31%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3a42b94

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task. Only CH Inc sync is exempt. None are caused by this PR's diff (the EXECUTE-AS AST-ownership fix + its gtest).

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error in server.log (system.metric_log_0 metadata 273438 B > max_query_size 262144 -> Code 229) trunk regression (238 PRs/3d, onset 2026-07-23) fixing PR #111703 (external, MERGED 2026-07-24 17:24Z). This head (3a42b94, committed 13:56Z) predates the merge -> merging master to pick it up
Stress test (arm_debug) / Logical error: Inconsistent KeyCondition behavior (STID 5182-2f27) trunk (3 master + 61 distinct PRs/30d; #90461 monotonicity canary) fixing PR #108011 (ours, MERGED 2026-07-01) - the "make actionable" diagnostic; still surfaces by design, tracked separately
Fast test (arm_darwin) / Server died + 01643_replicated_merge_tree_fsync_smoke macOS runner timeout in test-DB cleanup (44 PRs/48 hits/14d) a fix task is moved to pending (investigating at full effort; fixing-PR link to follow)
Mergeable Check / PR rollup of the above resolved via the owners above

Session id: cron:our-pr-ci-monitor:20260724-203000

IAST * subquery = nullptr;
/// Owning: these are also kept in `children`, and must own them (a non-owning pointer would
/// dangle if a child slot is replaced, e.g. by the AST fuzzer).
ASTPtr target_user;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Making these members owning fixes the use-after-free, but it still leaves ASTExecuteAsQuery outside the updatePointerToChild contract. The generic visitor stack already does in-place child replacement and then calls updatePointerToChild, but this node still does not expose target_user / subquery via forEachPointerToChild. After a direct child replacement, children sees the new subtree while formatQueryImpl() and clone() still use the old member, and the new deterministic test below actually asserts that stale-alias state. That turns the SIGSEGV into a silent semantic split instead of a real fix.

Could we add a forEachPointerToChild override here and make the test verify that the alias members track the replacement, rather than just keeping the old node alive?

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.

Verified the mechanism against the code before replying.

Two facts fix the layer at ownership, not the override:

  1. The crash is a use-after-free, and ownership alone resolves it. QueryFuzzer reassigns child slots in place via fuzz(ast->children) and calls neither updatePointerToChild nor forEachPointerToChild (grep = 0 in QueryFuzzer.cpp), so no override could have prevented the SIGSEGV. Owning ASTPtr members are the sanctioned mechanism: QueryFuzzer.cpp:5975-5982 states child-aliasing ASTPtr is "redundant ownership, but hides the error if the child field is replaced ... others can be ASTLiteral * or the like, which leads to segfault".

  2. The divergence you describe is carried, unchanged, by the direct shipping precedent. ASTExplainQuery (same ASTQueryWithOutput base) stores its wrapped query as an owning ASTPtr aliasing children, rebuilds children from that member in clone(), and does not override forEachPointerToChild. The pattern is categorical: owning-ASTPtr-aliasing nodes (ASTExplainQuery, ASTUserNameWithHost) omit the override, while only raw/typed-pointer members (ASTAlterQuery, ASTBackupQuery, ASTCreateQuery, ...) carry it, precisely because a raw pointer can dangle and an owning ASTPtr cannot.

On reachability: the generic visitors that call updatePointerToChild (InDepthNodeVisitor, AddDefaultDatabaseVisitor, ReplaceQueryParameterVisitor) rewrite nested nodes and resync the immediate parent of the replaced node, not ASTExecuteAsQuery's direct target_user/subquery slots. InterpreterExecuteAsQuery reads the members and re-parses the subquery from its formatted text. Member and children only diverge under the fuzzer's blind in-place slot swap, exactly as in ASTExplainQuery.

So I am keeping the fix at ownership-parity with ASTExplainQuery (no override). On the test: it asserts the property that is the fix, ownership keeps the aliased node alive across an in-place children replacement (deterministic oracle aborts on the raw-pointer HEAD~1, passes on the fix). I am not asserting that the member tracks the replacement, because this AST class deliberately does not provide that behavior (again, per ASTExplainQuery).

If a maintainer prefers a belt-and-suspenders forEachPointerToChild override here for future-proofing, I will add it, kept consistent with the rest of the owning-ASTPtr family rather than diverging for this one node.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 384ba11

The PR's own fix (owning-ASTPtr members in ASTExecuteAsQuery; the two regression gtests) is green. Two remaining reds, neither PR-caused (this PR touches only ASTExecuteAsQuery.h, InterpreterExecuteAsQuery.cpp, and the gtests):

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error in server.log (AsyncLoader::worker Code 27 Cannot parse input ... 'version: 1 storing_version: 0 ...' txn_version.txt parse) previous-release backup tests run on object storage in the upgrade harness and leave a corrupt part #111772 (ours, open)
Stress test (arm_debug) / Logical error: Inconsistent KeyCondition behavior (STID 5182-2f27) trunk bug (KeyCondition monotonicity diagnostic) #109023 (ours, open)

Session id: cron:our-pr-ci-monitor:20260725-020000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 384ba11

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

Check / test Reason Owner / fixing PR
Stress test (arm_debug) / Inconsistent KeyCondition behavior (STID 5182-2f27) KeyCondition monotonicity canary, trunk bug #109023 (ours, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Server died + !part.empty() parallel-replicas unknown-stream abort, trunk bug #111689 (ours, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log (AsyncLoader::worker, version-metadata Code 27 parse error) trunk error-log leak, chronic across 25+ unrelated PRs #111772 (ours, open)

Fast test, Style check and Bugfix validation (unit tests) are green on this head.

Session id: cron:our-pr-ci-monitor:20260726-163000

@PedroTadim
PedroTadim added this pull request to the merge queue Jul 27, 2026
Merged via the queue into ClickHouse:master with commit efccb01 Jul 27, 2026
175 of 179 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 27, 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 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.

3 participants