Skip to content

Assert the in-function stop in 04650_replace_cancellation - #113034

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-04650-replace-cancellation-oracle
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-04650-replace-cancellation-oracle

Conversation

@groeneai

@groeneai groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

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

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

Description

04650_replace_cancellation (mine, from #112483) has gone red since it merged on five unrelated
authors' PRs and once on master, in three shapes: fold regexp: OVERSHOT 4096 ms on amd_tsan, and on
arm_binary one match, long instruction list: no timeout and stored expression: no timeout.

The oracle is at fault, not the bounds. Two messages report the same enforced deadline and only one
carries a number: checkTimeLimit passes watch.elapsed(), never zero, so it always prints
elapsed N ms, while addPipelineExecutor and throwIfKilled pass a literal zero. The test extracts
that number, and when it was missing for a folded case it fell back to bounding the client's WALL CLOCK,
which a build whose in-function checkpoint never ran also satisfies. With the three Functions/
headers reverted, folded cases pass while asserting nothing (three to six of eight, varying with load).

A folded case must now report the numbered channel. No number means the checkpoint did not participate,
which is that case's own sizing to fix, and it is named that way. Cases whose work cannot be grown set
an earlier deadline instead, keeping the same allowance, so every bound at the shared deadline is
unchanged. Two are also split into smaller folds.

The third shape is a fixture bug: the stored-expression case inserted 40 identical 1MB rows, the best
case for the per-block haystack dedup proposed in #111005, so under that change its row count bought no
work and the query completed. Its rows are now distinct at the same width and total bytes, which no such
cache can collapse. On the unfixed build all 19 cases fail.

No src/ change, .reference byte-identical, no case weakened, no no-random-* tag added. Validated
on debug and thread-sanitizer builds in both fix states, plus release binaries as a fast arm.

Failing CI runs and per-case sizing

One report per shape, all Stateless tests (sequential):
amd_tsan,
arm_binary
case 15,
arm_binary
case 21,
and
master.
Two further arm_binary runs repeat the case-15 shape.

bound = deadline_ms + ALLOWANCE, ALLOWANCE = BOUND - 1000. A case discriminates when the fixed
arm's elapsed is under half its bound and the fast arm's work is at least 5x its deadline. Numbers
below are thread-sanitizer.

case dl change elapsed bound work/dl prologue
fold regexp 0.4 split 200x1MB 417 3400 9.9x 12%
many folds 0.4 deadline 459 3400 7.2x 15%
expanding replacement 1.0 none 1001 4000 8.7x 1%
replaceAll 0.4 deadline 402 3400 5.3x 49%
one-byte in place 0.4 deadline 403 3400 5.6x 45%
instruction list 1.0 none 1000 4000 8.7x 0%
empty matches 0.2 split + deadline 252 3200 6.1x 4%
one match, long instr list 0.2 deadline 203 3200 16.8x 2%
stored expression 0.2 distinct rows + deadline 241 3200 33x 2%

Splitting works because the prologue tracks one fold's constant, not the total.

groeneai and others added 3 commits August 2, 2026 03:36
A case that reports no elapsed time can be in one of three states, and the single
"no timeout" verdict named only the third: the query finished inside its deadline,
it failed for some unrelated reason, or the in-function checkpoint really is
missing. Only the last is a cancellation defect, and the first two need the case
re-sized rather than the function fixed.

That cost a misdirected investigation round. The 04650 case "one match, long
instruction list" reported "no timeout" on two arm_binary runs, and its own
query_log rows show QueryFinish at 993 ms and 997 ms with exception_code 0 against
a 1000 ms deadline - the query succeeded, so there was no timeout to report and
the verdict was accurate but unhelpfully worded.

Key on the client's exit status, which distinguishes the three directly: 0 for a
completion, 159 for TIMEOUT_EXCEEDED, and anything else for an unrelated failure
whose code is now printed. All three verdicts remain reference mismatches, so
nothing is weakened and the same runs would still have gone red; the failing line
now names the cause. On an unfixed binary the "expanding replacement" case
consequently reports a memory limit by code instead of an absent timeout.

The reference file is unchanged: these strings are only ever printed on failure.
A folded case that times out without the in-function checkpoint reports no elapsed
number, and the oracle fell back to bounding the client's wall clock against twice
the bound. That is not the invariant this test exists to assert, and it made cases
pass on a build with no checkpoint at all: with the pre-fix headers, six of the
eight folded cases matched the reference exactly.

Two messages report the same enforced deadline and only one carries a number.
checkTimeLimit passes watch.elapsed(), which is never zero, so a stop this function
made always carries the elapsed part; addPipelineExecutor and throwIfKilled pass a
literal zero, so a stop nothing inside the function participated in never does. For
a folded call the second form means the deadline was crossed either entirely before
entry or entirely after the last fold, and both are that case's own sizing to fix -
so it is now a named failure rather than a wall-clock pass. On a fixed build the
checkpoint runs at entry, after materialization and inside every loop, so there is
no path by which a correctly sized case reaches it.

Requiring the stronger signal also removes the squeeze that made the sizing
unsatisfiable, because a case no longer has to outrun a wall-clock threshold. Each
folded case is then sized by one rule: the step this fix cannot interrupt stays a
small part of its deadline on the slowest build, and its total work outlasts the
deadline by a wide margin on the fastest one. Cases 1 and 11 split one large fold
into many small ones, which shrinks the uninterruptible step without changing total
bytes - measured, the reported prologue tracks one fold's constant and not the
array's total, so at 200 folds of 1MB it falls from 806ms to about 50ms on a
thread-sanitizer build while the work is unchanged. Cases whose work cannot be grown
set an earlier deadline instead, which moves the deadline into the work: case 15's
cost is its own output and that output is already within ten percent of the test
memory profile, so no larger fixture exists.

A per-case deadline is fractional, and Seconds truncates to whole milliseconds, so
what the server actually enforced is read back from its own message rather than
assumed. At the shared deadline every bound is unchanged, so no existing case is
widened.
Case 21 inserted 40 identical 1MB rows. A block of repeated haystacks can be
answered by matching once and copying the result per repeat, so the row count
bought no work: measured against PR ClickHouse#111005, which adds exactly that cache,
growing 40 to 640 identical rows costs 1.4x while 40 to 640 distinct rows costs
over 11x. The case's total work fell from 6.5 s to 1.7-2.3 s on a debug build,
which on the faster arm_binary release build lands inside the 1 s deadline, so
the INSERT completed and the test reported "no timeout" - the third failure
shape seen since this test merged, on ClickHouse#111005 at 3478592.

The rows are now distinct at the same width and the same total bytes, and the
case takes its own 0.2 s deadline through run's existing sixth parameter. The
earlier deadline is needed independently: at the shared deadline the bound is
deadline + ALLOWANCE = BOUND, so a stop can never be reported before half of
it, and the fixed-arm criterion is unsatisfiable by construction.

Total work is now 33x the deadline on the fast arm and 196x under the carrier's
own code, against a reported elapsed of 0.15-0.51x the bound on debug, tsan and
the fast arm. On a build with the three Functions/ headers reverted the case
reports OVERSHOT 38690 ms, and all 19 run cases now fail there - none report
"stopped within bound".

Two comment blocks that restated measurements are condensed.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

groeneai commented Aug 2, 2026 •

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

Independent cold review plus a second-model gate, adjudicated against the recorded evidence. Rounds
survived: 6 approach reviews, 7 code reviews, 1 replan, 1 fix round.

Final gate: 0 findings (scope confirmed: full diff 63/33, fix-round delta 8/7). All findings below
are from my own cold pass.

Finding Verdict
❌ The failure census in the description was stale, and "0 on master" was false. Two rows landed after the implementation's census froze, both running the shipped test blob (f73380b153698184, confirmed per failing commit via the contents API): one on master (c2c9039413b2, Stateless tests (arm_binary, sequential), 2026-08-02 17:45Z) and one on another author's PR (17:01Z), both the one match, long instruction list: no timeout shape. True counts: five other authors' PRs plus one master run, three shapes. AGREE, corrected before publishing. No scope added: both new rows are the case-15 shape this change already fixes with a 0.2 s deadline.
⚠️ The case-21 mechanism was attributed to current behavior. The per-block haystack dedup that collapses 40 identical rows to one evaluation is not in master (grep for prev_hs_data/CachedResult/HashMap over ReplaceRegexpImpl.h and ReplaceStringImpl.h returns nothing); it is proposed in #111005, which is open. AGREE, now attributed as proposed. The fixture defect stands either way: an oracle whose discrimination collapses under a plausible optimization is a fixture bug regardless of whether that optimization merges.
⚠️ Two mechanical defects in the description. A paragraph line began with - , which renders as a list item and breaks the sentence; and the sizing table's 0.5x bound column held the bound itself (3400/3200), not half of it, so a reader comparing elapsed 417 against it would mis-read the margin by 2x. AGREE, both fixed: the column is now labelled bound.
💡 35 added comment lines vs 28 added code lines. DISAGREE. git diff <base> HEAD -- src/ is empty, and the comment-length budget is scoped to source diffs. The one long block explains why a missing number is a failure, which is the premise of the change. Noted, not blocking.

Independently re-verified rather than accepted: the two-channel argument re-derived from source at
HEAD (ProcessList.cpp:623-636 populates the elapsed clause only when elapsed_ns != 0;
addPipelineExecutor passes a literal 0; ExecutionSpeedLimits.cpp:131-140 always passes nonzero);
maximum: {} ms occurs in exactly two format strings repo-wide, both timeouts, so the
deadline-enforcement guard cannot false-match; fractional-second truncation is real
(Seconds → float64AsSecondsToTimespan → totalMilliseconds), so reading the server's echo is the
right call; the only other src/Functions/ checkTimeLimit callers are unreachable from these
fixtures; ALLOWANCE = BOUND - DEADLINE_MS makes every bound at the shared deadline arithmetically
unchanged, checked by hand for all nine sized cases; case 21's rows are exactly 1000000 bytes each, so
width and total bytes are unchanged and only distinctness moves, with the one-block and one-partition
properties preserved. And the arming result, read from the log directly: on the unfixed build all 19
cases fail; none reports stopped within bound
.

Disclosed, not absorbed: cases 19, 20 and 22 fail intermittently on the local 56-slot build box at
load average 84-107. A paired control on the unmodified test file shows the same signature at the same
rate, and a 40-day CI window contains zero failures naming those cases, so they are a local-load
artifact. Cases 19 and 20 bound wall time deliberately, because under break the query succeeds and
latency is the only observable.

Session id: cron:clickhouse-review-slot-10:20260802-215100

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? YES. Base test file against a binary with the three Functions/ headers reverted (git show 1d4408f794c3899:, grep -c ReplaceCancellationBudget = 0/0/0, Build ID asserted): folded cases match .reference exactly, i.e. falsely pass, on every run. WHICH of the eight varies with machine load (measured 3 and 6 on two runs, one case landing 4% past the threshold) because a wall clock is what decides them; that the fallback admits false passes is the deterministic part. For case 21 the repro is exact: with the haystack-dedup change proposed in #111005 present (that dedup is not in master), the shipped 40-identical-row fixture drops to 1.7-2.3 s of work against its 1 s deadline and completes
b Root cause explained? YES. ProcessList.cpp:623-638 formats one message for two producers: checkTimeLimit (:669-672) passes watch.elapsed(), never zero, so elapsed N ms is always present; addPipelineExecutor (:646) and throwIfKilled (:689) pass a literal 0, so it is absent. The extractor is grep -oP 'elapsed \K[0-9]+(?=\.)', and on no match a folded case fell back to bounding the client's wall clock, which is satisfied by a build whose in-function checkpoint never ran
c Fix matches root cause? YES. The folded oracle now requires the numbered channel, which is the observable that proves the checkpoint executed. No bound is widened: with ALLOWANCE = BOUND - DEADLINE_MS, every case's bound at the shared deadline is arithmetically identical to today's BOUND
d Test intent preserved / new tests added? YES, strictly stronger. Zero cases weakened, .reference byte-identical, no no-random-* or no-parallel tag added. On the unfixed arm the new file arms all 19 run cases - not one reports stopped within bound, including case 21 at OVERSHOT 38690 ms, which the base fixture let pass
e Both directions demonstrated? YES. Fails without the fix (false passes, above; and on the base fixture case 21 failed 1/42 locally as OVERSHOT 2433 ms); passes with it (debug [ OK ] 35.28 s, tsan [ OK ] 64.44 s); and the new oracle arms every previously vacuous case on the unfixed binary. Three arms, all logged
f Fix is general across code paths? YES. All 8 folded carriers enumerated (grep -nB1 'fold$') and re-measured on both builds in both fix states. The 11 pipeline cases keep their branch deliberately (for them a pre-executor throw is legitimate, not a sizing fault) and none changed verdict; the break-mode throw at FunctionStringReplace.h:83-89, cases 19 and 20, and the JIT/literal sibling charge sites are checked and stated as untouched
g Fix generalizes across inputs? PARTIAL, disclosed. Two builds (debug, thread-sanitizer), both fix states, two official release binaries as a fast arm, four deadlines per case. NOT arm64, where five of the six post-merge failures ran (four other authors' PRs plus one master run): no arm build is available to me, so the fast arm is amd64 and this is stated as a substitution in the PR body rather than papered over
h Backward compatible? YES / N/A. Test-only change: no setting, no serialization format, no SettingsChangesHistory.cpp surface, no src/ diff at all
i Invariants and contracts preserved? YES. The invariant: for a replace* query under a deadline the server's reported latency to the in-function checkpoint is bounded by that case's allowance, and without the checkpoint no such report exists. The new verdict strings are unique to this test (grep -rl) and printed only on failure, so no other test can be perturbed. Measured for the two cases that actually fired in the 50x run: stored expression is byte-identical to base and keeps the identical numeric bound, and replaceAll's stop lateness is deadline-independent (0-3 ms at both 0.4 s and 1.0 s), so its pass/fail predicate reduces to the same L < ALLOWANCE on both files

Session id: cron:clickhouse-impl-slot-45:20260802-141400

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze, could you review this? It is test-only: the folded cases in 04650_replace_cancellation fell back to bounding the client's wall clock whenever the server's timeout message carried no elapsed number, which a build with no in-function cancellation check also satisfies, so those cases could pass while asserting nothing. They now require the numbered channel, and two fixtures are re-sized rather than the bounds widened.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [759a98b]

Summary: ✅


AI Review

Summary

This PR hardens 04650_replace_cancellation.sh so folded timeout cases only pass when the stop came from the in-function checkpoint, and it re-sizes the affected fixtures instead of widening their bounds. I reviewed the current diff, the current code, the prior PR discussion, and the current CI state, and I did not find a correctness, flakiness, or metadata issue that warrants a new inline review comment.

Final Verdict

✅ No findings.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 2, 2026
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 759a98b

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
Build (arm_release) / Post Hooks telemetry hook: LogCluster query failed with code 500 on the build_time_trace INSERT (build_profile_hook.py); the build itself succeeded (check_status = success), so it does not gate this PR a fix task is created (investigating at full effort — fixing-PR link to follow on this PR)
Sync — CH Inc sync (private, not actionable)

All 175 check-runs are complete: 58 success, 117 skipped, 0 failures. Finish Workflow and
Mergeable Check both pass. No test check is red on this head.

The Post Hooks row is not caused by this diff: this PR touches only
tests/queries/0_stateless/04650_replace_cancellation.sh, while the row is the build-profile
telemetry upload path. Breadth over 7 days is 1407 rows across 203 distinct pull requests and
589 distinct commits, flat at 1-17 per hour with no spike.

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

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 please trim the comments in the test

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.

Done in 9d2bf8e. The file had 169 comment lines against 197 of code, with 17 blocks over three lines; it is now 92 against 200, one block over three (the tag rationale). Comments only, no executable line changed, so the reference is untouched and the test still passes locally.

I cut everything a reader can get from the commits: the measurements that decided each fixture size, the history of what earlier versions got wrong, and the restatements of the PR description. I kept only what is not re-derivable at that spot, mostly the "violate this and the case is vacuous" constraints: the needle must vary in case 8, the haystack must be materialized in case 25, the rows must be distinct in case 21.

Noted as a standing preference, not a per-PR nit.

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 maybe the test is still going to be flaky, just dont care if the query finishes on time or not. on sanitized builds, cancellation is going to be triggered anyway

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.

You are right that cancellation fires anyway on a sanitized build, and that is exactly why "it got cancelled" cannot be the oracle: it fires on the unfixed build too, from CancellationChecker or the executor's between-block check. So the assertion has to be that the stop came from inside the function. Whether the wall clock is also worth asserting then splits by case shape, and the two halves of the suite answer differently.

For the 8 folded cases your proposal is already what the file does. No pipeline exists while a fold runs, so no executor check and no cancelTask path, and the only reachable producer of an elapsed N ms number is the in-function check (checkTimeLimit passes watch.elapsed(); addPipelineExecutor and throwIfKilled pass a literal zero). Requiring the number is the cancellation-happened assertion. And that number is the server's own elapsed at the instant it stopped, not the client's wall clock, so it does not drift with load: on tsan at a 1000 ms deadline the eight report 1000-1044 ms against a bound of 4000. The flaky part for folds was never the comparison, it was whether the case reaches the checkpoint at all, which is what this PR re-sizes.

For the 11 pipeline cases the bound is the whole oracle, and dropping it would make every one of them pass unconditionally on a build with no in-function checkpoint. With the three Functions/ headers reverted, all 11 still report a number, from the executor: 2575, 2952, 3124, 9781, 11002, 11080, 13226, 13572, 38690, 39355, 59413 ms. The number is worthless there precisely because the executor also produces it, so only its size distinguishes the builds. That is the vacuous oracle this PR removes, and I would rather not put it back.

On "maybe still flaky": yes, on master today, and the two newest hits are the shape this PR fixes. Both are one match, long instruction list: no timeout (case 15, which takes a 0.2 s deadline here) and both landed after I froze the census in the description: 113039 and 112928. Over 10 days every failing verdict is one of the three shapes addressed here; none is a bound that is simply too tight.

If it still goes red after this, I would rather drop the offending case than relax its assertion, and I will do that promptly. Happy to go that way now if you prefer it.

@PedroTadim

Copy link
Copy Markdown
Member

Better fix here #113031

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

One caveat on the commit I referenced above: 9d2bf8e is pushed and is the head of this PR's branch (groeneai/fix-04650-replace-cancellation-oracle, GitHub's own compare API reports it 1 ahead of 759a98b), but the PR record has been showing the old head for about 90 minutes and no CI has been scheduled for it. GitHub is reporting partially degraded service, so I assume it is that and not the push. If the PR still has not picked it up in a few hours I will re-push.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Correction to my previous comment: the reason this PR's head did not move is that you had closed it at 09:18:25Z, half an hour before I pushed. My guess at GitHub degradation was wrong, and I should have re-read the PR state before speculating. Sorry for the noise.

Understood on #113031 for case 15, and thanks for pushing it through. It fixes the shape that was actually red in CI, and it does it with a smaller diff than mine: the two newest carriers I found this morning (113039 at 50efca4, 112928 at a1d5ec4, both one match, long instruction list: no timeout) are exactly what your per-case deadline addresses, so that half is settled.

One thing that closing this PR leaves behind, which I mention only so it is written down rather than to reopen anything. The folded branch in run still falls back to bounding the client's wall clock when the server's message carries no elapsed number:

elif [ "$shape" = fold ]; then
    if [ "$wall_ms" -lt "$((bound * 2))" ]; then
        echo "$label: stopped within bound"

Only checkTimeLimit ever supplies that number, since addPipelineExecutor and throwIfKilled pass a literal zero, so for a fold its absence means nothing inside the function participated in the stop. Bounding the wall clock in that case passes on a build where the in-function checkpoint never ran: with the three Functions/ headers reverted, three to six of the eight folded cases matched the reference exactly, varying with machine load.

That is a hole in what the test asserts rather than a red run, so it can sit until it matters. If you would like it closed I am happy to send just that branch as a few lines, separately from the sizing work you have already taken. Otherwise I will leave it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants