Skip to content

Bound retries in FuzzQuerySource to prevent hung queries - #103742

Closed
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-fuzz-query-hung-loop
Closed

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-fuzz-query-hung-loop

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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's max_query_length literal into a value that put FuzzQuerySource::createColumn into an unbounded retry loop, and the thread was unkillable because the loop never checks isCancelled. The same hang is reachable today on master without that PR by running SELECT * FROM fuzzQuery('SELECT 1', 600, 42) LIMIT 1 — the existing if (config.max_query_length > 500) guard resets fuzz_base on 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:

  • Cap retries per row in FuzzQuerySource::createColumn at 100 attempts. When the budget is exhausted, the source emits the original (unfuzzed) query as a fallback row so the loop always makes progress.
  • Check isCancelled at the top of the loop so the source responds to KILL 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 the block_size invariant; the cancelled pipeline discards the chunk anyway.
  • Add 04143_fuzz_query_no_infinite_loop with 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 > 500 guard or the tighter fuzzed_text.size() > config.max_query_length check 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 5 returns in <1s with the fix; without it, it hangs (timeout 15 exits 143).
  • The PR Revert "Temporarily disable server-side AST fuzzer in Stress Test and BuzzHouse [2]" #101354 hang shape — 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_loop passes 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):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

`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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Session id: cron:clickhouse-ci-task-worker:20260429-201500

a) Deterministic repro? Yes.

  • Master HEAD: timeout 15 build/programs/clickhouse client -q "SELECT count() FROM (SELECT * FROM fuzzQuery('SELECT 1', 600, 42) LIMIT 5)" exits 143 (SIGTERM), thread is in FuzzQuerySource::createColumn and the query is not killable via KILL QUERY or max_execution_time.
  • The hung CI run on Revert "Temporarily disable server-side AST fuzzer in Stress Test and BuzzHouse [2]" #101354 matches: hung_check.log shows the stuck query is the new 04141_fuzz_query_max_query_length regression test executed via executeASTFuzzerQueries (ast_fuzzer_runs=5), elapsed 2178s, is_cancelled=1, stack inside FuzzQuerySource::createColumn → FuzzQuerySource::generate → ... → executeASTFuzzerQueries.

b) Root cause explained? Yes. FuzzQuerySource::createColumn runs while (row_num < block_size) with no upper bound on retries. The if (config.max_query_length > 500) guard always resets fuzz_base = query and continues when the cap is large, so row_num never increments. With the tighter if (fuzzed_text.size() > config.max_query_length) check from #101354 the loop also spins when no fuzzed AST fits the cap (e.g. cap below the unmutated query's formatted length). In both shapes the loop produces zero rows and the thread is stuck in user code with no isCancelled check.

c) Fix matches root cause? Yes. Cap retries per row at 100. When the budget is exhausted, emit the unfuzzed query as a fallback row and reset for the next row — guarantees forward progress regardless of which size check is active. Add isCancelled at the top of the loop so query cancellation works; on cancellation, fill the remaining rows with the unfuzzed query to preserve the block_size invariant (the cancelled pipeline discards the chunk).

d) Test intent preserved? / New tests added? New tests added. 04143_fuzz_query_no_infinite_loop covers three previously hung shapes:

  • cap = 1000 (master > 500 resets always),
  • cap = 501 (one above the threshold),
  • cap = 1 with a base query of ~45 chars (fuzzer always exceeds the cap).
    All three return 5 rows with the fix; without it they hang.

No existing test is changed, no assertion is widened, no no-random-* tag is added.

e) Both directions demonstrated? Yes.

  • Without fix (master HEAD StorageFuzzQuery.cpp): timeout 15 ... fuzzQuery('SELECT 1', 600, 42) exits 143; query stays in system.processes forever after KILL QUERY runs.
  • With fix: the same query returns 5 rows in <1s. 04143_fuzz_query_no_infinite_loop passes 50/50 via clickhouse-test --test-runs 50. The PR Revert "Temporarily disable server-side AST fuzzer in Stress Test and BuzzHouse [2]" #101354 hang shape (SELECT max(length(query)) <= 200, count() FROM (SELECT query FROM fuzzQuery('SELECT 1 + ... + 10', 200, 42) LIMIT 100) SETTINGS ast_fuzzer_runs = 5, ast_fuzzer_any_query = 1) returns in <1s.

f) Fix is general, not a narrow patch? Yes. The bound is on the createColumn retry loop itself, not on the configuration entry, so it covers both observed hang shapes (large-cap-always-reset and small-cap-never-fits) and any other future shape where fuzzing cannot fit the cap. The isCancelled check is added so any future hang in this code path is interruptible by KILL QUERY and Stress test's hung check rather than requiring a server kill.

I have not searched for other while (...) loops in Storages/Storage*Query.cpp that could spin without a cancellation check — flagging this as follow-up if reviewers want it audited.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @azat — could you review this? Bounds the retry loop in FuzzQuerySource::createColumn and adds isCancelled so fuzzQuery(..., > 500) and similar shapes stop hanging. Triggered by the hung check on #101354.

@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label Apr 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b704364]

Summary: ❌

job_name test_name status info comment
Unit tests (tsan, function_prop_fuzzer) FAIL

AI Review

Summary

This PR fixes the fuzzQuery hang by bounding per-row retries, making cancellation responsive, replacing the old > 500 reset condition with a real length check, and adding create-time validation for impossible configurations while preserving ATTACH compatibility for existing metadata. I did not find additional high-confidence issues to report beyond the inline concerns already posted by clickhouse-gh[bot].

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Apr 30, 2026
/// `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)

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.

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
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the catch — pushed a follow-up commit that drops the backfill (commit 47c2def).

What changed:

  • FuzzQuerySource::createColumn now resizes offsets to the actual row count on cancellation (no O(block_size * query_length) backfill).
  • FuzzQuerySource::generate checks isCancelled upfront and after each createColumn call, and returns an empty Chunk if any column is short. The pipeline treats this as end-of-stream and stops pulling.
  • The previous commit's bounded retries still guarantee non-cancelled queries always make progress.

Verification:

  • Existing regression test 04143_fuzz_query_no_infinite_loop: 50/50 passes with --test-runs 50.
  • Cancellation latency 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 (1004 ms total).

cc @alexey-milovidov @azat

continue;
}

++attempts_for_current_row;

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.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed the second bot inline concern (wasted attempts at max_query_length > 500) in commit 12d7ed385567. With this and the previous two commits, both bot concerns are resolved.

What changed in this commit:

  1. Replaced the lazy if (config.max_query_length > 500) guard with the precise if (fuzzed_text.size() > config.max_query_length) check from PR Revert "Temporarily disable server-side AST fuzzer in Stress Test and BuzzHouse [2]" #101354. The old guard always reset fuzz_base = query when the cap was > 500, regardless of the actual fuzzed size — which meant the 100-attempt cap was paying O(max_attempts_per_row * block_size) of fuzz/format cost per scan before falling back. 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 produces a row on the first attempt.

  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) — a no-op fuzzer with extra cost.

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: SELECT * FROM fuzzQuery('SELECT 1', 600, 42) LIMIT 1 hangs forever on master (commits 1+2 made it terminate, commit 3 makes it correct). With fix: returns in <1 s. Wasted-attempts case (LIMIT 1000 with cap = 1000): 113 ms with fix, would be ~10 s with the old > 500 guard + 100-attempt cap.

b) Root cause explained? ✅ The lazy guard config.max_query_length > 500 was a coarse heuristic that conflated two distinct conditions: "cap is large" and "fuzzed text exceeds cap". For cap > 500, every iteration took the reset branch, never producing a row (the original hang). With the 100-attempt cap, every row paid 100 wasted fuzz attempts (the second bot concern). Replacing the guard with fuzzed_text.size() > config.max_query_length directly addresses both. max_query_length = 0 is a degenerate input that produces a no-op fuzzer with extra cost — rejected up front.

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? ✅ 04143_fuzz_query_no_infinite_loop adds a fourth scenario (max_query_length = 0 → BAD_ARGUMENTS); the original 3 scenarios (cap = 1000, cap = 501, cap = 1) still pass.

e) Both directions demonstrated? ✅ 50/50 test runs. Cancellation: max_execution_time = 1 exits within ~5 ms of deadline (cancellation latency is now ≤ block_size of pre-cancel work, plus header allocation).

f) Fix is general? ✅ Single fault location in FuzzQuerySource::createColumn and one input-validation location in StorageFuzzQuery::getConfiguration. Searched for sibling max_query_length > 500 and similar heuristics — none. Defense-in-depth (100-attempt cap, partial-column shrink on cancel, BAD_ARGUMENTS on cap=0) covers the remaining edge cases.

cc @alexey-milovidov @azat @PedroTadim — ready for review.


if (attempts_for_current_row >= max_attempts_per_row)
{
auto fallback_text = query->formatForErrorMessage();

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.

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Third bot concern (contract violation on fallback) addressed in 1060162e6642.

The bot is right: when max_query_length is below the formatted base query's length, the fallback path emitted the original query whose size already exceeded the cap, silently violating the documented max_query_length output-length contract. Test 4 in the previous push (cap = 1 with a long base query) was relying on exactly that broken fallback.

Fix: moved the validation up front into StorageFuzzQuery::getConfiguration, mirroring the existing max_query_length == 0 rejection. The check parses the base query, formats it, and rejects with BAD_ARGUMENTS if formatForErrorMessage().size() > max_query_length. After the check passes, every subsequent emission path — fuzzed variants (precisely bounded by the in-loop fuzzed_text.size() > config.max_query_length check) and the per-row fallback (which re-emits the original query) — is guaranteed to satisfy the cap, so the contract is preserved without weakening it.

This covers both call sites (storage engine CREATE TABLE and table function SELECT FROM fuzzQuery(...)) since TableFunctionFuzzQuery::parseArguments delegates to the same StorageFuzzQuery::getConfiguration. The single-shot SQL function FunctionFuzzQuery doesn't have a max_query_length parameter and is unaffected.

Pre-PR validation gate (a–f) — all GREEN:

  • (a) Deterministic repro: SELECT * FROM fuzzQuery('SELECT 1 + 2 + ... + 10', 1, 42) LIMIT 5 — without the fix returns 5 rows of 61 chars each (contract violation); with the fix throws Code: 36 BAD_ARGUMENTS: FuzzQuery max_query_length (1) is smaller than the formatted base query length (61); fuzzer cannot produce any rows that satisfy the cap.
  • (b) Root cause: for max_query_length < format(base_query).size() no fuzzed variant can fit the cap; the 100-attempt fallback then emits the unfuzzed base query whose size > cap → contract violation. The fix removes the impossible state at construction.
  • (c) Fix matches root cause: rejection happens at the configuration boundary, before any source pipeline runs. Same shape as the existing max_query_length == 0 rejection.
  • (d) Test intent preserved: scenarios cap=1000 and cap=501 still exercise the no-hang invariant under valid configurations. The cap=1 scenario is now rejected up front (which is the correct contract). The cap=0 scenario remains a serverError BAD_ARGUMENTS assertion.
  • (e) Both directions demonstrated: test 04143 passes 50/50 with randomization; sibling test 03834 still passes 20/20.
  • (f) Fix is general: boundary check confirmed at exact cap (cap=8 with 'SELECT 1' 8 chars passes), one byte under (cap=7, 8 chars rejected), and zero (rejected by the existing check). Both call paths (storage and table function) covered.

Recap of all three bot concerns now addressed in the branch:

  1. 47c2deff75bd — drop cancellation backfill; return empty Chunk on cancel (1st concern: KILL/timeout latency)
  2. 12d7ed385567 — replace if (config.max_query_length > 500) with precise if (fuzzed_text.size() > config.max_query_length); reject max_query_length = 0 (2nd concern: O(100×block_size) wasted fuzz attempts; folds in the tighter check from Revert "Temporarily disable server-side AST fuzzer in Stress Test and BuzzHouse [2]" #101354)
  3. 1060162e6642 — enforce max_query_length contract up front in getConfiguration (3rd concern: silent oversized rows on fallback)

cc @alexey-milovidov @azat

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)

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.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed b704364cd8a3 to address the fourth bot concern (backward compatibility for existing FuzzQuery tables).

What changed

StorageFuzzQuery::getConfiguration now takes a LoadingStrictnessLevel mode parameter (default CREATE). The two new contract checks introduced in the previous commit (max_query_length == 0 and formatted_base.size() > max_query_length) only fire when mode < ATTACH. The factory lambda passes args.mode from StorageFactory::Arguments; the table function path keeps the default since every SELECT FROM fuzzQuery(...) is a fresh construction.

This matches the existing convention in StorageStripeLog, StorageKafka, and others (if (mode < LoadingStrictnessLevel::ATTACH)). The runtime is already safe in the lenient case — the FuzzQuerySource loop caps retries per row and falls back to the unfuzzed query — so an attached table with a stale configuration cannot hang or corrupt anything.

Pre-PR validation gate (a–f)

  • (a) Deterministic repro? Yes. CREATE: CREATE TABLE fq_t (q String) ENGINE = FuzzQuery('SELECT 1+2+3+4+5+6+7+8+9+10', 1, 42) -> BAD_ARGUMENTS. ATTACH (Ordinary DB): same args -> succeeds.
  • (b) Root cause explained? getConfiguration is called from both the CREATE path (mode=CREATE) and the ATTACH path (mode=ATTACH or higher) of the storage factory. Unconditional validation rejected previously-tolerated metadata at server startup, breaking the backward-compatibility rule.
  • (c) Fix matches root cause? Yes — gates the new validation on mode < ATTACH, the standard ClickHouse pattern for "this is a fresh creation". Existing objects keep loading; new ones are validated.
  • (d) Test intent preserved? / New tests added? Yes — extended 04143_fuzz_query_no_infinite_loop with both directions: CREATE paths still throw BAD_ARGUMENTS, ATTACH TABLE name (cols) ENGINE = FuzzQuery(...) in an Ordinary database succeeds with the same bad args. The Ordinary DB is needed because ATTACH TABLE ... ENGINE = ... requires no pre-existing UUID there (Atomic requires UUID for full ATTACH).
  • (e) Demonstrated in both directions? Yes:
    • Without fix (HEAD~1): ATTACH TABLE ... ENGINE = FuzzQuery('SELECT 1+...', 1, 42) -> BAD_ARGUMENTS (broken compat).
    • With fix (HEAD): same ATTACH succeeds; CREATE still throws.
  • (f) Fix is general? Yes — single mode parameter handles all LoadingStrictnessLevel values: CREATE/SECONDARY_CREATE -> strict; ATTACH/FORCE_ATTACH/FORCE_RESTORE -> lenient. Both new validations (cap=0 and cap < base size) are gated together. Sibling test 03834 still passes (no regression). Original hang shape (fuzzQuery('SELECT 1', 600, 42) LIMIT 1) still returns in ~70ms; wasted-attempts proof (LIMIT 1000 at cap=1000) returns in ~113ms; cancellation latency under max_execution_time=1s exits within ~5ms of the deadline.

Branch state — five commits ahead of master

  • b704364cd8a3 StorageFuzzQuery: gate strict validation to fresh creation only ← this run, 4th bot concern (compat)
  • 1060162e6642 StorageFuzzQuery: enforce max_query_length contract up front (3rd bot concern)
  • 12d7ed385567 FuzzQuerySource: precise size check + reject max_query_length=0 (2nd bot concern, folds in Revert "Temporarily disable server-side AST fuzzer in Stress Test and BuzzHouse [2]" #101354's check)
  • 47c2deff75bd FuzzQuerySource: drop cancellation backfill; return empty Chunk (1st bot concern)
  • 614df1d6a0a0 Bound retries in FuzzQuerySource to prevent hung queries (original hang fix)

All four bot concerns now resolved. Waiting on CI + re-review. cc @alexey-milovidov @azat

@clickhouse-gh

clickhouse-gh Bot commented Apr 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.00% -0.10%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 77.61% (52/67) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Superseded by #101354 (merged 2026-06-14), which folded equivalent FuzzQuerySource fixes into master: the max_query_length == 0 and base_formatted_size > max_query_length BAD_ARGUMENTS checks, bounded per-row retries with an unfuzzed-query fallback, cancellation-aware column truncation, and the regression test 04141_fuzz_query_max_query_length.

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 LoadingStrictnessLevel so pre-existing tables still ATTACH after upgrade. Leaving that to the maintainers, since #101354 intentionally validates unconditionally.

@groeneai groeneai closed this Jun 15, 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-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants