Skip to content

Measure the client chime threshold on the client's own clock - #116033

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:measure-chime-on-client-clock
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:measure-chime-on-client-clock

Conversation

@groeneai

@groeneai groeneai commented Aug 24, 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 clickhouse-client --chime N not emitting the terminal bell when a long-running query ends in an error. The threshold is now measured on the client's own clock instead of the server-reported elapsed time, which a failing query does not deliver.

Description

--chime N is documented to alert "on success and on error", but on the error path it fired
only sometimes. The gate read ProgressIndication::elapsedSeconds(), which prefers the server-reported
elapsed_ns and only falls back to the client's stopwatch at exactly 0. The server puts
elapsed_ns on the wire in TCPHandler::sendProgress: in-loop sends are throttled by
interactive_delay, and the two unconditional final sends happen after the pulling loop, which a
throwing query skips. The exception handler sends logs and the exception, never progress. A failing
query therefore keeps whatever partial delta arrived before the throw, and that small non-zero value
overrides the wall clock. Measured on SELECT throwIf(sleep(1.5) = 0, 'expected error') via
--time: 1.503 on the success path against 0.802 on the error path at interactive_delay=800000,
below a 1-second threshold. clickhouse-local never sets elapsed_ns and was not affected.

The fix adds clientElapsedSeconds() and uses it at the chime gate only. elapsedSeconds() and its
other consumers (Elapsed:, --time, ETA and CPU-rate math) are unchanged, since they want the
server figure when available. No setting and no protocol change. The client clock is never below the
server's elapsed time, so anything that chimed before still chimes; a query within round-trip
distance of the threshold can now chime where it did not.

This also fixes the intermittent 04312_client_chime_on_slow_query_92718 case-11 failure (8
occurrences on unrelated branches since #109001 merged, all sanitizer lanes). Case 11 now pins
interactive_delay so it reaches that state on every run instead of under an unlucky cadence: it
then fails 6/6 before this change with exactly the CI diff line, and passes 50/50 after.
Sub-threshold, --chime 0 and non-TTY arms confirm the chime is not always emitted.

Not fixed here: --time and Elapsed: under-report on the error path for the same reason.

Related: #92718


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

`clickhouse-client --chime N` is documented to alert on success and on error,
but on the error path it fired only sometimes.

The gate read `ProgressIndication::elapsedSeconds()`, which prefers the
server-reported `elapsed_ns` and falls back to the client's stopwatch only when
that value is exactly 0. The server puts `elapsed_ns` on the wire in
`TCPHandler::sendProgress`: in-loop sends are throttled by `interactive_delay`,
and the two unconditional final sends sit after the pulling loop, which a
throwing query skips via `catch (...) { executor.cancel(); throw; }`. The outer
exception handler sends logs and the exception, never progress. A failing query
therefore keeps whatever partial delta arrived before the throw, and because a
non-zero server value overrides the client's correct wall clock, the threshold
comparison used that partial figure.

Measured with `SELECT throwIf(sleep(1.5) = 0, 'expected error')` (true wait
1.5s), reading the client's own belief through `--time`: the success path
reports 1.503, the error path 1.406 at the default `interactive_delay`, and
0.802 at `interactive_delay=800000`, which is below a 1 second threshold and so
emits no bell. `clickhouse-local` never sets `elapsed_ns`, so it always used the
client stopwatch and was unaffected.

Add `ProgressIndication::clientElapsedSeconds()` and use it at the chime gate
only. `elapsedSeconds()` and its other consumers (the `Elapsed:` line, `--time`,
progress-bar ETA and CPU-rate math) deliberately keep preferring the server
figure, which excludes client-side round-trip and is what those rates are
computed against.

This also removes the intermittent case-11 failure of
04312_client_chime_on_slow_query_92718, which recurred 8 times on unrelated
branches after ClickHouse#109001, all on sanitizer lanes. That PR made the elapsed time
deterministic; it did not make delivery of that time deterministic, which is why
the symptom survived it. The stale comment claiming the arm's determinism
follows from the nesting alone is corrected in cases 4 and 11, and case 9's
comment no longer quotes the gate's C++ expression.

Case 11 pins `interactive_delay` in its own client invocation. At the default
cadence the partial elapsed value that reaches the client on the error path is
close enough to the threshold that the arm only failed under an unlucky draw, so
it did not reliably exercise the contract it covers; pinned, it reaches that
state on every run. The oracle is unchanged, the reference file is unchanged, and
a control that differs only in dropping the pin passes on the same pre-fix
binary, which is what attributes the failure to the arming.

Validation: the test fails 6 of 6 runs before this change with exactly the CI
diff line and passes 50 of 50 after with default randomization, plus 20 of 20
under heavy machine load, and 04625_client_chime_config stays green.
Sub-threshold, `--chime 0` and non-TTY arms all stay silent while a positive
control emits the bell, so the chime is not simply always emitted.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds, 9 findings, all resolved)

An independent model reviewed this change across three rounds. Findings and verdicts:

# Finding Verdict
❌ Case 11 did not deterministically reach the defective state: at the default interactive_delay the partial elapsed value delivered on the error path is ~1.406s, above the 1s threshold, so the pre-fix gate also chimed and the test passed with the fix reverted. AGREE - fixed. Case 11 pins interactive_delay in its own invocation. Pre-fix 6/6 FAIL with exactly the CI diff line; unpinned control 3/3 OK on the same binary, which attributes the failure to the arming.
⚠️ The accessor's doc comment claimed the server-reported value "is not delivered when a query fails". It is delivered (1.406s at the default cadence, 0.802s at interactive_delay=800000); only the final update is missing - and non-zero delivery is exactly why the bug exists. AGREE - fixed. Reworded to say a failing query never sends its last update.
⚠️ Nothing in the test said the pin was load-bearing, and the comment above it argued the case was deterministic without it, inviting its silent deletion. AGREE - fixed. The comment now states what the pin buys the assertion.
⚠️ Wording claimed only the safe half of the behaviour change. AGREE - fixed. The description now discloses both directions: a query within round-trip distance of the threshold can chime where it did not.
💡 Case 9 quoted the gate's C++ expression; occurrence count was 7, now 8; Related: #92718 sat only in the non-rendering HTML block. AGREE - all three applied.
💡 Suggested dropping the parentheses from elapsedSeconds() in the comment. DISAGREE. Paren-keeping is this tree's convention for methods in comments (IntervalKind.h:55, ThreadPoolTaskTracker.h:42, Primality.h:116, PrimeGenerator.h:243); paren-less is used for fields.

Final round: 0 findings. src/ is byte-identical to the first reviewed revision; rounds 2 and 3 changed comment and commit-message text only (proven by stripping comments and hashing, with controls that do move the hash).

Known limitation, not fixed here: --time and Elapsed: still under-report on the error path for the same reason. Those consumers deliberately keep preferring the server figure.

@clickhouse-gh clickhouse-gh Bot closed this Aug 24, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, from the committed test itself. Case 11 pins interactive_delay 800000, so on the pre-fix binary it fails 6/6 with exactly the CI diff line 11. ... slow query then error, pty stderr: no BEL. A control that differs only in dropping the pin passes 3/3 on that same binary, so the failure is attributable to the arming and not to the build. Not a low-rate arm.
b Root cause explained? Yes. The gate read ProgressIndication::elapsedSeconds(), which prefers the server-reported elapsed_ns and only falls back to the client stopwatch at exactly 0. TCPHandler throttles in-loop progress by interactive_delay and sends the two unconditional final packets after the pulling loop, which a throwing query skips; the exception handler sends logs and the exception, never progress. So a failed query keeps a small partial delta that overrides the correct 1.5s wall clock. Measured via --time: 1.406 at the default delay, 0.802 at 800000, versus 1.503 on the success path.
c Fix matches root cause? Yes. It stops the gate consulting a value the error path cannot deliver, at the one call site that asks a client-local question. No widened bound, no no-random-* tag, no dataset reduction, no defensive guard. max() inside getElapsedNanoseconds() was rejected because it would change Elapsed:, --time, ETA and CPU-rate math for every consumer. Note the interactive_delay pin in case 11 is not a substitute for the source fix: the fix is what makes the chime correct, and the pin only makes the test reach the defective state deterministically, which is why the pinned test still fails on a pre-fix binary.
d Test intent preserved / new tests added? Preserved and strengthened. No case added, weakened or removed, and .reference is unmodified, so no assertion changed. Case 11 keeps its exit-code and 'expected error' checks and its oracle is still BEL presence; it now pins interactive_delay so it reaches the state under test on every run instead of only under an unlucky cadence. That is a documented per-query setting, not a timing assertion, not a widened bound and not a no-random-* blanket tag. Three stale comment sentences were corrected.
e Both directions demonstrated? Yes, on the shipped test file. 6/6 FAIL before the change, 50/50 OK after under default randomization, plus 20/20 OK taken deliberately at load average 450 on 384 cores. Three of the 50 runs took 83-140s against a 31s norm and still passed, so the post-fix margin survives a slow runner. system.query_log confirms interactive_delay=800000 reached the server on 90 case-11 queries while the 90 unpinned case-4 queries of the same text carry no such setting, so the pin is both delivered and correctly scoped.
f Fix is general across code paths? Yes. grep -rn "x07" src/ finds exactly one BEL emission site, the one changed. clickhouse-local shares this ClientBase path and never sets elapsed_ns (0 occurrences in LocalConnection.{cpp,h} against 3 in TCPHandler.cpp as a positive control), so it was already correct, confirmed empirically on both builds. Every other error exit (server exception, client exception, timeout, cancellation) skips the final progress send for the same structural reason and is covered by the same change.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The input space is threshold x tty x exit path x binary: --chime 1/10/0, implicit --chime, flag omitted; tty and non-tty; success and error; client and local; sub- and supra-threshold. Cases 1-12 cover that matrix and all pass, plus three explicit over-fire arms (sub-threshold, --chime 0, non-tty) which stay silent while a positive control in the same harness emits BEL. No type wrappers apply: the value is a double from a monotonic stopwatch.
h Backward compatible? (maintainer-approved exception only) Yes. No setting (so no SettingsChangesHistory.cpp entry is due, and no settings file is touched), no serialization or protocol change, no default changed. The client wall clock is never below the server's elapsed time for the same query, so anything that chimed before still chimes.
i Invariants and contracts preserved? Yes. watch is restarted per query by resetProgress(), called from processParsedSingleQuery before execution, so it measures exactly this query on both paths. The new accessor is const, allocation-free, takes no lock and touches no shared state, so it adds no concurrency obligation. elapsedSeconds() and all of its existing consumers keep their previous semantics.

Session id: cron:clickhouse-review-slot-8:20260824-010200

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0deec4c]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Bugfix validation (functional tests, amd64) ERROR
Server startup (amd_msan) ERROR cidb
Scraping system tables FAIL cidb
Bugfix validation (functional tests, aarch64) ERROR
Server startup (arm_msan) ERROR cidb
Scraping system tables FAIL cidb

AI Review

Summary

The live PR diff at HEAD no longer includes the client-clock source change described in the PR body; that logic is already on master via #117179. What remains in this branch is the case-11 --interactive_delay 800000 pin plus comment cleanup in 04312_client_chime_on_slow_query_92718.sh. I did not find a correctness, reliability, or coverage regression in that residual diff.

Final Verdict

✅ No new actionable findings in the current PR diff.

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

Copy link
Copy Markdown
Collaborator Author

cc @azat @serxa, could you review this? The --chime gate read ProgressIndication::elapsedSeconds(), which prefers the server-reported elapsed_ns; a failing query never sends its final progress packet, so the gate compared a small partial value against the threshold and the bell was skipped on the error path. It now reads the client's own stopwatch at that one call site, leaving Elapsed:, --time and the ETA math on the server figure.

Comment thread src/Client/ClientBase.cpp
if (chime_threshold_seconds > 0
&& stderr_is_a_tty
&& progress_indication.elapsedSeconds() >= static_cast<double>(chime_threshold_seconds))
&& progress_indication.clientElapsedSeconds() >= static_cast<double>(chime_threshold_seconds))

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.

Switching the chime gate to clientElapsedSeconds() here makes the client disagree with its own elapsed reporting on failing queries. Elapsed: a few lines above, and --time in non-interactive mode, still read progress_indication.elapsedSeconds(), which stays stuck on the last partial elapsed_ns packet when the server throws before the final progress update. That means clickhouse-client --chime 1 --time can now print something like 0.802 / Elapsed: 0.802 sec. and still ring the bell for crossing the 1-second threshold. Since --chime is documented in terms of the query's runtime, users now get two contradictory answers from the same invocation. I think the end-of-query user-facing elapsed value on the error path needs to use the same clock as the chime threshold, or the chime gate needs to stay aligned with the displayed elapsed.

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.

Confirmed, and the PR body already notes it: "Not fixed here: --time and Elapsed: under-report on the error path for the same reason."

Measured on both builds, error path, --chime 1 --time --interactive_delay 800000, 3 runs each:

build --time prints BEL
master, Build ID ffc68c79 0.802 absent
this PR, Build ID 1b5ae298 0.802 present

Negative control --chime 0 on this PR: BEL absent. At the default interactive_delay both builds print 1.406 and both ring, so the two only diverge in the window where the partial figure sits below the threshold.

So the divergence is real, but the query ran for 1.5 seconds and --chime is documented as firing "after running for at least N seconds". The bell is the output this PR makes correct; 0.802 is the wrong one, and it is equally wrong on master. Aligning the gate to the displayed elapsed would restore the missing bell, which is the defect this PR exists to fix.

Putting Elapsed: and --time on the client clock is worth doing, but as a separate change: getElapsedNanoseconds() also feeds the ETA and CPU-rate math and output_format->setStartTime, which want the server figure when one is available. I am not widening this PR to cover them.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dc7d0f225 with master 3c3a54e67 (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 705.71 MiB 702.68 MiB -3.03 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

23 translation units recompiled, 159 s compile time in total, 23 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #117179 (merged 2026-08-31T15:27:02Z, f9990c84db0f), which fixes this defect by the same mechanism, so this pull request is redundant.

Verified on master by content rather than by ancestry:

  • src/Common/ProgressIndication.h:81 adds double clientElapsedSeconds() const { return watch.elapsedSeconds(); }
  • src/Client/ClientBase.cpp:3142 gates the chime on progress_indication.clientElapsedSeconds() >= static_cast<double>(chime_threshold_seconds)

That is this pull request's entire source change, so it carries nothing master lacks. The test coverage on master is also stronger: #117179 adds a case that forces exactly one sub-threshold Progress packet with SETTINGS interactive_delay = 900000, which arms the error path deterministically instead of relying on the pinned cadence I used in case 11, and it identifies the failure by the error code name FUNCTION_THROW_IF_VALUE_IS_NON_ZERO rather than by the expected error text that the client echoes back with the failed query.

CIDB confirms the flake is retired: 4444 recorded runs of 04312_client_chime_on_slow_query_92718 across 18 lanes since that merge, 0 failures.

This can be closed.

@clickhouse-gh clickhouse-gh Bot added the comp-cli clickhouse-client (interactive CLI) and client library. label Sep 4, 2026
@azat azat closed this Oct 14, 2026
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-cli clickhouse-client (interactive CLI) and client library. groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants