Repository navigation
Limit and cancel in-flight queries in the server-side AST fuzzer - #108212
alexey-milovidov merged 7 commits into
Conversation
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]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-4:20260622-181400 |
|
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). |
|
Workflow [PR], commit [2cd7b21] Summary: ❌
AI ReviewSummaryThis PR limits server-side AST fuzzer executions by stripping query-level overrides of the pinned safety settings, pruning empty Final VerdictStatus: ✅ Approve No required follow-up actions. |
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]>
Pre-PR validation gate (commit 250ae42 - settings-override fix)
Session id: cron:clickhouse-worker-slot-3:20260622-200300 |
…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]>
…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]>
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]>
…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]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-2:20260623-002200 |
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]>
Pre-PR validation gate (block-forming settings, commit 2cd7b21)
Session id: cron:clickhouse-worker-slot-2:20260623-015700 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 332/341 (97.36%) | Lost baseline coverage: none · Uncovered code |
|
CI finished on
|
|
Correction to my earlier triage of this failure (thanks @tiandiwonder for the full-log pointer): CI finished on
This PR and #108353 are complementary: this one bounds the The 4 flaky-check variants of the new |
|
FYI — the full |
tiandiwonder
left a comment
There was a problem hiding this comment.
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.
| fuzz_context->setSetting("max_block_size", Field(UInt64(65409))); | ||
| fuzz_context->setSetting("min_insert_block_size_rows", Field(UInt64(65409))); |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
optional: pull the 30000 ms deadline into a named local (e.g. fuzzed_query_deadline_ms) — it's a bare magic number here.
|
You're right, and thanks for the full-log pointer. Confirmed in the source: The two are complementary, not overlapping: this PR bounds the 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 |
|
Confirmed from the So it ran via this PR's fuzzer path, cancellation was requested ( The two changes look complementary rather than overlapping:
So #108353 covers the uninterruptible-source dimension and this PR caps the unbounded-volume dimension. Corrected ledger for |
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]>
…-cancel-server-ast-fuzzer-queries Limit and cancel in-flight queries in the server-side AST fuzzer
`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]>
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]>
Related: #107941
Related: #108353
Changelog category (leave one):
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.logartifacts 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::getRandomFieldrewrites numeric literals to boundary values (1024*1024 +/- 1,INT_MAX,INT64_MAX, ...), so a seednumbers(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 fuzzedCompletedPipelineExecutorhad no cancel callback, so it ignored the outer query's KILL/timeout (max_execution_timeis only checked between pipeline tasks). The outer query lingered in the processlist (elapsed438-3004s,is_cancelled: 1) and tripped the hung check.Changes, all confined to the fuzz context set up by
executeASTFuzzerQueries: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.max_block_sizeandmin_insert_block_size_rowssmall.max_rows_to_readis only checked after a source emits a chunk, andInterpreterInsertQuery::applyTrivialInsertSelectOptimizationcopiesmin_insert_block_size_rows(default ~1M) into the SELECT'smax_block_size, so without this one ~1M-row chunk could still reach the wide-part writer before the row cap fires.CompletedPipelineExecutora cancel callback bound to the outer query'sQueryStatus(KILL/timeout viacheckTimeLimitSoft), server shutdown, and a 30s wall-clock deadline, so an in-flight fuzzed query is cancelled between pipeline tasks (mirrors the normalexecuteTrivialBlockIOpath).src/Parsers/stripQuerySettings.{h,cpp}, with gtests): a fuzzed/seed query can put the same setting names in its ownSETTINGSclause, whichexecuteQueryImplre-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 thechangesand= DEFAULTlists, all repeated entries, and theSELECT/INSERT/ASTQueryWithOutput/ CREATE-storage /BACKUPsettings slots. It also prunes a settings node that becomes empty after stripping, so it does not reformat as a bareSETTINGS(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
primestable function itself respond to cancellation: a singlePrimesSource::generatecall can spin on a largestepwithout emitting a chunk, an un-cancellable-source mechanism that the between-task cancel callback here cannot reach). It also builds on the existingmax_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
26.7.1.204(included in26.7and later)