Repository navigation
Conversation
`FuzzQuerySource::createColumn` repeatedly fuzzes an AST until `block_size`
rows have been produced. The current loop has no upper bound on retries:
- The existing `if (config.max_query_length > 500)` guard always resets
`fuzz_base = query` and `continue`s when the cap is large, so `row_num`
never increments. Any `SELECT FROM fuzzQuery(..., > 500)` query hangs.
- With a tighter `if (fuzzed_text.size() > config.max_query_length)` check
(under review in ClickHouse#101354), the loop can also spin when no fuzzed AST
fits the cap, e.g. when the unmutated query already exceeds it.
Either way the loop produces no rows. The thread is also stuck in
`createColumn`, which never checks `isCancelled`, so `KILL QUERY`,
`max_execution_time`, and Stress test's hung check cannot stop it. The
ClickHouse#101354 CI run hit this via the server-side AST fuzzer
mutating the test query's `max_query_length` literal.
This patch caps retries per row at 100 attempts. When the budget is
exhausted, the source emits the original (unfuzzed) query as a fallback
row so progress is always made. `isCancelled` is also checked at the top
of the loop so the source responds to query cancellation; if the source is
cancelled mid-block, remaining rows are filled with the unfuzzed query to
keep the chunk size invariant (the cancelled pipeline discards the chunk).
Adds `04143_fuzz_query_no_infinite_loop` covering caps above 500, at the
old 500 threshold, and below the unmutated query length.
Hung CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101354&sha=5da866fbdbe5ef63d3498b9030b65987626e9dce&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29
Related: ClickHouse#101354
Co-authored-by: Alexey Milovidov <[email protected]>
Pre-PR validation gateSession id: a) Deterministic repro? Yes.
b) Root cause explained? Yes. c) Fix matches root cause? Yes. Cap retries per row at 100. When the budget is exhausted, emit the unfuzzed d) Test intent preserved? / New tests added? New tests added.
No existing test is changed, no assertion is widened, no e) Both directions demonstrated? Yes.
f) Fix is general, not a narrow patch? Yes. The bound is on the I have not searched for other |
|
cc @alexey-milovidov @azat — could you review this? Bounds the retry loop in |
|
Workflow [PR], commit [b704364] Summary: ❌
AI ReviewSummaryThis PR fixes the ClickHouse Rules
Final Verdict
|
| /// `block_size` offsets. If we exited early due to cancellation, fill the remaining rows | ||
| /// with the unfuzzed query so the chunk size invariant holds; the cancelled pipeline | ||
| /// will discard the chunk anyway. | ||
| if (row_num < block_size) |
There was a problem hiding this comment.
isCancelled is checked here, but the code below still backfills all remaining rows with fallback_text before returning. That turns cancellation into potentially huge extra work (block_size * query_length bytes copied) and can delay/defeat KILL QUERY / timeout handling under large max_block_size or long input query strings.
Can we avoid backfilling on cancellation (for example by returning an empty Chunk from generate when cancelled, or by returning row_num instead of always block_size so createColumn can stop immediately)?
Address bot inline review on PR ClickHouse#103742: the previous fix backfilled the remaining rows of the chunk with the unfuzzed query when the loop exited early due to cancellation. That meant `KILL QUERY` / `max_execution_time` cancellation still paid `O(block_size * query_length)` extra work before the source returned, defeating fast cancel response. This commit drops the backfill. `createColumn` resizes the offsets to the actual row count and returns the partial column. `generate` checks `isCancelled` upfront and after each `createColumn`; if a column is short, it returns an empty `Chunk`, which the pipeline treats as end-of-stream. The previous commit's bounded retries still guarantee that uncancelled queries always make progress. No SQL-level behavior change for non-cancelled queries: the existing regression test `04143_fuzz_query_no_infinite_loop` still passes 50/50 with `--test-runs 50`. Cancellation latency check: with `max_block_size = 65536`, `SELECT count() FROM (SELECT * FROM fuzzQuery('<200-term sum>', 100000, 42) LIMIT 1)` returns in ~70 ms; `max_execution_time = 1s` on an unbounded scan exits within ~5 ms of the deadline. Reviewer: clickhouse-gh[bot] PR: ClickHouse#103742
|
Thanks for the catch — pushed a follow-up commit that drops the backfill (commit 47c2def). What changed:
Verification:
|
| continue; | ||
| } | ||
|
|
||
| ++attempts_for_current_row; |
There was a problem hiding this comment.
max_attempts_per_row bounds the infinite loop, but this path still does 100 full fuzz attempts for every row when max_query_length > 500 because the check below is unconditional on fuzzed_text.size():
if (config.max_query_length > 500)
{
fuzz_base = query;
continue;
}That makes fuzzQuery(..., > 500) return eventually but with avoidable O(100 * block_size) extra fuzzing work (and each attempt formats/clones ASTs). Can we fold the length condition into this PR (for example if (fuzzed_text.size() > config.max_query_length)) or otherwise short-circuit to emit fallback immediately for this known-always-rejected branch?
Folds in the source-code changes from PR ClickHouse#101354 in response to the bot review on PR ClickHouse#103742 ("wasted attempts at max_query_length > 500"). Two combined changes: 1. Replace the lazy `if (config.max_query_length > 500)` guard with the precise `if (fuzzed_text.size() > config.max_query_length)` check. The old guard was a coarse heuristic: it triggered the reset branch whenever the cap was larger than 500, regardless of the actual fuzzed AST size. With the 100-attempt cap added in 614df1d the source no longer hangs, but every row in the `cap > 500` case still does 100 full fuzz-and-format cycles before falling back to the unfuzzed query — `O(max_attempts_per_row * block_size)` wasted work per scan. The precise check resets only when the produced fuzzed text actually exceeds the cap. For the common case `cap > 500` with a small input query, the loop now produces a row on the first attempt: SELECT count() FROM (SELECT * FROM fuzzQuery('SELECT 1', 1000, 42) LIMIT 1000); -- 113 ms (vs ~10 s with 100 wasted attempts per row). The 100-attempt cap stays in place as defense-in-depth for genuine oversized-variant cases (e.g. `max_query_length = 1`, where every non-trivial mutation overflows). 2. Reject `max_query_length = 0` in `getConfiguration` with `BAD_ARGUMENTS`. With cap = 0, every non-empty fuzzed AST exceeds the cap by definition, so the source would degrade to emitting the unfuzzed query for every row (after `max_attempts_per_row` retries). That is a no-op fuzzer with extra cost; the user clearly did not mean to ask for it. Both changes were originally proposed in PR ClickHouse#101354 (ClickHouse#101354). With them folded in here, PR ClickHouse#101354 only needs to keep its workflow / CI re-enablement bits. Test: - `04143_fuzz_query_no_infinite_loop` adds a fourth scenario for the `max_query_length = 0` `BAD_ARGUMENTS` rejection. - 50/50 passes via `clickhouse-test --test-runs 50`. - `fuzzQuery('SELECT 1', 1000, 42) LIMIT 1000` returns in 113 ms. - `max_execution_time = 1` exits within ~5 ms of the deadline. Bot review: ClickHouse#103742 (comment) Related: ClickHouse#101354 Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Addressed the second bot inline concern (wasted attempts at What changed in this commit:
Both source-code changes are folded in from PR #101354. With this commit, PR #101354 only needs to keep its workflow / CI re-enablement bits. Pre-PR validation gate (combined: all three commits): a) Deterministic repro? ✅ Without fix: b) Root cause explained? ✅ The lazy guard c) Fix matches root cause? ✅ Direct: replaces the bad heuristic with a precise check. The 100-attempt cap is kept as defense-in-depth for the small-cap case where the fuzzer keeps producing oversized variants. d) Test intent preserved? ✅ e) Both directions demonstrated? ✅ 50/50 test runs. Cancellation: f) Fix is general? ✅ Single fault location in cc @alexey-milovidov @azat @PedroTadim — ready for review. |
|
|
||
| if (attempts_for_current_row >= max_attempts_per_row) | ||
| { | ||
| auto fallback_text = query->formatForErrorMessage(); |
There was a problem hiding this comment.
max_query_length is documented as a maximum output length, but this fallback writes the original query even when its length is above the cap (the new test with cap = 1 relies on this). That means the setting silently stops being enforced in exactly the cases where fuzzing cannot satisfy it.
Can we keep the contract strict here? A concrete option is to reject impossible configs up front in getConfiguration: if the formatted base query length is already greater than max_query_length, throw BAD_ARGUMENTS instead of returning oversized rows.
Validate in `getConfiguration` that the formatted base query already fits within `max_query_length`. If not, no fuzzed variant can satisfy the cap either: the loop in `FuzzQuerySource::createColumn` would exhaust its retries and fall back to the unfuzzed query, silently emitting oversized rows that violate the documented output-length invariant. Reject the impossible configuration at construction time with `BAD_ARGUMENTS` so callers see a clear error at table / table-function construction instead of an out-of-spec result at scan time. Update regression test `04143_fuzz_query_no_infinite_loop`: the previous "tiny cap" scenario was relying on the fallback path emitting the unfuzzed base query whose size exceeds the cap. Under the strict contract that scenario is rejected up front, so the test now asserts `BAD_ARGUMENTS`. The first two scenarios (cap=1000 and cap=501) still exercise the no-hang invariant for valid configurations. Addresses third bot inline review concern on PR ClickHouse#103742.
|
Third bot concern (contract violation on fallback) addressed in The bot is right: when Fix: moved the validation up front into This covers both call sites (storage engine Pre-PR validation gate (a–f) — all GREEN:
Recap of all three bot concerns now addressed in the branch:
|
| auto base_ast = parseQuery(parser, begin, end, "FuzzQuery base query", 0, DBMS_DEFAULT_MAX_PARSER_DEPTH, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS); | ||
|
|
||
| const size_t base_formatted_size = base_ast->formatForErrorMessage().size(); | ||
| if (base_formatted_size > configuration.max_query_length) |
There was a problem hiding this comment.
This new validation changes behavior for existing FuzzQuery tables, not only new ones: getConfiguration is also used while loading table metadata. A table that was previously valid (for example max_query_length smaller than the formatted base query) would now fail ATTACH/startup with BAD_ARGUMENTS.
Per ClickHouse compatibility rules, new enforcement on existing objects should be gated (for example by compatibility) or applied only to newly created objects. Could we avoid rejecting existing metadata here and keep strict validation only for new CREATE TABLE/table-function usage?
Adds a `LoadingStrictnessLevel mode` parameter to `StorageFuzzQuery::getConfiguration`
and only enforces the contract checks introduced in the previous commit (`max_query_length
== 0` and `formatted_base.size() > max_query_length`) when `mode < ATTACH`.
The previous commit threw `BAD_ARGUMENTS` unconditionally inside `getConfiguration`,
which is also called during table metadata load on `ATTACH` and server startup. Per the
ClickHouse backward-compatibility rule, new validation must not break existing objects:
a previously-tolerated configuration (e.g. `FuzzQuery('long-base-query', 1, ...)`) must
still attach after upgrade. The runtime is already safe in that case because the
`FuzzQuerySource` loop caps retries per row and falls back to the unfuzzed query.
The factory lambda now passes `args.mode` from `StorageFactory::Arguments`. The table
function path (`TableFunctionFuzzQuery::parseArguments`) keeps the default value
(`LoadingStrictnessLevel::CREATE`) since every `SELECT FROM fuzzQuery(...)` is a fresh
construction with no metadata to migrate.
Updated regression test `04143_fuzz_query_no_infinite_loop` to cover both directions:
- `CREATE TABLE` with bad config -> `BAD_ARGUMENTS`
- `ATTACH TABLE` with the same bad config -> succeeds (compat preserved)
Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Pushed What changed
This matches the existing convention in Pre-PR validation gate (a–f)
Branch state — five commits ahead of master
All four bot concerns now resolved. Waiting on CI + re-review. cc @alexey-milovidov @azat |
LLVM Coverage Report
Changed lines: 77.61% (52/67) · Uncovered code |
|
Superseded by #101354 (merged 2026-06-14), which folded equivalent The runtime hang and argument validation this PR targeted are now fixed on master, so closing rather than rebasing (as noted in the original description: whichever PR lands first, the other becomes a rebase). The only delta here not adopted upstream was gating the new validation behind |
Investigation of the hung check failure on #101354 (https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101354&sha=5da866fbdbe5ef63d3498b9030b65987626e9dce&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29) — the hung query was the new regression test from that PR, executed via
executeASTFuzzerQueries(ast_fuzzer_runs=5). The AST fuzzer mutated the test'smax_query_lengthliteral into a value that putFuzzQuerySource::createColumninto an unbounded retry loop, and the thread was unkillable because the loop never checksisCancelled. The same hang is reachable today on master without that PR by runningSELECT * FROM fuzzQuery('SELECT 1', 600, 42) LIMIT 1— the existingif (config.max_query_length > 500)guard resetsfuzz_baseon every iteration when the cap is large and never produces a row.Per @alexey-milovidov's request on #101354, sending the fix as a separate PR.
The change:
FuzzQuerySource::createColumnat 100 attempts. When the budget is exhausted, the source emits the original (unfuzzed) query as a fallback row so the loop always makes progress.isCancelledat the top of the loop so the source responds toKILL QUERY,max_execution_time, and Stress test's hung check. If the source is cancelled mid-block, remaining rows are filled with the unfuzzed query to keep theblock_sizeinvariant; the cancelled pipeline discards the chunk anyway.04143_fuzz_query_no_infinite_loopwith three scenarios that hang on master without this fix: cap above 500, cap right at 501, and a tiny cap below the unmutated query's formatted length.The fix is orthogonal to #101354. With either the existing
> 500guard or the tighterfuzzed_text.size() > config.max_query_lengthcheck from that PR, retries are bounded and the source always returns. Whichever PR lands first, the other becomes a small rebase.Verified locally:
SELECT * FROM fuzzQuery('SELECT 1', 600, 42) LIMIT 5returns in <1s with the fix; without it, it hangs (timeout 15exits 143).SELECT max(length(query)) <= 200, count() FROM (SELECT query FROM fuzzQuery('...', 200, 42) LIMIT 100) SETTINGS ast_fuzzer_runs = 5, ast_fuzzer_any_query = 1— completes in <1s.04143_fuzz_query_no_infinite_looppasses 50/50 with--test-runs 50.CI report referenced: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101354&sha=5da866fbdbe5ef63d3498b9030b65987626e9dce&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Documentation entry for user-facing changes