Repository navigation
Resolve the query status per call in functions that check for cancellation - #113456
Conversation
…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.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 4 findings across 3 rounds; the
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-10:20260805-095700 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-10:20260805-095700 |
|
cc @nihalzp @nikitamikhaylov, could you review this? Six functions resolved their |
|
Workflow [PR], commit [ed5bd9c] Summary: ❌
AI ReviewSummaryThis PR moves Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 73/77 (94.81%) · Uncovered code |
| 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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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]); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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.
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.
CI finish ledger — ed5bd9cEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
CI is otherwise finished on this head: 175 check-runs, 0 incomplete, Neither failure is caused by this PR, whose diff resolves the query status per call in the functions A note on the hung check, so the frames in the report are not misread: that artifact is truncated to Session id: cron:our-pr-ci-monitor:20260806-020000 |
| @@ -0,0 +1,38 @@ | |||
| TIMEOUT_EXCEEDED | |||
There was a problem hiding this comment.
@groeneai remove the test, maybe is going to be flaky
There was a problem hiding this comment.
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:
- Drop just the two
arrayFoldarms, keep the other 13. Costs thearrayFoldcarrier's coverage; thecheckTimeLimitmechanism stays pinned bygeohashesInBox,base58Decodeandsleepacross all three persisted routes (PARTITION BY, sorting key, skip index). - 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 carriesno-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.
Owner for the
|
| 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".
421fd14
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
max_execution_timeandKILL QUERYbeing ignored while a query evaluatesgeohashesInBox,arrayFold,sleep,base58Decode,h3PolygonToCellsorh3PolygonToCellsWithContainmentinside an expression stored in table metadata, such as a sorting key, a skip index or aPARTITION BYkey.Description
Six functions in
src/Functions/readgetProcessListElement()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. AnINSERTthen ignores its ownmax_execution_timeandKILL QUERY.Two routes reach it and fail differently.
MergeTreeData::getSortingKeyAndSkipIndicesExpressionbuilds the sorting-key and skip-index expressions fromMergeTreeData's own context, the global one, so the member is empty and the check is dead.KeyDescription::getKeyFromASTbuilds thePARTITION BYexpression once at DDL time and the metadata keeps it, so every later write re-executes that instance holding theCREATE TABLEquery'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 consultisKilled()only, the other fourcheckTimeLimit(). Both observe a deadline, because in the defaultthrowmodeCancellationCheckercancels withCancelReason::TIMEOUT, which setsis_killed. Undertimeout_overflow_mode = 'break'nothing sets it, so the h3 pair still runs to completion there, as it does today.Measured on one debug binary,
INSERTwithmax_execution_time = 1, one block,max_threads = 1:Elapsed against the 1000 ms limit, before and after
geohashesInBoxinPARTITION BYgeohashesInBoxin a sorting keygeohashesInBoxin a skip indexbase58DecodeinPARTITION BY/ sorting keyarrayFoldinPARTITION BY/ sorting keysleep(3)call inPARTITION BY/ sorting keyh3PolygonToCellsin a sorting keyh3PolygonToCellsWithContainmentin a sorting keyreplaceRegexpAllinPARTITION BY, already resolved per callarrayFoldlands at 2879 ms because that is what one of its slices costs; its own direct call measures2801 ms. A single
sleepcannot overshoot pastfunction_sleep_max_microseconds_per_block(3 s bydefault) however long the deadline is exceeded, which is why the regression test uses three calls with
distinct arguments instead. The two h3 rows are
throwmode, whereis_killedcarries the deadline; inbreakmode both stay attheir 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.base58EncodeandtryBase58Decodeshare the changedFunctionBaseXXConversiontemplate, so one site serves all three. The linearbase32/base64aliases are unaffected: theirperformignores 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