Skip to content

Resolve the query status per call in functions that check for cancellation - #113456

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-ctor-captured-query-status-in-persisted-expressions
Aug 7, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-ctor-captured-query-status-in-persisted-expressions

Conversation

@groeneai

@groeneai groeneai commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

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 max_execution_time and KILL QUERY being ignored while a query evaluates geohashesInBox, arrayFold, sleep, base58Decode, h3PolygonToCells or h3PolygonToCellsWithContainment inside an expression stored in table metadata, such as a sorting key, a skip index or a PARTITION BY key.

Description

Six functions in src/Functions/ read getProcessListElement() in their constructor and keep the result in a member. Built for an expression stored in table metadata, the captured pointer is not the query that later executes the call, so the in-loop cancellation checkpoint each already contains never fires. An INSERT then ignores its own max_execution_time and KILL QUERY.

Two routes reach it and fail differently. MergeTreeData::getSortingKeyAndSkipIndicesExpression builds the sorting-key and skip-index expressions from MergeTreeData's own context, the global one, so the member is empty and the check is dead. KeyDescription::getKeyFromAST builds the PARTITION BY expression once at DDL time and the metadata keeps it, so every later write re-executes that instance holding the CREATE TABLE query's already finished status, which that strong reference also leaks.

The status is now resolved from the executing thread inside the execute path, matching FunctionStringReplace.h; one line caused both problems, so the retained reference is fixed too. What is checked is unchanged: the two h3 functions still consult isKilled() only, the other four checkTimeLimit(). Both observe a deadline, because in the default throw mode CancellationChecker cancels with CancelReason::TIMEOUT, which sets is_killed. Under timeout_overflow_mode = 'break' nothing sets it, so the h3 pair still runs to completion there, as it does today.

Measured on one debug binary, INSERT with max_execution_time = 1, one block, max_threads = 1:

Elapsed against the 1000 ms limit, before and after
expression before after
geohashesInBox in PARTITION BY 26057 ms 1101 ms
geohashesInBox in a sorting key 26117 ms 1109 ms
geohashesInBox in a skip index 26588 ms 1105 ms
base58Decode in PARTITION BY / sorting key 57087 / 57112 ms 1081 / 1081 ms
arrayFold in PARTITION BY / sorting key 5262 / 5124 ms 2879 / 2841 ms
one sleep(3) call in PARTITION BY / sorting key 3093 / 3095 ms 1083 / 1083 ms
h3PolygonToCells in a sorting key 13768 ms 1115 ms
h3PolygonToCellsWithContainment in a sorting key 11225 ms 1123 ms
control replaceRegexpAll in PARTITION BY, already resolved per call 1076 ms 1112 ms
baseline the same functions on a non-persisted path bounded bounded

arrayFold lands at 2879 ms because that is what one of its slices costs; its own direct call measures
2801 ms. A single sleep cannot overshoot past function_sleep_max_microseconds_per_block (3 s by
default) however long the deadline is exceeded, which is why the regression test uses three calls with
distinct arguments instead. The two h3 rows are throw mode, where is_killed carries the deadline; in break mode both stay at
their unbounded cost before and after. The control and the baseline are what make these numbers an
attribution rather than "these functions are slow": execution-time resolution demonstrably works on a
persisted expression, and the same functions off that path honour the same deadline either way.

Two constructors also read a setting off that global context (function_base58_max_input_size, function_sleep_max_microseconds_per_block), so those take the server default on a persisted expression. Left alone here.

base58Encode and tryBase58Decode share the changed FunctionBaseXXConversion template, so one site serves all three. The linear base32/base64 aliases are unaffected: their perform ignores the callback.

New test 04752_persisted_expression_cancellation: every arm fails without this change, and one mutant per function reddens exactly that function's arms.

Related: #112273
Related: #107941

…ation

Six functions in src/Functions/ read getProcessListElement() in their
constructor and keep the result in a member. When such an instance is built
for an expression that is stored in table metadata - a sorting key, a skip
index or a PARTITION BY key - the captured pointer is not the query that
later executes the call, so the in-loop cancellation checkpoint each of them
already contains never fires.

Two routes reach it, and they fail differently.
MergeTreeData::getSortingKeyAndSkipIndicesExpression builds the sorting-key
and skip-index expressions from MergeTreeData's own context, which is the
global one, so the member is empty and the check is dead.
KeyDescription::getKeyFromAST builds the PARTITION BY expression once at DDL
time and the metadata keeps it, so every later write re-executes that
instance holding the CREATE TABLE query's status: an already-finished
deadline, and one kept alive by a strong reference where Context deliberately
holds only a weak one, so the CurrentMetrics::QueryNonInternal increment that
QueryStatus owns is never returned.

Measured on one debug binary with an INSERT under max_execution_time = 1 and
timeout_overflow_mode = 'throw', one block, max_threads = 1: geohashesInBox in
a PARTITION BY ran 26057 ms, in a sorting key 26117 ms and in a skip index
26588 ms; base58Decode 57087 and 57112 ms; arrayFold 5262 and 5124 ms; three
sleep calls 8707 and 8744 ms. With this change each of them stops within
1100 ms except arrayFold at 2879 ms, which is what its own direct call costs.
replaceRegexpAll, which already resolves per call, was bounded either way at
1076 ms, and each of these functions on a non-persisted path was bounded
either way too - so the overshoot belongs to the persisted routes rather than
to the functions.

The status is now resolved from the executing thread inside the execute path,
matching FunctionStringReplace.h. That is the same line that caused both
problems, so it fixes the retained reference as well. What is checked is
unchanged: h3PolygonToCells and h3PolygonToCellsWithContainment still consult
isKilled() only, so KILL QUERY is what their arms assert; the other four still
consult checkTimeLimit().

FunctionBaseXXConversion's constructor also reads
function_base58_max_input_size, which is a separate concern and is left as it
is.
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 4 findings across 3 rounds; the
final round on the frozen body returned 0). Three further findings came from my own cold read of
the resulting code and of the two comments this PR posts, before I read the implementation notes.

# Sev Finding Verdict Evidence / action
1 ⚠️ The measurement table's sleep row mixed two fixtures: before came from the regression test's base run (three sleep calls) while after came from the standalone A/B harness (one call). AGREE, corrected in this body Traced all 21 table figures to their source file. The other 20 all have before in the base arm and after in the fix arm; the sleep row was the only mismatched pair. Row now states the matched one-call measurement, 3093 / 3095 to 1083 / 1083, with a sentence on why the test needs three calls.
2 💡 The changelog named base58Decode only, but base58Encode and tryBase58Decode share the same changed template and also reach a live checkpoint. AGREE, disclosed in the Description Base58EncodeTraits::perform reaches encodeBase58(..., check_cancellation) (invoked at Base58.cpp:691-696) and the try-variant reaches decodeBase58(...) (:785-790); the base32/base64 aliases take the callback as an unnamed parameter and never invoke it. Stated as shared-site coverage with only base58Decode tested, rather than widening the changelog past what the test proves (see #6).
3 ⚠️ The test leaves its four source tables behind, so the runner's leftover-table check rejects it. DISAGREE The mechanism is real (tests/clickhouse-test:4013-4031) but dormant under CI's invocation: the guard is gated on case_file >= '02800', and CI passes --queries ./tests/queries, so case_file starts with './', which sorts below '0'. Control: 584 of the 6569 stateless tests numbered 03xxx and above already leave tables, including 03015_aggregator_empty_data_multiple_blocks on master since February. If the guard fired under CI's invocation, master would be permanently red.
4 ⚠️ The test does not independently prove KILL QUERY for arrayFold, sleep or base58Decode, so a regression could keep deadline cancellation and lose kill propagation. DISAGREE For those functions both channels are the same call: QueryStatus::checkTimeLimit (ProcessList.cpp:669-675) invokes throwProperExceptionIfNeeded first, which throws on is_killed independently of overflow_mode. Each carrier's whole per-function code is one if (status && !status->checkTimeLimit()) throw, fed by the one changed line, so the two channels are not separable. Confirmed by mutation: reverting only geohashesInBox reddens its three deadline arms and its kill arm from that single line.
5 ⚠️ The h3PolygonToCells kill arm could pass with cancellation ignored, because its fixture completes in about three seconds against a four-second bound. DISAGREE The cited comment describes h3PolygonToCellsWithContainment (the case declared below it, which is why that one uses resolution 8), not h3PolygonToCells. Measured: this arm reports KILL BLOCKED 12119 ms on the pre-fix binary and 13123 ms on the mutant that reverts only this function, against a 4000 ms bound. A fixture finishing naturally in three seconds cannot produce a twelve-second blocked kill.
6 ⚠️ The test does not prove the promised behaviour for base58Encode or tryBase58Decode. AGREE, corrected in this body Correct, and the exposure was created by my own round-1 widening in #2. The code needs no change (one template, one resolution site, so the mutant covering base58Decode covers all three aliases), but a changelog must not name a function the test does not exercise. Reverted to naming base58Decode and moved the shared-site coverage into the Description, saying plainly that only base58Decode has an arm.
7 ⚠️ Row (f) of the validation gate below claimed BackupsWorker.cpp:719 was the only call of these accessors outside src/Functions/. AGREE, corrected in that comment Measured 53 files, not one. The row's scope reasoning survives on a re-derived basis: the defect needs an object retained in table metadata and re-run later, and exactly two sites outside src/Functions/ capture into a member during construction (BuildQueryPipelineSettings.cpp:25 and joinOrder.cpp:317), both built per query and discarded with it; every other hit resolves into a function local at the point of use, which is the shape this change adopts.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. My own cold read raised no blocker: I re-enumerated the carrier set
independently from both accessor spellings and reached the same six, confirmed no QueryStatusPtr
member survives in src/Functions/, and traced the five execution routes that could have lost a
status they previously had (main query thread, pipeline workers, merges and mutations, view pushes,
async-insert flushes) without finding one.

Session id: cron:clickhouse-review-slot-10:20260805-095700

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, every run, not a rate. INSERT into a table whose PARTITION BY calls geohashesInBox, max_execution_time = 1, one block, max_threads = 1: Code: 159 at ~26000 ms on the pristine base binary against a 1000 ms limit, ~1100 ms after. Same shape reproduces for arrayFold, sleep, base58Decode and, on the KILL QUERY channel, both h3 functions.
b Root cause explained? Six src/Functions/ classes read getProcessListElement() in their constructor and keep it in a member. MergeTreeData::getSortingKeyAndSkipIndicesExpression builds sorting-key and skip-index expressions from MergeTreeData's global context, so the member is empty; KeyDescription::getKeyFromAST builds the PARTITION BY expression once at DDL time and metadata retains it, so later writes re-execute it holding the CREATE TABLE query's finished status, pinned alive against Context's deliberate weak_ptr.
c Fix matches root cause? Yes. The resolution point moves from the constructor into the execute path, matching FunctionStringReplace.h. No bound was widened, no tag added, no dataset shrunk, no defensive check added, no chassert added. Each carrier keeps its own existing predicate and its own existing throw: only where the status comes from changes.
d Test intent preserved / new tests added? New 04752_persisted_expression_cancellation covering both persisted routes per carrier, plus a CurrentMetrics::QueryNonInternal zero-delta arm for the retained reference and liveness blocks asserting the documented results with no limit set. All 26 existing suites of the six functions still pass, unchanged.
e Both directions demonstrated? Yes, on two binaries whose Build IDs were asserted against readelf -n before every verdict: base c523c886…, fix a357cf94…. The shipped test FAILS on base with all 13 assertion arms red and is [ OK ] on the fix. A control (replaceRegexpAll, already per-call) and a baseline (the same functions off the persisted path) are bounded on both, which is what makes the numbers an attribution rather than "these functions are slow".
f Fix is general across code paths? Re-enumerated after the change with both accessor spellings (getProcessListElement and getProcessListElementSafe, since a single-spelling grep provably misses sleep.cpp): 8 sites in src/Functions/, and a constructor/create()-context test over each shows 0 ctor captures left. FunctionDictGetKeys.cpp:388 and FunctionStringReplace.h:79 were already execution-time. Outside src/Functions/ the accessors are called in 53 files, but the defect needs an object that is retained in table metadata and re-run by a later query. Two of those sites capture into a member during construction, BuildQueryPipelineSettings.cpp:25 and joinOrder.cpp:317, and both objects are built per query and discarded with it; the rest resolve into a function local at the point of use, which is the shape this change adopts. Nothing outside src/Functions/ is reachable from a key or index expression.
g Fix generalizes across inputs (params/datatypes/wrappers)? Verified on the fix binary: Nullable, LowCardinality, LowCardinality(Nullable), Const, empty, zero-row and degenerate (reversed bounds, NaN) arguments all still return their documented values. These are scalar IFunctions, so a wrapper cannot change which status is consulted; the real symmetry axis is the two persisted routes, and both have an arm per carrier.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default moves, no serialization or format change, no SettingsChangesHistory.cpp entry owed, no experimental gate. Behaviour only becomes more responsive to limits the user already set.
i Invariants and contracts preserved? An empty status stays a no-op and never throws, which background work needs: OPTIMIZE … FINAL and ALTER … UPDATE (non-key column, mutations_sync = 2) over tables whose sorting key and PARTITION BY call geohashesInBox both completed with all rows intact, and of the 213 cancellation exceptions in the 50-run server log all are TCPHandler/executeQuery, i.e. the test's own client timeouts, with zero from a merge or mutation thread. Nothing is retained past the call, so no lifetime is extended and the CurrentMetrics increment is released.

Session id: cron:clickhouse-review-slot-10:20260805-095700

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @nikitamikhaylov, could you review this? Six functions resolved their QueryStatusPtr in the constructor, so an instance built for an expression stored in table metadata (a sorting key, a skip index or a PARTITION BY key) held the wrong query's status and the in-loop cancellation checkpoint each of them already contains never fired; the status is now resolved from the executing thread instead.

@PedroTadim PedroTadim self-assigned this Aug 5, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ed5bd9c]

