Skip to content

Bound typo hint computation and stop it for a cancelled query - #116356

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:bound-name-prompter-work
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:bound-name-prompter-work

Conversation

@groeneai

@groeneai groeneai commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112203

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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::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: name
length, candidate count (merge(REGEXP('.+'), '.+') unions the columns of up to
merge_table_max_tables_to_look_for_schema_inference tables), and call count
(TreeRewriter.cpp:1303 calls getHints once per required column).

Seen as Hung check failed, possible deadlock found in Stress test (amd_tsan): one row at
elapsed 453.88, is_cancelled 1, read_rows 0, its 60 s max_execution_time ignored for ~6.5
minutes more.

Two bounds in src/Common/NamePrompter.{h,cpp}, the chokepoint every hint path goes through:

  • a per-call cumulative work limit, charged only for candidates reaching the dynamic program. On
    exhaustion no hint is returned, since the nearest candidate is only known once all are scored;
  • CurrentThread::checkIfNotCancelled before 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 a
per-row or per-function check. All 44 hint call sites (4 direct NamePrompter users, 15 IHints
subclasses) are error paths, so neither bound costs a successful query anything.
IDatabase::getCreateTableQuery also re-asserts cancellation before giving up, so a cancelled query
is 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 still
runs 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_work is the same kind of budget exposed as a setting, so I can
make it one if preferred.


Workflow [PR]
Sync PR [sync-upstream/pr/116356]

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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Aug 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Independent review of this change: a cold read of the resulting code, then a second-model gate, over
four rounds. Every finding is adjudicated against the code or a measurement. Verdicts below.

❌ Fixed in this PR

Finding Verdict What changed
The test asserted the capitalised suggestion with no analyzer pin, while the old-analyzer CI profile sets allow_experimental_analyzer = 0 server-side. Under set -e the failing grep -c aborted the script, so one line of output met a three-line reference: a deterministic red, not a flake. AGREE Every asserting query pins the analyzer. Verified with the real CI profile installed server-side, and with the pin stripped as a negative control.
The test pinned only the existence of a work limit, not its value: any limit between 14.4M and 432M cells produced identical output, so an eightfold regression would pass. AGREE The boundary was bisected and the arms now bracket it to a 0.7% window (138 versus 139 candidates).
No arm covered cancellation, so the test passed with the checkpoint removed. AGREE A cancellation arm asserts the TIMEOUT_EXCEEDED token, never a duration, with a one-sided margin (fires at ~1.3 s against ~10.2 s of unavoidable work) and holds at eight concurrent copies.
Cancellation arriving during scoring was reported as the unresolved-name error, because only the entry to getHints was checked. AGREE The checkpoint now also runs on both exits, following the shape at ConnectionEstablisher.cpp:202-206.
The hint fallback in IDatabase::getCreateTableQuery swallowed the cancellation and rethrew the original missing-table error. AGREE The cancellation reason is let through; the catch-all is not narrowed. Five non-cancelled paths are byte-identical to master.
The non-zero-divisor precondition for the new division was established in a different function, undocumented at the site. AGREE Stated as an invariant at the division.
A cancellation arriving after the prompter's last exit check and before the rethrow in IDatabase::getCreateTableQuery returned normally, so the catch never ran and the query was still reported as a missing table. The window is not a narrow instruction gap: it spans up to max_hint_candidates visibility checks, each of which can wait synchronously for a table to start up. AGREE One statement re-asserts cancellation before the rethrow, guarded on the existing table_is_missing flag so any other failure is reported unchanged. Measured on the same fixture: CANNOT_GET_CREATE_TABLE_QUERY without it, TIMEOUT_EXCEEDED with it, five non-cancelled paths byte-identical to master.

⚠️ Raised and answered with evidence

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 IDatabase re-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 CREATE callers. 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 is TreeRewriter.cpp:1305,
    reached only through InterpreterSelectQuery. 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 to 1. 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 test no-old-analyzer and keep it, or leave it as is.

Session id: cron:clickhouse-review-slot-10:20260825-125100

@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ef93dbc]

Summary: ❌

job_name test_name status info comment
Docker keeper image FAIL
clickhouse/clickhouse-keeper:head-distroless-arm64 FAIL cidb

AI Review

Summary

This PR adds a cumulative work cap plus cancellation checkpoints around NamePrompter hint scoring, updates IDatabase::getCreateTableQuery to preserve cancellation, and adds a stateless regression test. The Levenshtein bound itself looks reasonable, but I do not think the broader "stop it for a cancelled query" contract is fully closed yet: the shared table-hint post-processing can still continue after cancellation on non-SHOW CREATE callers.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/Bound typo hint computation and stop it for a cancelled query #116356#issuecomment-5417430437] [src/Interpreters/DatabaseCatalog.cpp:2362-2438, src/Databases/IDatabase.cpp:45-53, src/Analyzer/Resolve/IdentifierResolver.cpp:407-409, src/Interpreters/InterpreterShowCreateQuery.cpp:148-156] The new trailing checkPromptingNotCancelled only fixes the IDatabase::getCreateTableQuery wrapper. After NamePrompter::getHints returns, TableNameHints::getHintForTable and getExtendedHintForTable still run visibility checks and cross-database ranking with no further cancellation check, so the other unknown-table callers can still keep working and eventually surface UNKNOWN_TABLE after the query has already been cancelled. I still consider this real because isHintNameVisible can synchronously tryGetTable, so the residual is not just an error-code cosmetic. Suggested fix: move the post-prompter cancellation boundary into the shared TableNameHints loops so every table-hint caller stops on cancellation, not only the SHOW CREATE path.
Final Verdict

Changes needed: the main NamePrompter bound is sound, but the table-hint path still has a post-scoring cancellation hole outside IDatabase::getCreateTableQuery.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.30% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.40% +0.10%

Changed lines: Changed C/C++ lines covered: 30/32 (93.75%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Two servers, 60 unresolved 600-char names against a 30-table merge(), max_execution_time = 5: 146.68 s before vs 5.37 s after, on demand. Also a single-call clickhouse local form measuring 720,000,000 dynamic-programming cells. Not a low-rate flake.
b Root cause explained? Yes. NamePrompter::getHints scores the unresolved name against every candidate with levenshteinDistanceCaseInsensitive, an O(m*n) dynamic program with no early exit, and no cancellation point exists anywhere on the path (measured: 0 in TreeRewriter.cpp, NamePrompter.h, levenshteinDistance.cpp). Work is unbounded in three query-controlled dimensions: name length, candidate count (merge(REGEXP('.+'), '.+') unions up to merge_table_max_tables_to_look_for_schema_inference tables' columns, all handed to the prompter by getAllRegisteredNames), and call count (TreeRewriter.cpp:1303 calls getHints once per required column). So a cancelled query keeps building a string that is often never emitted.
c Fix matches root cause? Yes. A cumulative work limit bounds one call and one shared cancellation checkpoint bounds the caller's loop, both at the single chokepoint all hint paths pass through. No widened bound, no no-random-* tag, no data reduction, no guard at the symptom site.
d Test intent preserved / new tests added? Yes. No existing test weakened or removed. A new stateless test ships and fails without the fix. Its four assertions are each load-bearing: three separate mutants fail at three distinct lines (work limit halved, work limit doubled, cancellation checkpoint neutralised), so the test pins the limit's value and not merely its existence. Hint quality is asserted unchanged across seven hint families (identifier, table, setting, function, data type, table function, nested identifier), byte-identical, and the five non-cancelled missing-table paths are byte-identical too.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (SELECT lower(buildId()) matched against each binary's NT_GNU_BUILD_ID). Before: 61 hint computations, 43.92e9 cells, 146.68 s, UNKNOWN_IDENTIFIER with the 5 s timeout ignored. After: 31 computations, 1.54e9 cells, 5.37 s, TIMEOUT_EXCEEDED. Each bound was also mutated separately: reverting the work limit returns the counter to exactly the pre-fix figure, and neutralising the checkpoint restores the 60-call behaviour and the ignored timeout, so with the limit alone the query still runs 10.46 s and still ignores cancellation. The final tree was re-measured the same way: the new test passes in 4.15 s and fails in 13.02 s without the fix.
f Fix is general across code paths? Yes. The change is at NamePrompter<N>::getHints, through which all 4 direct call sites and 44 IHints callers pass, covering both analyzers, including the Analyzer/Resolve/TypoCorrection.cpp path whose per-callsite fix was reverted earlier. The shared Levenshtein helper is deliberately untouched, so its two exact-distance consumers keep exact values by construction; isLocalAddress.cpp inputs are DNS-bounded and DatabaseCatalog.cpp:2430 ranks candidates that already came through the bounded getHints. Cancellation is observed on both exits of getHints, and the hint fallback in IDatabase::getCreateTableQuery no longer discards it, so a cancelled query cannot be reported as a missing identifier or a missing table.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. getHints takes const String &, so there is no Nullable / LowCardinality / Const / Array / Map axis. Boundary inputs covered: empty name (explicit guard, returns before any allocation), names from 32 to 4000 characters, candidate sets from 5 to 54,002, exactly-at-limit and over-limit, and length pairs whose product overflows size_t (the affordability test is a division, so no product is formed until it is known to fit).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no default change, no serialization or format change, so no SettingsChangesHistory.cpp entry is required. Behaviour differs only where the limit is exhausted (a suggestion is withheld; the error itself is unchanged) or the query is already cancelled (it stops). The max_execution_time documentation already says "most of query analysis" and already names an existing analysis-time exception, so it stays accurate.
i Invariants and contracts preserved? Yes. getHints still returns the true nearest candidate or nothing, never the nearest of an arbitrary prefix, which is why exhaustion returns empty rather than breaking out: the nearest candidate is only known after every candidate is scored, and candidate order is unordered_set-dependent. Returning empty is an already-live path (TreeRewriter.cpp:1306,1315, appendHintsMessage, getHintsErrorMessageSuffix, and DatabaseCatalog.cpp:2447-2450, which already returns empty on two opt-out paths). The over-limit path allocates nothing. The checkpoint makes getHints able to throw where it previously could only return, so all 30 files with call sites were re-scanned after the edit: none is inside a noexcept function or a destructor. The catch-all in IDatabase::getCreateTableQuery keeps its log-and-preserve behaviour for every failure except cancellation, verified byte-identical to the previous behaviour on five non-cancelled paths. The precondition the affordability division relies on is recorded at its use site. No locks, shared state, or concurrency contracts are touched.

Session id: cron:clickhouse-impl-slot-4:20260825-040500

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix @yakov-olkhovskiy, could you review this? A cancelled query could sit for minutes inside NamePrompter::getHints, which scores an unresolved name against every candidate with an O(m*n) edit distance that has no early exit and no cancellation point, so a 60 s max_execution_time was ignored for another 6.5 minutes and tripped the stress hung check. This adds a cumulative per-call work budget plus one CurrentThread::checkIfNotCancelled at the single chokepoint all 44 hint call sites route through, and re-asserts cancellation in IDatabase::getCreateTableQuery so a cancelled query is not reported as a missing table.

@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ef93dbc56 with master 0f7cac9ea (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 710.18 MiB 707.14 MiB -3.04 MiB (-0.43%)

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 units

2304 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 matched translation units cost +652.4 s (+5%) in total before that adjustment.

Job report

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

Copy link
Copy Markdown
Collaborator Author

Pushed ef93dbc to make the new test fit the flaky-check time limit, and one correction to what
I wrote above.

Stateless tests (amd_tsan, flaky check) was failing 04862_name_prompter_work_limit with
"Test runs too long (> 180s)". The job's own query log has the breakdown: 140 s of the run was
four queries, 75 s of that was a single query executed twice, and every non-TSAN flavour
finished the whole test in 9 to 43 s. The passing runs sat at 161 to 180 s and the failing ones
at 180 to 185 s, so it was a cost profile a few seconds under a hard limit, not non-determinism.

Two changes, and the reference file is byte-unchanged, so the four asserted properties are the
same ones you reviewed:

  • The unresolved-name error was asserted by re-running a query the previous line had already
    run; both properties now come from one execution of it.
  • The boundary tables go from 138 and 139 columns of 600 characters to 555 and 556 of 300. That
    brackets the same budget at a quarter of the per-candidate cost, and it pins the limit's value
    tighter than before: one column's work is 0.18% of the budget rather than 0.72%.
  • The cancellation arm needs the opposite shape, so it now has its own small table: the total has
    to exceed what the deadline allows by a wide margin, but a hint computation is only
    interruptible between computations, so the size of one is time spent overshooting. Same total
    spread over 600 cheap names instead of 60 expensive ones keeps the margin and cuts the
    overshoot to a tenth.

Projected from the failing job's own per-arm costs this is about 108 s against the 180 s limit.
Locally: 50 of 50 randomized runs pass, and 8 concurrent copies move it 7.71 s to 7.94 s.

I checked that none of the three properties lost coverage, since making a test cheaper is the
easy way to make it vacuous. Against builds that each disable exactly one thing: budget raised,
the second line still fails; charging made per-candidate instead of cumulative, the second line
still fails; cancellation check removed, the fourth still fails. That middle one is a real
regression I introduced in a first attempt and then reverted: a single-candidate fixture cannot
tell cumulative charging from per-candidate charging, which is why the boundary pair is still
many candidates.

Correction to my earlier comment. I said a trailing cancellation checkpoint for the other
TableNameHints callers would be inert because isHintNameVisible wraps tryGetTable in
catch (...) { return false; }. That is only true of a checkpoint placed inside
isHintNameVisible. The suggestion was to put one in the calling loop, and getHintForTable's
body has no try at all, so a checkpoint there would propagate. My reason for not doing it was
wrong; the conclusion that it is a separate change is not. It touches a deliberate fail-closed
path that stops a dictionary-only grant from leaking table names, and it wants its own mutation
evidence through a caller other than getCreateTableQuery. The residual is still bounded, at
most max_hint_candidates = 10 visibility checks per database and only after the prompter saw
no cancellation, and it affects the reported error code rather than whether the query stops.
Happy to open that PR if it is wanted.

The --enable_analyzer=0 question on the last arm is unchanged and still yours to call.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ef93dbc

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Docker keeper image / clickhouse/clickhouse-keeper:head-distroless-arm64 apt mirror 503, retries exhausted 2/2, Canonical fallback never selected #116441 (ours, open)

The whole test matrix ran on this head: 38/38 Stateless tests legs OK, 27/27 Build legs OK,
Fast test and Fast test (arm_darwin) OK, Config Workflow and Style check OK, 154 of 176
praktika nodes OK with 0 DROPPED. CIDB has 12 non-green rows of 304,565 at this head, and after
the Bugfix validation inversion filter exactly the one row above is ownable.

Why #116441 owns it, not the already-merged #115726: the mirror-2 rebuild #115726 added is
present in the tree that ran and never engaged. Its gate anchors on ERROR: failed to solve:
while buildx prints ERROR: failed to build: failed to solve:, so terminal_build_failure
fails closed to the empty string and is_apt_mirror_failure is always false. This job log
contains the shipped anchor 0 times and the real sentence 3 times, logs apt mirror 1/2 six
times and apt mirror 2/2 zero times, and carries no exhausted its retries line. #116441
corrects that literal.

Not caused by this PR: the diff is src/Common/NamePrompter.{cpp,h}, src/Databases/IDatabase.cpp
and one stateless test, none of which participate in building a Docker image. Breadth over 30 days
is 177 Docker keeper image failure rows across 12 pull requests plus 33 on master, first seen
2026-07-31.

Session id: cron:our-pr-ci-monitor:20260826-030000

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
@clickhouse-gh clickhouse-gh Bot added comp-common-library Common library: the general-purpose code in src/Common and src/Core that belongs to no feature - ... and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 19, 2026

This branch has not been deployed

No deployments
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 comp-common-library Common library: the general-purpose code in src/Common and src/Core that belongs to no feature - ... groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant