Repository navigation
Conversation
NamePrompter::getHints scores an unresolved name against every candidate with
levenshteinDistanceCaseInsensitive, an O(m*n) dynamic program with no early
exit, and nothing on that path checks cancellation. The work is unbounded in
three query-controlled dimensions: the length of the name, the number of
candidates (merge(REGEXP('.+'), '.+') unions the columns of up to
merge_table_max_tables_to_look_for_schema_inference tables, and
getAllRegisteredNames hands that whole union to the prompter), and the number
of calls (TreeRewriter.cpp:1303 calls getHints once per required column). A
query can therefore spend minutes building a string that is often never
emitted, and keeps going after it has been cancelled.
Observed as "Hung check failed, possible deadlock found" in Stress test
(amd_tsan): one row at elapsed 453.88, is_cancelled 1, read_rows 0, a single
thread, QueryProfilerRuns 889 at the 1 s default timer (so about 435 s of
thread CPU, spinning rather than blocked), and no "Missing columns" message
ever produced. The 60 s max_execution_time fired and the query continued for
another 6.5 minutes.
Two bounds, both in NamePrompter, which is the single chokepoint that all four
direct call sites and 44 IHints callers route through, so this covers every
hint path in the server and both analyzers:
- A per-call cumulative work limit of 50,000,000 dynamic-programming cells,
charged after the existing rejection guards (so rejected candidates are
free) and before the dynamic program (so an unaffordable call is never
paid for). Affordability is decided by division, comparing prompt.size()
against work_left / name.size(), so the product is never formed before it is
known to fit and cannot wrap. 50e6 cells is roughly 0.5 s under TSAN and
0.05 s in a release build, against the 435 s measured above, while a
realistic worst case of a 31-character name against a 10,000-column table
uses 9,920,000 cells, 19.8% of the limit, and still returns its hint.
Exhaustion returns no hints rather than breaking out of the loop: the
nearest candidate is only known once every candidate has been scored, and
TypoCorrection materializes candidates by iterating an unordered_set, so a
partial scan would return the nearest of a hash-order-dependent prefix.
- One CurrentThread::checkIfNotCancelled() per getHints call. The work limit
is per call and the caller loops, so a limit alone still lets N unresolved
names cost N times the limit. This is the pre-existing shared checkpoint,
already used in six places, and a no-op when there is no current_thread, so
hint paths outside a query (client command-line options, HTTP path hints)
are unaffected. It is not the per-function polling that was reverted
earlier.
Measured on two servers with 60 unresolved names and max_execution_time = 5:
before, 61 hint computations, 43.92e9 cells, 146.68 s, and the timeout ignored
(UNKNOWN_IDENTIFIER); after, 31 computations, 1.54e9 cells, 5.37 s,
TIMEOUT_EXCEEDED. Per call the limit cuts 720,000,000 cells to 49,680,000.
With the limit but without the checkpoint the query still runs 10.46 s and
still ignores the timeout, so neither bound is redundant.
The shared Levenshtein helper is deliberately untouched, so the two consumers
that need an exact distance (DatabaseCatalog cross-database ranking and the
nearest_hostname load balancer) keep exact values by construction.
Hint quality is unchanged: seven hint families (identifier, table, setting,
function, data type, table function, nested identifier) produce byte-identical
output. The new test covers the work limit and fails without it; the
cancellation half is not asserted in the suite because that would require a
wall-clock assertion.
…e test Follow-up to the two bounds in NamePrompter: close the two places where a cancelled query was still reported under the wrong error code, and make the new test discriminate what it claims to. The cancellation checkpoint ran only before scoring, so cancellation arriving during the scoring window was unobserved and the analyzer's UNKNOWN_IDENTIFIER beat the normalisation in executeQuery. Check on both exits instead, following the same shape as the trailing check in ConnectionEstablisher. On the exhaustion path a cancelled query now reports TIMEOUT_EXCEEDED rather than UNKNOWN_IDENTIFIER. The hint fallback in IDatabase::getCreateTableQuery wraps both isTableExist and getHintForTable in a catch-all that logs and rethrows the original UNKNOWN_TABLE, which discarded the cancellation exception. Re-assert cancellation there so that one reason propagates; the catch-all is deliberate (remote engines report CANNOT_GET_CREATE_TABLE_QUERY transiently) and keeps its behaviour for every other failure, verified byte-identical on five non-cancelled paths. The test failed deterministically in the old-analyzer job: the two analyzers render the suggestion with different capitalisation, the test greps case-sensitively, and the old-analyzer configuration sets allow_experimental_analyzer=0 in the server's default profile. Worse, grep -c returning 0 exits non-zero and set -e then aborted the script, so one line of output met a three-line reference. Pin the analyzer on every asserting query, as 04338_analyzer_unknown_table_cross_database_hint.sh already does. The two arms were 14.4M and 432M cells around a 50M limit, so any limit in that range produced identical output and the test pinned only the limit's existence. The arms now bracket it at 49.68M and 50.04M: halving the constant fails the first, doubling it fails the second. A fourth assertion covers the cancellation bound by its error code, with a one-sided margin of ~1.3s against ~10.2s of work the query would otherwise have to finish; it holds over 50 randomized runs and 8 concurrent copies.
The comment claimed every caller throws its unresolved-name exception as soon as getHints returns. Two callers do not: KeeperHTTPHandlerFactory constructs and returns a handler without throwing, and TableNameHints::getHintForTable keeps scanning candidates for visibility and then searches other databases. Both exit checkpoints stay. Each was measured to be independently load-bearing: parking a query at one exit site until its own max_execution_time elapses, so CancellationChecker cancels it through the ordinary path, and then deleting only that site, turns the reported error from TIMEOUT_EXCEEDED into UNKNOWN_IDENTIFIER on that path and leaves the other path unchanged. The entry check does not cover either exit, because a single hint computation returns before the next name's entry check runs.
…mally `IDatabase::getCreateTableQuery` re-asserts cancellation inside its `catch (...)`, which covers a cancellation raised *during* the hint work. It does not cover a cancellation that arrives after `NamePrompter::getHints` makes its last exit check and before the rethrow: the hint computation then returns normally, the catch is never entered, and the user is told the table is missing for a query that was in fact cancelled. That window is not a narrow instruction gap. `TableNameHints::isHintNameVisible` calls `tryGetTable`, which on ordinary and atomic databases waits synchronously for the matched table's load and startup job, for up to `max_hint_candidates` candidates per database across every database the user may `SHOW`. So the window can span foreground table loads after the query was already cancelled. Re-assert cancellation immediately before the rethrow, guarded on the existing `table_is_missing` flag so that an exception raised for any other reason - where no hint work ran - keeps being reported exactly as before. `is_killed` is sticky, so the second assertion is idempotent when the one in the catch already passed. Evidence: with a query parked past the prompter's last checkpoint until its own `max_execution_time` elapsed, the same fixture reports CANNOT_GET_CREATE_TABLE_QUERY without this statement and TIMEOUT_EXCEEDED with it, while the five non-cancelled paths (missing table with and without a hint, the getTable path, a successful SHOW CREATE, and SHOW CREATE DICTIONARY) stay byte-identical. A stateless test cannot cover this: the hint computation here is sub-millisecond, while CancellationChecker aligns deadlines to a 100 ms grid.
Internal second-model reviewIndependent review of this change: a cold read of the resulting code, then a second-model gate, over ❌ Fixed in this PR
|
| Finding | Verdict | Evidence |
|---|---|---|
| The 50M limit is a hardcoded threshold where the repository convention prefers a setting. | Kept a constant | Exhausting it only withholds an optional suggestion and never changes a result. The body names optimize_and_compare_chain_max_hash_work as the same kind of budget shipped as a setting, and I will switch if a reviewer prefers it. |
| This looks like the per-function cancellation-check pattern discussed on #112203. | Different pattern | Nothing is added inside the dynamic program, and none of the changed files is an IFunction, so vectorization and per-row cost are not in scope. Bounding the work product is the analogue of bounding an input for an O(m*n) cost. All 44 hint call sites are error paths, so neither bound can cost a successful query anything, and the reported carrier is a documented merge() schema union rather than a fuzzer-supplied string. |
DatabaseCatalog.cpp:2430 runs a second Levenshtein loop outside the bounded chokepoint. |
Not a second carrier | It re-scores only the candidates NamePrompter already returned, capped at max_hint_candidates = 10, and breaks at the first visible one, so its cost is bounded by the bounded call above it. |
| The exit-check comment claimed every caller throws immediately. | AGREE | Two callers do not (KeeperHTTPHandlerFactory.cpp:56 returns a handler; DatabaseCatalog.cpp:2362 continues processing). The claim is narrowed to the query-analysis callers, which is the justification the checkpoint needs. |
TableNameHints reads work-budget exhaustion as "no match", so it can fall back to a cross-database hint when the nearest local candidate is unknown; propagate an explicit exhaustion status instead. |
Not a defect | Exhaustion and a returnable local hint are mutually exclusive on the same call. work_left is a per-call local, and the budget is only ever exceeded by a candidate that would push the running total past it, at which point the queue is discarded. So an exhausted call is one that had already scored ~50M cells' worth of candidates; it never displaces a hint that would otherwise have been returned. The cross-database fallback on an empty local result is pre-existing and unchanged, and it yields a true, database-qualified name. The global comparison also stays exact: the ranking at DatabaseCatalog.cpp:2430 uses the untouched Levenshtein helper, and a database that exhausted contributes no candidate rather than a wrong one, which is the same nearest-of-a-subset shape as the three long-standing skips at :2412, :2415 and :2445. |
Three other TableNameHints callers can still report UNKNOWN_TABLE for a query cancelled during post-scoring visibility work; add trailing checkpoints inside both hint methods. |
Correct, and out of scope here | The finding notes that isHintNameVisible catches every exception, which is what makes its own remedy inert: DatabaseCatalog.cpp:2503-2514 wraps tryGetTable in an unconditional catch (...) { return false; } that a checkpoint there cannot escape. Doing this properly means narrowing that catch-all, which exists to stop hint formatting from replacing UNKNOWN_TABLE with an unrelated load error and guards a SHOW_DICTIONARIES name leak. That is its own change with its own review. The residual is bounded (at most max_hint_candidates = 10 visibility checks per database, entered only after the prompter observed no cancellation) and affects the reported error code, not termination, so it is disclosed here rather than folded in. |
💡 Noted, not blocking
max_execution_time's documentation says a query "cannot stop during most of query analysis
(establishing a connection to a remote replica is one place where it can)". This adds a second such
place. The sentence stays true, and it is autogenerated into a tracked file, so it is left alone.- Each of the two exit checkpoints and the
IDatabasere-check is individually exercised by
mutation rather than by a suite arm: one hint computation is bounded at ~0.18 s while cancellation
deadlines are aligned to a 100 ms grid, so a deterministic arm for a sub-window of a single call
does not exist and a timing-based one would flake. - Narrowing
isHintNameVisible's catch-all so a cancellation can propagate through the visibility
check would close the residual described above for the three non-SHOW CREATEcallers. I have not
done it here: it touches a deliberate fail-closed path that prevents a dictionary-only grant from
leaking table names, so it wants its own change. Happy to open one if that is wanted. - @PedroTadim, one thing I want to flag rather than have you find it. The last arm of the new test
passes--enable_analyzer=0, which cuts against what you told me on Do not use the trivial count optimization when the aggregate argument contains arrayJoin #115227 ("forget
enable_analyzer = 0, it's obsolete"). The reason is mechanical: that arm exists to show a cancelled
query stops while the caller loops over unresolved names, and that loop isTreeRewriter.cpp:1305,
reached only throughInterpreterSelectQuery. Under the current analyzer resolution stops at the
first unresolved identifier, so the same arm makes one hint call instead of sixty and stops testing
the thing it is there for. The three other arms all pin the analyzer to1. I would rather you chose
than have me guess: I can drop the arm (losing the only cancellation oracle in the suite, which is
why it was added), tag the testno-old-analyzerand keep it, or leave it as is.
Session id: cron:clickhouse-review-slot-10:20260825-125100
|
Workflow [PR], commit [ef93dbc] Summary: ❌
AI ReviewSummaryThis PR adds a cumulative work cap plus cancellation checkpoints around Findings
Final VerdictChanges needed: the main LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 30/32 (93.75%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260825-040500 |
|
cc @tavplubix @yakov-olkhovskiy, could you review this? A cancelled query could sit for minutes inside |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units2304 translation units recompiled, 13584 s compile time in total, 2304 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
The test ran 161 to 185 seconds under ThreadSanitizer against the 180 second per-test limit of the flaky check, so it failed about a fifth of its runs, while every other build finished it in 9 to 43 seconds. The job's own query log shows where the time went: 140 of those seconds were four queries whose cost is the Levenshtein work the hint limit is measured in, and 75 of those 140 were one query that ran twice. Two changes, neither of which touches an assertion. The reference file is unchanged and still pins the same four properties. The unresolved-name error was asserted by re-running a query the previous line had already run, so both properties are now read from one execution of it. The boundary tables move from 138 and 139 columns of 600 characters to 555 and 556 of 300, which brackets the same budget with a quarter of the candidate cost and a tighter pin: one column's worth of work is now 0.18 percent of the budget rather than 0.72. The cancellation arm needs the opposite shape to those two lines, so it gets its own table. Its total work has to exceed by a wide margin what the deadline allows, but a hint computation is only interruptible between computations, so the size of one is time spent overshooting. Spreading the same total over 600 cheap names instead of 60 expensive ones keeps the margin and drops the overshoot to a tenth. None of the three properties loses coverage: with the budget raised the second line still fails, with the charging made per-candidate rather than cumulative it still fails, and with the cancellation check removed the fourth still fails.
|
Pushed
Two changes, and the reference file is byte-unchanged, so the four asserted properties are the
Projected from the failing job's own per-arm costs this is about 108 s against the 180 s limit. I checked that none of the three properties lost coverage, since making a test cheaper is the Correction to my earlier comment. I said a trailing cancellation checkpoint for the other The |
CI finish ledger - ef93dbcEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
The whole test matrix ran on this head: 38/38 Why #116441 owns it, not the already-merged #115726: the mirror-2 rebuild #115726 added is Not caused by this PR: the diff is Session id: cron:our-pr-ci-monitor:20260826-030000 |
Related: #112203
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a query occupying a thread for minutes after it was cancelled while computing the "Maybe you meant" suggestion for an unknown identifier. Computing the suggestion is now bounded, and a cancelled query stops instead of finishing a suggestion nobody will read.
Description
NamePrompter::getHintsscores an unresolved name against every candidate withlevenshteinDistanceCaseInsensitive, anO(m*n)dynamic program with no early exit, and nothing onthat path checks cancellation. The work is unbounded in three query-controlled dimensions: name
length, candidate count (
merge(REGEXP('.+'), '.+')unions the columns of up tomerge_table_max_tables_to_look_for_schema_inferencetables), and call count(
TreeRewriter.cpp:1303callsgetHintsonce per required column).Seen as
Hung check failed, possible deadlock foundinStress test (amd_tsan): one row atelapsed 453.88,is_cancelled 1,read_rows 0, its 60 smax_execution_timeignored for ~6.5minutes more.
Two bounds in
src/Common/NamePrompter.{h,cpp}, the chokepoint every hint path goes through:exhaustion no hint is returned, since the nearest candidate is only known once all are scored;
CurrentThread::checkIfNotCancelledbefore and after scoring, bounding the caller's loop.Nothing is added inside the dynamic program, and no changed file is an
IFunction, so this is not aper-row or per-function check. All 44 hint call sites (4 direct
NamePrompterusers, 15IHintssubclasses) are error paths, so neither bound costs a successful query anything.
IDatabase::getCreateTableQueryalso re-asserts cancellation before giving up, so a cancelled queryis not reported as a missing table.
Two servers, 60 unresolved names,
max_execution_time = 5: before, 146.68 s with the timeout ignored(
UNKNOWN_IDENTIFIER); after, 5.37 s,TIMEOUT_EXCEEDED. With the limit but no checkpoint it stillruns 10.46 s and still ignores the timeout, so both bounds are load-bearing. Hint quality is
unchanged: seven hint families are byte-identical, and a 31-character name against a 10,000-column
table still gets its hint.
The limit is a constant, not a setting, since exhausting it only withholds an optional suggestion.
optimize_and_compare_chain_max_hash_workis the same kind of budget exposed as a setting, so I canmake it one if preferred.
Workflow [PR]
Sync PR [sync-upstream/pr/116356]