Skip to content

Limit and cancel in-flight queries in the server-side AST fuzzer - #108212

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/limit-and-cancel-server-ast-fuzzer-queries
Jun 28, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/limit-and-cancel-server-ast-fuzzer-queries

Conversation

@groeneai

@groeneai groeneai commented Jun 22, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #107941
Related: #108353

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

Fixes the recurring stress-test "Hung check failed, possible deadlock found" on Stress test (*) for the dominant class: server-side AST-fuzzer queries that read millions of rows.

Root cause (from 30 full hung_check.log artifacts across ~26 PRs plus master): the hung query runs inside the server-side AST fuzzer (executeASTFuzzerQueries, src/Interpreters/executeQuery.cpp), which runs fuzzed queries as a finish callback of the outer query. QueryFuzzer::getRandomField rewrites numeric literals to boundary values (1024*1024 +/- 1, INT_MAX, INT64_MAX, ...), so a seed numbers(100) becomes e.g. numbers(1048576) and the fuzzed INSERT reads ~1M rows through the MergeTree wide-part writer (InsertedRows ~= 2^20 + seed in the artifacts). Under sanitizers a single granule write takes minutes, and the fuzzed CompletedPipelineExecutor had no cancel callback, so it ignored the outer query's KILL/timeout (max_execution_time is only checked between pipeline tasks). The outer query lingered in the processlist (elapsed 438-3004s, is_cancelled: 1) and tripped the hung check.

Changes, all confined to the fuzz context set up by executeASTFuzzerQueries:

  1. Bound the fuzzed read: pin max_rows_to_read = 1e5 + read_overflow_mode = break, so a fuzzer-inflated read stops after a bounded number of rows instead of grinding through millions.
  2. Bound the first block: pin max_block_size and min_insert_block_size_rows small. max_rows_to_read is only checked after a source emits a chunk, and InterpreterInsertQuery::applyTrivialInsertSelectOptimization copies min_insert_block_size_rows (default ~1M) into the SELECT's max_block_size, so without this one ~1M-row chunk could still reach the wide-part writer before the row cap fires.
  3. Cancel callback: give the fuzzed CompletedPipelineExecutor a cancel callback bound to the outer query's QueryStatus (KILL/timeout via checkTimeLimitSoft), server shutdown, and a 30s wall-clock deadline, so an in-flight fuzzed query is cancelled between pipeline tasks (mirrors the normal executeTrivialBlockIO path).
  4. Strip the fuzzed query's own overrides (src/Parsers/stripQuerySettings.{h,cpp}, with gtests): a fuzzed/seed query can put the same setting names in its own SETTINGS clause, which executeQueryImpl re-applies on reparse and which would lift the caps from 1-3. The helper removes those names from every query-settings carrier the fuzzed query can reach: both the changes and = DEFAULT lists, all repeated entries, and the SELECT / INSERT / ASTQueryWithOutput / CREATE-storage / BACKUP settings slots. It also prunes a settings node that becomes empty after stripping, so it does not reformat as a bare SETTINGS (which would make the query unparseable and silently skipped, hiding whether the cap was effective).

This complements the already-merged #107640 (which guards only between fuzzer-loop iterations, not in-flight) and #108353 (which makes the primes table function itself respond to cancellation: a single PrimesSource::generate call can spin on a large step without emitting a chunk, an un-cancellable-source mechanism that the between-task cancel callback here cannot reach). It also builds on the existing max_execution_time / max_memory_usage / max_result_* per-query limits.

CI report (one of 30): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107851&sha=ac6d3657bee4c54de67abdad3f6c4743e7f5d720&name_0=PR&name_1=Stress%20test%20%28amd_asan_ubsan%29

Version info

  • Merged into: 26.7.1.204 (included in 26.7 and later)

The server-side AST fuzzer (executeASTFuzzerQueries) runs fuzzed queries as a
finish callback of the outer query. QueryFuzzer::getRandomField rewrites numeric
literals to boundary values (1 MiB +/- 1, INT_MAX, INT64_MAX, ...), so a seed
numbers(100) can become numbers(1048576) and the fuzzed INSERT reads ~1M rows
through the MergeTree wide-part writer. Under sanitizers that single granule
write takes minutes, and the fuzzed CompletedPipelineExecutor had no cancel
callback, so it ignored the outer query KILL/timeout (max_execution_time is only
checked between pipeline tasks). The outer query then lingered in the processlist
(observed elapsed 438-3004s, is_cancelled=1) and tripped the stress hung check.

Two changes in executeASTFuzzerQueries:
- Bound the fuzzed read with max_rows_to_read + read_overflow_mode=break so a
  fuzzer-inflated INSERT/SELECT stops after a reasonable number of rows instead
  of grinding through millions.
- Give the fuzzed CompletedPipelineExecutor a cancel callback bound to the outer
  query's QueryStatus, server shutdown, and a wall-clock deadline, so a single
  in-flight fuzzed query is cancelled between pipeline tasks.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. INSERT INTO t SELECT number FROM numbers(2000000) SETTINGS max_rows_to_read=100000, read_overflow_mode='break' deterministically caps at ~130K rows vs 2M uncapped. With the fuzzer: a debug-build run of an ast_fuzzer_runs=50 numbers(100) INSERT seed inserted 487,231,760 rows before the fix (the fuzzer rewrote the literal to a 2^20-class boundary value).
b Root cause explained? Yes. QueryFuzzer::getRandomField substitutes bad_int64_values (1024*1024 +/- 1, INT_MAX, INT64_MAX, ...) for numeric literals, so a seed numbers(100) becomes numbers(1048576) and the fuzzed INSERT reads ~1M rows through MergeTreeDataPartWriterWide. max_execution_time=10 never fires because PipelineExecutor only checks the limit between tasks (PipelineExecutor.cpp:369) and the fuzzed CompletedPipelineExecutor had no cancel callback, so the outer KILL/timeout could not reach the in-flight write. Outer query then lingered (elapsed 438-3004s, is_cancelled=1), tripping the hung check (elapsed > 300).
c Fix matches root cause? Yes. (1) max_rows_to_read + read_overflow_mode=break bounds the fuzzer-inflated row count; (2) a cancel callback on the fuzzed CompletedPipelineExecutor bound to the outer QueryStatus + server shutdown + a 30s wall-clock deadline makes a single in-flight fuzzed query cancellable between tasks (mirrors executeTrivialBlockIO). Both target the identified mechanism, not a symptom.
d Test intent preserved / new tests added? New test 04344_server_ast_fuzzer_insert_limit.sql exercises the server fuzzer with a heavy INSERT seed under a tight outer max_execution_time and confirms the server stays responsive (no hang, no crash). No existing test weakened; 03833_server_ast_fuzzer still passes 10/10.
e Both directions demonstrated? Yes. Baseline binary (Build ID fc081ba6, fix reverted): fuzzed numbers(100) seed inserted up to 487M rows, 12.5s in a fast debug build (minutes under sanitizers). Fixed binary (Build ID aa84cd28): each fuzzed read bounded to ~100-130K rows, 1-2s; with outer max_execution_time=3, 100 fuzzer runs finish in 2s.
f Fix is general, not a narrow patch? Yes. executeASTFuzzerQueries has a single executor for completed/pulling fuzzed pipelines (the INSERT ... SELECT FROM numbers() path); the pushing path (external-data INSERT) is already cancel()-ed. No sibling fuzzer-executor exists. The read bound + cancel callback cover the whole in-flight fuzzed-query path, not just one query shape.

Session id: cron:clickhouse-worker-slot-4:20260622-181400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @Algunenano — this implements option (a) plus the heavy-INSERT limit you asked for on #107941: a cancel callback on the fuzzed CompletedPipelineExecutor (bound to the outer QueryStatus + shutdown + a 30s wall-clock deadline) and max_rows_to_read + read_overflow_mode=break to bound fuzzer-inflated INSERTs (the fuzzer rewrites numeric literals to 2^20-class boundary values, turning numbers(100) into ~1M-row reads).

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2cd7b21]

Summary: ❌

job_name test_name status info comment
Stress test (arm_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR limits server-side AST fuzzer executions by stripping query-level overrides of the pinned safety settings, pruning empty SETTINGS carriers, pinning row/block-forming limits, and adding a cancel callback for completed fuzzed pipelines. I found no remaining correctness, safety, or test-coverage findings in the current diff; all previously raised inline issues have been addressed and resolved.

Final Verdict

Status: ✅ Approve

No required follow-up actions.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jun 22, 2026
Comment thread src/Interpreters/executeQuery.cpp Resolved
The fuzz context pins resource caps (max_rows_to_read, read_overflow_mode,
max_execution_time, max_memory_usage, max_result_rows, max_result_bytes) before
running each fuzzed query, but executeQueryImpl re-applies the query's own
SETTINGS on top of the context (InterpreterSetQuery::applySettingsFromQuery).
A seed or fuzzed query carrying SETTINGS max_rows_to_read = 0 (or a larger value)
therefore lifted the guard, and stress tests have plenty of such queries, so a
fuzzer-inflated numbers(2^20) read could still grind a single granule for minutes
and the between-tasks cancel callback could not interrupt it.

Strip those limit settings from every SETTINGS clause in the fuzzed AST before it
is formatted and executed, so the fuzz-context values win. The new test seeds the
exact override (SETTINGS max_rows_to_read = 0, ...) on both a heavy SELECT and a
heavy INSERT and confirms the server stays responsive.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 250ae42 - settings-override fix)

# Question Answer
a Deterministic repro? Yes. SET max_rows_to_read = 1000; SELECT count() FROM numbers(5000) throws TOO_MANY_ROWS, but ... SETTINGS max_rows_to_read = 0 returns 5000 - the query-level setting overrides the context cap. In the fuzzer path: a numbers(2000000) read under the fuzz-context cap (max_rows_to_read = 100000, read_overflow_mode = break) summed all 2,000,000 rows when the query carried SETTINGS max_rows_to_read = 0.
b Root cause explained? Yes. executeASTFuzzerQueries pins the safety caps on fuzz_context, but executeQueryImpl later calls InterpreterSetQuery::applySettingsFromQuery(out_ast, context) which re-applies the query's own SETTINGS on top of the context. So a seed or fuzzed SETTINGS max_rows_to_read = 0 (or larger) silently lifted every fuzzer cap, and the heavy single-granule write the cancel callback cannot interrupt could still run.
c Fix matches root cause? Yes. stripFuzzerSafetyLimitSettings walks the fuzzed AST and removes those six limit settings from every ASTSetQuery before formatting, so applySettingsFromQuery has nothing to re-apply and the pinned fuzz-context values are authoritative. Targets the override mechanism directly, not a symptom.
d Test intent preserved / new tests added? 04344_server_ast_fuzzer_insert_limit now seeds the exact override (SETTINGS max_rows_to_read = 0, read_overflow_mode = 'throw', max_execution_time = 0, max_result_rows = 0) on both a heavy SELECT and a heavy INSERT - the bypass case the review flagged. No existing test weakened.
e Both directions demonstrated? Yes, on one env-toggle binary (eafdaeb8). Strip disabled: 20/20 fuzzed queries kept the override settings; numbers(2000000) read summed all 2,000,000 rows. Strip enabled: 20/20 fuzzed queries had an empty SETTINGS; the same read broke at 131,072 rows (sum = 8556609153). Clean fix binary (aa5a9c8b): 04344 10/10, 03833 3/3.
f Fix is general, not a narrow patch? Yes. The strip covers all six caps the fuzzer pins (not just max_rows_to_read) and every ASTSetQuery reachable in the AST (top-level, INSERT settings_ast, subquery), using the same children-walk as validateAnalyzerSettings.

Session id: cron:clickhouse-worker-slot-3:20260622-200300

Comment thread src/Interpreters/executeQuery.cpp Resolved
…mits

The server-side AST fuzzer strips its resource-limit settings (max_rows_to_read,
read_overflow_mode, max_execution_time, max_memory_usage, max_result_rows,
max_result_bytes) from a fuzzed query so the query's own SETTINGS cannot lift the
fuzz-context caps. When a SETTINGS clause held only those settings, stripping left
an empty ASTSetQuery attached to its owner. ASTSelectQuery, ASTInsertQuery and
ASTQueryWithOutput formatters all emit `SETTINGS ` whenever that slot is non-null,
so an empty node re-serialized to a bare trailing `SETTINGS`. executeQuery then
re-parses the formatted query, the bare `SETTINGS` throws a syntax error, and the
fuzzer's catch silently skips the query instead of running it under the caps. The
heavy seed reads were therefore never exercised under the bound.

Move the strip logic into removeSettingsFromQuery (Parsers/stripQuerySettings),
which after stripping prunes any SETTINGS node that became empty from its owner
slot: ASTSelectQuery::Expression::SETTINGS, ASTQueryWithOutput::settings_ast
(SELECT-UNION, EXPLAIN, SHOW, ...) and ASTInsertQuery::settings_ast. The
re-serialized query then parses and runs under the fuzz-context caps.

Add a gtest (RemoveSettingsFromQuery.PrunesEmptySettingsAndKeepsQueryParseable)
that strips the safety settings from SELECT, SELECT-UNION, INSERT, EXPLAIN and a
subquery clause carrying only those settings, and asserts no empty SETTINGS node
remains and the formatted query re-parses. Without the prune the test fails with
the exact bare-`SETTINGS` syntax error seen by the fuzzer.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Parsers/stripQuerySettings.cpp Resolved
…t too

removeSettingsFromQuery only removed the safety-limit settings from
ASTSetQuery::changes (the `name = value` form). A query can also park a
setting in ASTSetQuery::default_settings via `SETTINGS max_rows_to_read =
DEFAULT`. When the fuzzed query is formatted and re-parsed, applying its
SETTINGS runs InterpreterSetQuery::executeForCurrentContext, which calls
resetSettingsToDefaultValue(default_settings); that resets the fuzz-context
cap (max_rows_to_read = 100000, read_overflow_mode = 'break') back to its
unbounded default (0 / 'throw') before the plan is built. So a seed such as
`SELECT ... FROM numbers(100) SETTINGS max_rows_to_read = DEFAULT` could
still lift the read cap and let the fuzzer grind through millions of rows.

Strip the same names from default_settings as well. The empty-node prune is
unchanged: isEmptySetQuery already requires default_settings to be empty
before detaching the SETTINGS owner.

Add a gtest (RemoveSettingsFromQuery.StripsResetToDefaultOverrides) covering
the `= DEFAULT` form across SELECT / SELECT-UNION / INSERT / subquery, and a
`= DEFAULT` seed to the 04344 regression test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Parsers/stripQuerySettings.cpp Resolved
SettingsChanges::removeSetting erases only the first matching entry, while
ParserSetQuery appends one SettingChange per occurrence. A seed such as
SETTINGS max_rows_to_read = 0, max_rows_to_read = 0 therefore kept its second
copy after the strip, and executeQueryImpl re-applied it on top of the pinned
fuzzer context, re-opening the unbounded read. Replace the per-name first-only
removal with std::erase_if over both changes and default_settings so every
copy is removed. Add a repeated-override gtest regression and a repeated-seed
case to 04344.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Parsers/stripQuerySettings.cpp Resolved
…AST-fuzzer safety limits

The strip walked the AST `children` and pruned only the SELECT, INSERT and
ASTQueryWithOutput settings owners, while the fuzzer can override the pinned
caps through two other carriers that InterpreterSetQuery::applySettingsFromQuery
also reads back onto the query context:

- ASTBackupQuery::settings is held outside `children` (and outside the inherited
  settings_ast), so the traversal never reached it. With ast_fuzzer_any_query=1
  a `BACKUP ... SETTINGS max_execution_time = 0` survived the strip and lifted
  the cap on re-parse (a strip miss).
- ASTStorage::settings is in `children` and was stripped, but had no prune
  branch, so a `CREATE ... SETTINGS <only a safety setting>` left an empty node
  that ASTStorage::formatImpl serialized to a bare `SETTINGS`; the re-parse threw
  and the fuzzed query was silently skipped instead of running under the caps (a
  prune miss).

Make strip and prune owner-driven and scoped to exactly the carriers
applySettingsFromQuery re-applies (SELECT, INSERT, ASTQueryWithOutput,
ASTStorage, ASTBackupQuery), so both carriers above are now stripped and pruned
in a single traversal. SETTINGS in positions that do not feed the query context
(refresh strategy, dictionary layout, column declarations, standalone SET) are
no longer touched, which also removes the bare-`SETTINGS` risk that blanket
stripping created for them.

Extend the unit test and the 04344 stateless test with the BACKUP and CREATE
storage carriers.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. New gtest RemoveSettingsFromQuery.StripsSettingsCarriersOutsideChildrenWalk fails on demand with the prior children-only strip (build id 4d726860): BACKUP cap max_execution_time = 0 survives, and the CREATE storage case throws Syntax error: failed at position 68 (end of query) on re-parse (the bare SETTINGS). Passes with the fix (build id 479ac859).
b Root cause explained? The strip walked children but pruned only 3 owners (asymmetric). ASTBackupQuery::settings lives outside children, so it was never stripped and applySettingsFromQuery's backup branch re-applied the cap. ASTStorage::settings is in children (stripped) but had no prune branch, so an empty node serialized to a bare SETTINGS that throws on re-parse, and the fuzzer silently skipped the query.
c Fix matches root cause? Yes. Strip+prune is now owner-driven and scoped to exactly the carriers InterpreterSetQuery::applySettingsFromQuery re-applies (SELECT, INSERT, ASTQueryWithOutput, ASTStorage, ASTBackupQuery), so both missed carriers are stripped and pruned in one traversal. No band-aid branch.
d Test intent preserved / new tests added? Yes. The three earlier RemoveSettingsFromQuery tests are unchanged and still pass. New gtest covers BACKUP (empty-clause prune + async survivor), CREATE storage (prune miss + engine-setting survivor), and CREATE AS SELECT. 04344 gains a BACKUP and a CREATE storage-settings seed.
e Both directions demonstrated? Yes. Negative: old children-only strip rebuilt (4d726860) -> new test FAILS exactly as the review described, old 3 pass. Positive: fix rebuilt (479ac859, reverted with no residue) -> all 4 pass. E2E: 04344 via clickhouse-local (ast_fuzzer_runs=30) -> reference match, 1992 ms, bounded, RC=0.
f Fix is general, not a narrow patch? Yes. Enumerated every SETTINGS carrier and every unconditional-SETTINGS formatter. The fix mirrors the authoritative carrier set of applySettingsFromQuery rather than patching just the 2 reported owners, and it stops blanket-stripping non-carrier SETTINGS (refresh strategy, dictionary, column declarations, standalone SET), removing the latent bare-SETTINGS risk for those too.

Session id: cron:clickhouse-worker-slot-2:20260623-002200

Comment thread src/Interpreters/executeQuery.cpp Resolved
max_rows_to_read is only checked after a source emits a chunk, so it
bounds the number of chunks but not the size of the first one. For a
trivial INSERT ... SELECT into a table that prefers large blocks,
InterpreterInsertQuery::applyTrivialInsertSelectOptimization copies
min_insert_block_size_rows (default ~1M) into the SELECT's max_block_size,
so a fuzzed numbers(100) inflated to numbers(~1M) can push one ~1M-row
block into the part writer in a single pipeline task before
read_overflow_mode = break cancels further reads. The executor cancel
callback only runs between tasks, so it cannot interrupt that block, and
the query can still spend minutes in one task (the recurring stress-test
hung check).

Pin max_block_size and min_insert_block_size_rows small on the fuzz
context so the first emitted chunk is bounded too, and add both names to
the stripped set so a fuzzed SETTINGS min_insert_block_size_rows = <large>
(or = DEFAULT, which would reset the pinned small value back to the ~1M
default) cannot re-inflate the first chunk. They get the same changes /
default_settings / repeated / all-carrier coverage as the other limits.

Add a gtest case (RemoveSettingsFromQuery.StripsBlockFormingOverrides) and
a trivial INSERT ... SELECT seed to 04344.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (block-forming settings, commit 2cd7b21)

# Question Answer
a Deterministic repro? Yes (gtest). RemoveSettingsFromQuery.StripsBlockFormingOverrides exercises the strip half for max_block_size/min_insert_block_size_rows across value/= DEFAULT/repeated/INSERT-carrier; the E2E grind is the CI-only flaky-check 300s timeout already observed on this test's seed at baeec9c (debug + heavy parallelism), which the row cap alone did not bound.
b Root cause explained? max_rows_to_read is checked only after a source emits a chunk, so it bounds the chunk count, not the first chunk's size. For a trivial INSERT ... SELECT into a table that prefers large blocks, InterpreterInsertQuery::applyTrivialInsertSelectOptimization copies min_insert_block_size_rows (default ~1M) into the SELECT's max_block_size, so one ~1M-row block reaches the part writer in a single pipeline task before read_overflow_mode = break fires; the cancel callback runs only between tasks, so it cannot interrupt that block.
c Fix matches root cause? Yes. Pin max_block_size and min_insert_block_size_rows to DEFAULT_BLOCK_SIZE (65409, < the 100000 read cap) on the fuzz context so the first chunk is bounded, and strip both names from the query so a fuzzed = <large>/= DEFAULT cannot re-inflate them. Directly bounds the first-chunk size the bot identified.
d Test intent preserved / new tests added? All 4 existing RemoveSettingsFromQuery.* tests unchanged and pass. New gtest StripsBlockFormingOverrides added; 04344 gains a trivial INSERT ... SELECT seed requesting a 1M-row block (reference unchanged, no stdout).
e Both directions demonstrated? Yes. Positive: 5/5 RemoveSettingsFromQuery.* pass (unit_tests build-id 004192a8); E2E 04344 = 4950/4950/4950/1, ~3s, and ~9-28s at 5x ast_fuzzer_runs. Negative: dropping the two names from the test's stripped set makes StripsBlockFormingOverrides fail (override survives, count=2 for the repeated case), other 4 pass; restoring reverts the build-id to 004192a8 (no residue).
f Fix is general, not a narrow patch? Yes. Both block-forming names go through the same changes/default_settings/repeated/all-carrier (removeSettingsFromQuery) coverage as the other six limits, and are pinned on the fuzz context the same way, so every override path is closed, not just the reported INSERT case.

Session id: cron:clickhouse-worker-slot-2:20260623-015700

@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.40% +0.10%
Functions 92.50% 92.60% +0.10%
Branches 77.50% 77.60% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 332/341 (97.36%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on 2cd7b21bcdd2. No failure is introduced by this PR:

  • Stress test (arm_tsan) "Hung check failed, possible deadlock found": chronic trunk-wide stress flake (server-side AST fuzzer runaway, not a deadlock), ~289 master hits / 30d. This is the exact class this PR limits/cancels.
  • CH Inc sync: internal mirror sync, not a merge gate.
    The four flaky-check jobs and the new test 04344 are green.

@groeneai

groeneai commented Jun 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

Correction to my earlier triage of this failure (thanks @tiandiwonder for the full-log pointer):

CI finished on 2cd7b21bcdd2. One failure, not caused by this PR:

This PR and #108353 are complementary: this one bounds the numbers-to-MergeTree wide-part-writer INSERT grind (the dominant class across the 30 hung_check.log artifacts), #108353 makes the primes source itself interruptible.

The 4 flaky-check variants of the new 04344 seed pass on this head; Finish Workflow and Mergeable Check are green.

@tiandiwonder tiandiwonder self-assigned this Jun 24, 2026
@tiandiwonder

Copy link
Copy Markdown
Contributor

FYI — the full hung_check.log for sha 2cd7b21 shows the actual hung query (the Found hung queries in processlist dump) is SELECT prime FROM primes(...) stuck in PrimesSource::generate, not the QueryAnalyzer::resolveExpressionNodeList truncated-tail stack cited above — that primes source ignores cancellation, and the executor cancel-callback added here can't interrupt a single uninterruptible generate. Fixed in #108353.

@tiandiwonder tiandiwonder left a comment

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.

optional: the description says "Two changes" but the landed diff has four mechanisms.

The removeSettingsFromQuery strip (src/Parsers/stripQuerySettings.* + the gtests) and the block-forming caps are the bulk of the change and aren't mentioned, so a reviewer opening src/Parsers/ won't know why it's touched. A sentence on why the caps also have to be stripped from the fuzzed query's own SETTINGS (a fuzzed max_rows_to_read = 0/= DEFAULT would otherwise lift them) would help.

Comment on lines +2200 to +2201
fuzz_context->setSetting("max_block_size", Field(UInt64(65409)));
fuzz_context->setSetting("min_insert_block_size_rows", Field(UInt64(65409)));

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.

optional: 65409 is exactly DEFAULT_BLOCK_SIZE (Core/Defines.h) — better to use the named constant so the intent ("pin block size back to the default after stripping the query's override") is clear and it doesn't drift if the default changes.

max_block_size's own default is already DEFAULT_BLOCK_SIZE, so that line only re-pins; min_insert_block_size_rows (default ~1M) is the real reduction.

return true;
if (process_list_element && !process_list_element->checkTimeLimitSoft())
return true;
return fuzzed_query_watch.elapsedMilliseconds() > 30000;

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.

optional: pull the 30000 ms deadline into a named local (e.g. fuzzed_query_deadline_ms) — it's a bare magic number here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

You're right, and thanks for the full-log pointer. Confirmed in the source: PrimesSource::generate only calls progress() after its while loop fills a block, and a large step makes the inner if (cur_prime_index < next_selected_index) continue; path spin through next() astronomically without emitting a chunk. So nothing in this PR can bound it: max_rows_to_read is checked only after a source emits a chunk, the block-forming caps bound chunk size not the skip count, and the executor cancel callback only runs between pipeline tasks. Your #108353 in-loop isCancelled() is the correct fix. I cited the QueryAnalyzer::resolveExpressionNodeList stack from a truncated log tail; corrected my CI-finish comment above to attribute it to primes and link #108353.

The two are complementary, not overlapping: this PR bounds the numbers-to-MergeTree wide-part-writer INSERT grind, which is the dominant class across the 30 hung_check.log artifacts behind #107941 (boundary-fuzzed numbers(100) to numbers(~1M) reading millions of rows through the part writer, is_cancelled: 1, elapsed 438-3004s). #108353 covers the un-cancellable-source case that the between-task callback can't reach. Keeping this PR as-is.

On the optional note: updated the description to list all four mechanisms (read cap, block-forming caps, cancel callback, and stripping the fuzzed query's own SETTINGS overrides of those caps) so the src/Parsers/ change is explained.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed from the hung_check.log artifact for 2cd7b21. You're right, and my earlier ledger note mis-cited the stack. The Found hung queries in processlist dump shows:

query:            SELECT prime FROM primes(3, 5, 2);
is_cancelled:     1
is_all_data_sent: 0
elapsed:          1492.2
stack:            PrimeGenerator.h:562  DB::PrimesSource::generate()
                  -> ISource::tryGenerate -> ISource::work
                  -> ... -> executeQuery.cpp:2241  DB::executeASTFuzzerQueries

So it ran via this PR's fuzzer path, cancellation was requested (is_cancelled = 1), but the in-flight PrimesSource::generate loop has no cancellation point and never returns, so the executor never regains control. That is exactly what #108353 fixes. The resolveExpressionNodeList tail I cited came from the auto-generated #107941 template body, not from this run.

The two changes look complementary rather than overlapping:

  • Make the primes table function respond to query cancellation #108353 makes the primes source honor cancellation, so a single uninterruptible generate returns.
  • This PR bounds the volume and block size of fuzzed reads, and supplies the cancel signal that Make the primes table function respond to query cancellation #108353's new isCancelled() check reads. It targets the other runaway class that has no per-source interrupt point: a trivial INSERT INTO MergeTree SELECT ... FROM numbers(N), where applyTrivialInsertSelectOptimization copies min_insert_block_size_rows (~1M) into the SELECT's max_block_size, so one ~1M-row block is pushed into the part writer in a single pipeline task. That was the 300s flaky-check timeout on this PR's own 04344 seed, fixed here by pinning max_block_size / min_insert_block_size_rows.

So #108353 covers the uninterruptible-source dimension and this PR caps the unbounded-volume dimension. Corrected ledger for 2cd7b21: the Stress test (arm_tsan) hung-check is fixed by #108353. Happy to defer to a maintainer if you would rather consolidate the two.

pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Jul 11, 2026
The test sets ast_fuzzer_any_query = 1, so the server-side AST fuzzer clones
each CREATE ~30 times reusing the real table's UUID. Those clones contend the
table's store/<uuid>/ directory, which slows the background drop worker.

Under the CI test profile database_atomic_wait_for_drop_and_detach_synchronously
is 1, so the trailing cleanup DROP TABLE waits in
DatabaseCatalog::waitTableFinallyDropped for that background worker. That wait
runs against the session max_execution_time = 20, and under the slowest
sanitizer (msan + WasmEdge) it can exceed 20s and fail with
Code: 159 TIMEOUT_EXCEEDED - a transient timeout on cleanup, not on anything the
test verifies.

Make the teardown DROPs asynchronous by pinning
database_atomic_wait_for_drop_and_detach_synchronously = 0 before them. The
fuzzed SELECT/INSERT queries still run under max_execution_time = 20 and the
fuzz-context resource caps, so the test still proves the server-side AST fuzzer
honors the insert/read limits; only the cleanup no longer blocks on the
synchronous drop wait.

Related: ClickHouse#108212

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-cancel-server-ast-fuzzer-queries

Limit and cancel in-flight queries in the server-side AST fuzzer
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`PrimesSource::generate` / `PrimesSimpleRangedSource::generate`
(src/Processors/Sources/SourceFromPrimes.h) run a `while (written < target)`
loop calling the prime generator's `next` with no cancellation point. A large
`step` (or `limit`) makes the loop call `next` an astronomical number of times
to skip to the next selected prime index, so a single `generate` call never
returns. The pipeline executor only checks cancellation and time limits between
`generate` calls, so a cancelled, KILLed or timed-out query keeps spinning
(observed as a query stuck with `is_cancelled = 1` and no progress in
`read_rows`). `next` itself is bounded (segment size 2^19, prime gaps are far
smaller), so the long pole is the `generate` loop.

Check `isCancelled` at the top of both loops. It is a cheap atomic load, set by
the executor on KILL / max_execution_time / shutdown, and each iteration already
does a bounded `next`, so the overhead is negligible.

This was the hung query behind a `Stress test (arm_tsan)` "Hung check failed,
possible deadlock found" on PR ClickHouse#108212 (server-side AST fuzzer feeding boundary
arguments to `primes`).

Related: ClickHouse#108212

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The test sets ast_fuzzer_any_query = 1, so the server-side AST fuzzer clones
each CREATE ~30 times reusing the real table's UUID. Those clones contend the
table's store/<uuid>/ directory, which slows the background drop worker.

Under the CI test profile database_atomic_wait_for_drop_and_detach_synchronously
is 1, so the trailing cleanup DROP TABLE waits in
DatabaseCatalog::waitTableFinallyDropped for that background worker. That wait
runs against the session max_execution_time = 20, and under the slowest
sanitizer (msan + WasmEdge) it can exceed 20s and fail with
Code: 159 TIMEOUT_EXCEEDED - a transient timeout on cleanup, not on anything the
test verifies.

Make the teardown DROPs asynchronous by pinning
database_atomic_wait_for_drop_and_detach_synchronously = 0 before them. The
fuzzed SELECT/INSERT queries still run under max_execution_time = 20 and the
fuzz-context resource caps, so the test still proves the server-side AST fuzzer
honors the insert/read limits; only the cleanup no longer blocks on the
synchronous drop wait.

Related: ClickHouse#108212

Co-Authored-By: Claude Opus 4.8 <[email protected]>
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-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.

5 participants