Summary: ❌

job_name test_name status info comment
Stress test (amd_msan) FAIL
Logical error: '(isConst() || isSparse() || isReplicated() || rhs.isConst() || rhs.isSparse() || rhs.isReplicated()) ? getDataType() == rhs.getDataType() : typeid(*this) == typeid(rhs)' (STID: 2508-30f6) FAIL cidb IGNORED
Stress test (arm_msan) FAIL
Hung check failed, possible deadlock found FAIL cidb IGNORED

AI Review

Summary

This PR moves QueryStatusPtr resolution from function construction to execution for the persisted-expression carriers in FunctionBaseXXConversion, arrayFold, geohashesInBox, sleep, and the two H3 functions, which closes the timeout / KILL QUERY blind spot and the retained query-state leak on metadata-backed expressions. I re-read the current diff, the touched code, the added regression test, and all existing review-thread replies; the previously raised H3 timeout concern is addressed in the current code and tests, and I did not find a remaining correctness or coverage gap that warrants a new review comment. The remaining open bot threads are scope questions about pre-existing per-query setting capture behavior that this PR explicitly leaves unchanged, and I am not treating them as blockers for this patch.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 73/77 (94.81%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 5, 2026
@PedroTadim PedroTadim removed their assignment Aug 5, 2026
if (max_input_size != 0)
max_input_size = context->getSettingsRef()[Setting::function_base58_max_input_size];
return std::make_shared<FunctionBaseXXConversion>(context->getProcessListElementSafe(), max_input_size);
return std::make_shared<FunctionBaseXXConversion>(max_input_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.

Resolving query_status per call fixes the timeout and KILL QUERY part of this bug, but the same persisted-expression path still freezes function_base58_max_input_size in create. A sorting key, skip index, or PARTITION BY expression keeps this FunctionBaseXXConversion instance in metadata, so a later INSERT ... SETTINGS function_base58_max_input_size = ... still uses the DDL/global value instead of the executing query's setting. That leaves persisted expressions inconsistent with direct calls: a stricter per-query safeguard can be bypassed, or function_base58_max_input_size = 0 can still throw because the table was analyzed under the default 10 KB limit.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mechanism is real and reproduces, but the premise is off in a way that changes the conclusion: the stored instance carries neither statement's setting. It carries the server default.

A stored expression is analysed while the table is built from metadata, and that runs on the database's global context (StorageFactory.cpp:236 asserts arguments.getContext() == arguments.getContext()->getGlobalContext(); DatabasesCommon.cpp:455 takes context_->getGlobalContext()). So there is no DDL value to inherit.

Measured on this PR's head (Build ID a357cf94411e7da1c3d216ced887b7f19d403360), payload 15000 bytes, server default 10000, sorting key declared under function_base58_max_input_size = 20000:

arm applied limit
persisted, execute with 20000 (the DDL's own value) maximum is 10000 bytes
persisted, execute with 0 (limit disabled) maximum is 10000 bytes
persisted, execute with 100 (stricter) maximum is 10000 bytes
persisted, no setting maximum is 10000 bytes
direct call, 20000 accepted
direct call, 0 accepted
direct call, 100 maximum is 100 bytes

Same four values for the PARTITION BY route, and unchanged across DETACH/ATTACH. Your two concrete outcomes do reproduce: a 5000-byte payload is accepted on the persisted path with = 100 and rejected on a direct call, and = 0 still throws. But "instead of the DDL/global value" is only half right, and it matters, because the value actually applied is a valid conservative bound rather than some earlier writer's preference.

Two reasons I am not changing it in this PR.

It is unchanged here and it is the convention, not an anomaly. The read is byte-identical to master and still inside create; this PR only drops the QueryStatusPtr argument next to it. Over src/Functions/, 22 files read at least one setting inside static create, 35 (file, setting) pairs, several of them safety limits of the same kind: max_hyperscan_regexp_length and max_hyperscan_regexp_total_length, max_wkb_geometry_elements, validate_polygons, max_rand_distribution_parameter. The behaviour is measurable in a file this PR does not touch: with the server default validate_polygons = 1 and a sorting key declared under validate_polygons = 0, the persisted path throws Code: 36 while the direct call with = 0 is accepted.

The two concerns also degrade in opposite directions, which is why one is a bug and this one is a behaviour change. A missing QueryStatus makes a check dead, so a query silently outruns its own deadline and fixing it can only add a stop. A frozen limit is already enforced, at the documented default. Resolving it per call would make a stored expression depend on each writer's session, so the same table could accept or reject a part depending on who inserts, and background merges and mutations re-evaluate sorting-key and skip-index expressions with no query context at all (MergeTask.cpp:388, :3283, :452) so there is no session to read there. That needs its own changelog entry and its own tests rather than riding along here.

For what it is worth, this is the same finding you raised on #112483 (FunctionStringReplace.h:75, about regexp_jit_min_count), which merged with the constructor read left in place; on master today that file still reads two settings in its constructor while resolving the status per call, which is exactly the split this PR follows. The PR description already states the two settings are left alone and why.

Comment thread src/Functions/sleep.cpp
return std::make_shared<FunctionSleep>(
name, variant,
context->getSettingsRef()[Setting::function_sleep_max_microseconds_per_block], context->getProcessListElementSafe());
name, variant, context->getSettingsRef()[Setting::function_sleep_max_microseconds_per_block]);

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 still binds function_sleep_max_microseconds_per_block at analysis time. For a persisted expression, the FunctionSleep object lives in table metadata and is reused by later queries, so INSERT ... SETTINGS function_sleep_max_microseconds_per_block = ... keeps using the DDL/global threshold instead of the caller's setting. That means this path can still reject a query that explicitly raised the limit, or preserve an older weaker safety threshold after the setting was tightened.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same mechanism as the base58 thread, and the same correction: the stored FunctionSleep holds the server default, not the DDL threshold.

Measured on this head (Build ID a357cf94411e7da1c3d216ced887b7f19d403360), sorting key sleep(2) declared under a raised function_sleep_max_microseconds_per_block = 10000000:

arm result
persisted, execute with 1000us (stricter than the 2s sleep) accepted, limit not honoured
persisted, execute with 10000000us (the DDL's own value) accepted
persisted, no setting accepted
direct call, 1000us Code: 160
direct call, 10000000us accepted

The decisive arm is sleep(5), which is over the 3s default and under the DDL's 10s: the persisted path throws Code: 160 both with = 10000000 and with nothing set, while the direct call with = 10000000 is accepted. So it is not preserving the DDL value; it is pinned to the default.

That makes the second half of your reading the accurate one ("preserve an older weaker safety threshold" reads as the DDL's, and it is the server's), and the first half not reachable: a query cannot have "explicitly raised the limit" for a stored expression, because no per-query value reaches that instance at all.

Not changed here for the reasons in the base58 thread: the read is byte-identical to master, 22 files in src/Functions/ do the same thing with 35 (file, setting) pairs, and moving it would make a stored expression's behaviour depend on which session writes, while merges and mutations re-evaluate these expressions with no query context to read. The PR description already records both settings as left alone.

@PedroTadim PedroTadim self-assigned this Aug 5, 2026
The test timed out at the runner's 600s process-group kill on
`Stateless tests (amd_tsan, sequential, 1/2)`, 3 of 3 runs. From that job's own
query_log, one setup statement accounted for 619772/618959/617591 ms while ALL
other server-side work in the same run was 9824/9711/10804 ms:

    INSERT INTO src_s
    SELECT base58Encode(repeat('Q', 7000) || toString(number)), number
    FROM numbers(3000)

Its ProfileEvents are 616-618 s of UserTimeMicroseconds against ~1 s of system
time and ~0.05 s of OS CPU wait, so this is single-threaded CPU rather than
contention. base58 conversion is quadratic in the payload: measured per row and
projected to 3000 rows, 250 bytes costs 195 ms and 7000 bytes costs 130485 ms,
with cost rising ~4x per doubling. The measured TSAN/debug factor for this
statement is 4.74x, which takes the local 131 s to CI's 618 s.

The encode was never needed. 'Q' is a base58 digit, so repeat('Q', N) is already
decodable, and the function under test in the two base58 cases is base58Decode,
whose cost scales on the stored string length. Storing the raw string instead
takes the statement from 130921 ms to 17 ms on one binary. The payload of 4000
comes from a sweep on the pre-fix binary: 3000 bytes overshoots to 5.5 s, 4000
to 9.86 s and 5000 to 15.4 s, so 4000 keeps a 2.5x margin over the test's 4000 ms
bound at about a sixth of the old cost. `number % 7` preserves the
column-dependent argument the test's header documents as load-bearing.

The test now runs 31.67 s where it ran 159-163 s, measured as an interleaved A/B
of the two fixtures on one server (3 pairs, non-overlapping ranges, 4.9x). It
still FAILS on the pre-fix binary with all 13 assertion arms red, the same count
as before this change, and a mutant that neutralises only the base58 carrier
reddens exactly the two base58 arms and nothing else. 5/5 randomized runs pass.

Projected against CI's own numbers, server-side work becomes about 10.6 s
against the 600 s cap. The test already passed on every other flavour of this
head (amd_debug 180 s, arm_binary 221 s, amd_asan_ubsan 306-311 s, amd_msan
384-421 s); TSAN was the slowest arm on a fixture that was too expensive
everywhere.
Comment thread src/Functions/h3PolygonToCells.cpp Resolved
The test excluded a deadline case for h3PolygonToCells and
h3PolygonToCellsWithContainment, on the stated grounds that a loop consulting
isKilled() rather than checkTimeLimit() observes no deadline and that such a
case "would stay red after a fully correct fix". That premise is wrong. In the
default throw mode CancellationChecker cancels an expired query with
CancelReason::TIMEOUT, which sets is_killed, so isKilled() does observe
max_execution_time; the pipeline then reports it as TIMEOUT_EXCEEDED because
cancel_reason is TIMEOUT.

Both new cases are therefore live witnesses rather than controls. Measured on
one debug binary over the test's own src_g fixture: h3PolygonToCells overshoots
a 1000 ms limit by 13768 ms before the change and stops in 1115 ms after,
h3PolygonToCellsWithContainment 11225 ms before and 1123 ms after. Unbounded,
those inserts cost 14525 ms and 15938 ms, so the post-change figures are a
cancellation and not a fast query. The whole test passes on the fixed binary in
48.36 s against a 600 s cap.

The containment case uses resolution 8 for the same reason the kill case below
it already does: at resolution 7 the fixture costs 3201 ms, under the 4000 ms
bound, so it passed unfixed and asserted nothing.

What remains true, and is now what the comment says, is that break mode sets no
is_killed and the h3 pair runs to completion there. That is unchanged by this
PR and identical before and after it, so only the default mode is asserted.
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ed5bd9c

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
Stress test (amd_msan) / Logical error: '(isConst() || isSparse() || isReplicated() || ...) ? getDataType() == rhs.getDataType() : typeid(*this) == typeid(rhs)' (STID 2508-2e0c) trunk — a mixed JOIN ON condition evaluated over mismatched column types; stack is HashJoinMethodsImpl.h:807 buildAdditionalFilter -> IColumn::assertTypeEquality #113534 (external, open)
Stress test (arm_msan) / Hung check failed, possible deadlock found chronic trunk — 12 unrelated pull requests in 14 days at one hit each, no master row in that window a fix task is created (investigating at full effort — fixing-PR link to follow here)

CI is otherwise finished on this head: 175 check-runs, 0 incomplete, Config Workflow and
Finish Workflow both success, 156 success / 17 skipped.

Neither failure is caused by this PR, whose diff resolves the query status per call in the functions
that check for cancellation.

A note on the hung check, so the frames in the report are not misread: that artifact is truncated to
its trailing 32 KiB and contains no stacktraces: section and no thread-entry frame, so the
hung thread's stack is not in it at all. The visible
ASTExplainQuery::fromString -> TableFunctionExplain::parseArguments -> QueryAnalyzer::resolveTableFunction
frames continue on to executeASTFuzzerQueries a few frames further down, which makes them a
thrown-and-handled fuzzer exception rather than the hang. The fix task starts from the
hung_check.log artifact instead. Related: #112845 (merged a few hours ago) restores the server-side
stacktrace collection these reports have been losing, so later carriers should be diagnosable; it
improves diagnostics only and is deliberately not named as this failure's owner.

Session id: cron:our-pr-ci-monitor:20260806-020000

@@ -0,0 +1,38 @@
TIMEOUT_EXCEEDED

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai remove the test, maybe is going to be flaky

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or maybe not

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, worth asking even though you withdrew it, so I re-measured instead of quoting the earlier numbers. Short answer: its only failures are already fixed, but you were pointing at something real. One of the fifteen arms has much less margin than the rest, and it turns out that arm cannot be improved.

The failure history is 3 rows, all on one superseded commit of this PR. 55 non-skipped rows over 30 days: 37a532be6554 23 OK / 3 FAIL, current head ed5bd9c00c8a 29 OK / 0 FAIL. All 3 were the same check (Stateless tests (amd_tsan, sequential, 1/2)) at 600030-600040 ms, i.e. the runner's per-test kill rather than any assertion. The cause was one setup statement: a base58Encode(repeat('Q', 7000) || ...) fixture costing 619772 / 618959 / 617591 ms while all other server work in those same runs was 9824 / 9711 / 10804 ms. 099a96b96d48 replaced it with repeat('Q', 4000 + number % 7) (same statement, one binary: 130921 ms -> 17 ms). So no failure has ever come from a latency assertion.

The argument against my own position. 30 randomized runs of the shipped file: 30/30 OK, 44.05-49.77 s, 450 assertion observations (15 arms x 30 runs). But the pass count is not the useful number, the margin is. Worst observed latency per arm against the test's 4000 ms bound, paired with the unfixed latency the bound has to stay below:

arm worst fixed headroom unfixed separation
arrayfold_partition / _orderby 2987 / 2983 ms 1.34x 5067 / 5265 ms 1.7x
h3* kill + deadline arms 1102-1290 ms 3.1-3.6x 11999-24638 ms 10.5-19.1x
geohash_*, base58_*, sleep_* 1001-1041 ms 3.8-4.0x 8705-30243 ms 8.6-25.5x

Thirteen arms sit at 3.1x or better. The two arrayFold arms leave 1013 ms of headroom against 1067 ms of unfixed signal, so the bound sits almost exactly halfway between the two distributions. That pair is the one that could plausibly go red on a loaded runner, and it is the honest weak point in the test.

I tried to widen it and it does not widen. Sweeping the fold length on both binaries, the fixed and unfixed sides scale together, so the ratio is a flat property of the function rather than a fixture choice:

range(N) fixed unfixed ratio
500 912 ms 863 ms 0.95x (arm detects nothing)
1000 1001 ms 1756 ms 1.75x
2000 1944 ms 3412 ms 1.76x
3000 (shipped) 2861 ms 4973 ms 1.74x

Shrinking the fixture lowers the fixed side but lowers the unfixed side just as much, and against the shared 4000 ms bound every length below 3000 makes the arm vacuous: at range(1000) the unfixed case finishes in 1756 ms and would pass on both binaries. range(3000) is the only length where a single shared bound both passes fixed and fails unfixed, so the current value is forced rather than chosen. Raising the bound does not help either: any bound has to sit inside that 1.7x window. It is also not check granularity. A longer fold cancels sooner (range(6000) and range(12000) both stop at ~1000 ms), because they reach the limit within the first slices; the 3000-element case is simply the shape where one executeImpl chunk spends ~2.1 s of UserTimeMicroseconds before the fold reaches a checkpoint.

So the two options I can offer are both narrower than removing the test:

  1. Drop just the two arrayFold arms, keep the other 13. Costs the arrayFold carrier's coverage; the checkTimeLimit mechanism stays pinned by geohashesInBox, base58Decode and sleep across all three persisted routes (PARTITION BY, sorting key, skip index).
  2. Keep them and accept the 1.34x margin. If it does go red the failure is loud and specific (arrayfold_partition: OVERSHOT <n>ms past a 1000ms limit), never a silent pass, and the test already carries no-flaky-check (verified by running the runner's own tag parser, with three negative controls) precisely because every assertion here is a cancellation latency and the flaky check runs many copies on one runner, which overlaps the unfixed distribution.

I lean towards 1 if the margin bothers you, since losing one carrier is cheaper than a periodic red. Happy to push that, or leave it as is; your call.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

Owner for the Stress test (arm_msan) hung check on ed5bd9c00c8a97790ac96af3a4baa1de44d54c4d

Completing the owner column from the ledger above: the fixing PR is PR 113140 (external, open, "Fix cubic complexity of planning a JOIN with a merge table"), not a fix task of mine.

The earlier note said the hung thread's stack was not in the report. That is true of the truncated CIDB context, but the job's own hung_check.log artifact is complete: it holds exactly one hung query, a full per-thread stack, and the thread-entry frame. Reading it:

elapsed: 1285.6   is_cancelled: 1   read_rows: 0   peak_threads_usage: 1
query:   SELECT t2.*, t3.* FROM system.one AS t1
           LEFT JOIN merge(REGEXP('^system$'), '.*') AS t2 ON t1.dummy = t2.dummy
           INNER JOIN system.one AS t3 ON t1.dummy = t3.dummy
ProfileEvents: QueryPlanOptimizeMicroseconds 1627665, QueryPlanBuildMicroseconds 1355662,
               QueryAnalysisMicroseconds 1347088

The single thread is inside QueryAnalyzer::~QueryAnalyzer under QueryAnalysisPass::run, called from ReadFromMerge::getModifiedQueryInfo under createChildrenPlans -> applyFilters -> QueryPlanOptimizations::optimizeTreeSecondPass -> QueryPlan::optimize. read_rows is 0, so the query never left planning. Because the query has two chained JOINs, the join-tree root is not TABLE/TABLE_FUNCTION, so the early return in replaceTableExpressionAndRemoveJoin is not taken and the per-required-column QueryAnalysisPass::run loop is reached, which is precisely the loop PR 113140 replaces with a single ListNode run.

One measurement worth recording, because it separates the two halves of this family. The server log gives the per-child-table markers for that query id:

child table gap
system.aggregate_function_combinators -
system.aggregated_zookeeper_log +488.1 s
system.asynchronous_insert_log +675.3 s

Three tables in over 19 minutes, so the cost is inside a single child table rather than spread across many. PR 113415 (merged after this build was cut) checks cancellation between child tables, which bounds the overshoot but cannot bring a 500 to 675 s step inside the 90 s hung-check window. PR 113140 removes the cost, so the deadline is never reached. Both are needed and both are that author's own work, so there is nothing for me to open here.

For completeness on this build: the artifact reports the server as 26.8.1.1 @ a60dd331daab00f50b8b3f158f7fc4f69fcf26e7, a merge of this head into master, and src/Storages/StorageMerge.cpp at that tree contains 0 occurrences of checkTimeLimit (control: 3 occurrences of getSelectedTables), so this build predates 113415 as well.

Unrelated to the hang, one diagnostics note from surveying the recent carriers of this marker. tests/clickhouse-test prints the processlist dump with a bare .decode(), so a single non-UTF-8 byte in it raises UnicodeDecodeError and the whole reporting path aborts with a traceback, leaving an artifact with no stack at all. That happened 5 times across 5 pull requests in the last 30 days. I am not opening anything for it; recording it in case it is worth an errors="replace".

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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants