Skip to content

Fix Keeper logical error response_bytes_in_all_queues.load() == 0 on shutdown - #112668

Merged
al13n321 merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-keeper-response-bytes-shutdown-assert
Aug 4, 2026
Merged

al13n321 merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-keeper-response-bytes-shutdown-assert

Conversation

@groeneai

@groeneai groeneai commented Jul 30, 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

KeeperDispatcher::shutdown drained the dispatcher queues and checked that they accounted for zero
bytes, and only then called server->shutdown(). But responses are produced by NuRaft's commit thread
(KeeperStateMachine::commit -> KeeperRequestDispatcher::onResponse), and only server->shutdown()
joins it, so the check sampled a quiescence property while a producer was still running.

Shutdown is now split so the check runs only once every producer is quiesced: shutdownRequests stops
intake, joins the dispatcher's own threads and submits the session Close requests;
KeeperServer::shutdown joins NuRaft (raft_server::shutdown spins until the commit thread has
terminated, so the join is a hard guarantee); drainAndCheckQueues then drains and checks both queues.
A split rather than a swap is required: the first phase needs the live raft_instance that
KeeperServer::shutdown destroys. Both assertions are unchanged; no new setting, timeout or threshold
is introduced.

chassert compiles to nothing outside debug and sanitizer builds, and the counter's remaining readers
belong to threads that are already joined at this point, so this is a test-only failure rather than
user-visible misbehavior, hence the CI category.

Found in CI 3 times across 3 unrelated PRs in 60 days, never on master. The new integration test uses a
failpoint added here to widen the window in which the dispatcher's own consumer threads are joined while
NuRaft is not, stops the leader under load, and asserts that no accounting logical error appears, that
the queue check ran after the Raft join, and that the drain performed after that join released a nonzero
number of response bytes. The ordering and byte-count assertions matter because on the arm_binary
integration job, where chassert compiles away, they are the only ones that can fail. Deleting the
post-join drain, or restoring the old ordering, each reproduces the original logical error; removing the
check itself reddens the ordering assertion instead.

CI provenance

Observed on Integration tests (amd_tsan, 3/6) and Integration tests (amd_msan, 3/8). Report for
one of them, PR #110627 at commit dcb02553e49f08659bcb9d40fdf6e57f70ce0997:

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110627&sha=dcb02553e49f08659bcb9d40fdf6e57f70ce0997&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%203%2F6%29

#112088 edits two timeout expressions inside the block
that moves here, so whichever merges second needs a trivial keep-both resolution.

Version info

  • Merged into: 26.8.1.728 (included in 26.8 and later)

groeneai and others added 4 commits July 29, 2026 23:09
KeeperDispatcher::shutdown drained the dispatcher queues and asserted that they
accounted for zero bytes, and only afterwards called server->shutdown(). But
responses are produced by NuRaft's commit thread (KeeperStateMachine::commit ->
KeeperRequestDispatcher::onResponse), and only server->shutdown() joins it. The
check therefore sampled a quiescence property while a producer was still
running: a commit landing in that window pushes a response and increments
response_bytes_in_all_queues after the drain, so the assertion fired in debug
and sanitizer builds. The request side is unaffected because putRequest already
returns early once shutdown is called, which is why the sibling
requests_queue_bytes assertion was never the one failing.

There is a second leak on the same path. After the check, shutdown appends
session Close requests to Raft and waits only for them to reach the leader.
Their responses arrive later, with response_thread already joined, so nothing
ever drained them.

Shutdown is now split into shutdownRequests() and drainAndCheckQueues(), called
around server->shutdown(), so the check runs only once every producer is
quiesced. This also drains the Close responses that used to leak. A split is
required rather than a swap: shutdownRequests needs a live raft_instance to send
the Close requests, and KeeperServer::shutdown destroys it. Both assertions are
preserved unchanged; no new setting, timeout or threshold is introduced.

The failure showed up as an integration test failing at cluster.shutdown() with
"Crash in instance", on whichever test happened to be tearing its cluster down.
The window is only a few atomic loads wide, hence no master sightings and only
sanitizer builds affected. The new integration test widens it with the
keeper_shutdown_delay_before_queue_check failpoint, keeps writes in flight while
the leader is stopped, and asserts that no accounting logical error appears. It
fails on master and passes with this change.
The regression test only asserted the absence of the accounting logical error.
That also holds when the checks never run, so it could not distinguish this fix
from a build where drainAndCheckQueues is never called or its assertions are
gone.

drainAndCheckQueues now logs a fixed marker where it performs the checks, and
the test asserts that the marker is present and that it follows nuraft's
"commit thread stopped." line, which is the ordering this fix establishes.
NuRaft already logs that line at the raft_logs_level this suite configures, so
no production change is needed for the ordering half.

Also drop a clause from the startup-error path comment. On that path initialize
rethrows, so the dispatcher is never stored in the Context and
KeeperDispatcher::shutdown is not called through it later. The behaviour was
already correct; only the stated reason was wrong.
test_session_close_shutdown pointed at a TODO in
KeeperRequestDispatcher::shutdown, which this branch splits into
shutdownRequests() / KeeperServer::shutdown() / drainAndCheckQueues().
The TODO it refers to now lives in shutdownRequests, so point there.

Comment only, no behaviour change.

Co-Authored-By: Claude Fable 5 <[email protected]>
The regression test pinned the shutdown ordering and the absence of the
accounting logical error, but not that the drain performed after nuraft's
commit thread is joined actually removes anything, so it still passed with
that drain deleted.

The window that drain exists to cover is not the few hundred microseconds
between the dispatcher's own drain and the nuraft join, but the wait inside
shutdownRequests for the session Close entries to reach the leader, which can
last up to session_shutdown_timeout. By then both dispatcher threads are
joined, so responses_queue has no consumer while nuraft's commit thread is
still publishing into it, and those bytes survive until the final drain.

Reuse keeper_shutdown_delay_before_queue_check at a second site, at the end of
shutdownRequests, so a test can open that window; return the released byte
count from drainQueues and report it on the existing marker line; assert it is
nonzero. Deleting the final drain now reproduces the original assertion
failure instead of passing silently. Both assertions stay byte-identical and
the failpoint remains inert when disabled.

Also correct a comment: on the measured path the Close responses are never
produced, because raft_server::shutdown sets stopping_ before waiting for the
commit thread, so commit_in_bg_exec returns early and the state machine never
commits those entries.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 30, 2026 •

Copy link
Copy Markdown
Collaborator Author

Reviewed internally over 4 rounds before opening. Everything merge-relevant from those rounds is in
the description, including the withdrawn claim that this also fixes a release-build response-byte leak,
which is why the category is CI Fix rather than Bug Fix.

@groeneai

groeneai commented Jul 30, 2026 •

Copy link
Copy Markdown
Collaborator Author
Validation summary (click to expand)

Repro. A bare rerun does not reproduce: the drain-to-check window is a few atomic loads, which is
why this has 0 master hits and shows only under sanitizers. Holding that window open with a probe,
response_bytes_in_all_queues goes 0 to 1891 and the logical error fires with a stack identical to the
CI reports.

Both directions. Merge-base source, with the same failpoint injected at its own drain-to-check
boundary, reddens on the accounting assertion, so the arm fails on the bug rather than on the new
assertion. Three mutations each redden, on two different assertions between them: deleting the
post-join drainQueues() (accounting assertion, with the marker reporting drained 0 just before the
fatal line), removing the phase-3 call site (dispatcher never checked its queue byte accounting), and
restoring the pre-fix ordering. A fourth, deleting the two chasserts, deliberately does not redden: a
passing chassert is unobservable by construction. With the failpoint disabled the suite's other
Close-path tests pass unchanged, so the added delay is inert in normal runs.

Generality. All 5 counter mutation sites enumerated. KeeperRequestDispatcherOld has no
occurrences of the counter and KeeperOverDispatcher's response callback never defers, so neither
holds bytes across teardown and no sibling fix is owed. Of the four executeReads call sites two are
under onCommit, so local reads publish from the commit thread too, which is why joining only the
dispatcher's own threads cannot be correct. The startup-error call site in
KeeperDispatcher::initialize is updated as well.

Session id: cron:clickhouse-review-slot-9:20260730-211400

@groeneai

groeneai commented Jul 30, 2026 •

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @kssenii, could you review this? The mechanism and the split are described in the PR description.

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7232670]

Summary: ✅


AI Review

Summary

This PR splits Keeper shutdown so the dispatcher stops intake first, KeeperServer::shutdown joins NuRaft before the final queue check, and the queue-byte assertions run only after response producers are quiesced. The current head is consistent with that contract, the new integration test proves both the post-join ordering and a nonzero post-join drain, and the PR's CI is fully green. I did not find a remaining review issue in the changed code.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 47/48 (97.92%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 47/48 (97.92%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 31, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger: 3f7020c

CI is fully finished (174 check-runs, none queued). Every failure has an owner, and none is caused by
this PR: the diff is confined to src/Common/FailPoint.cpp, src/Coordination/KeeperDispatcher.cpp,
src/Coordination/KeeperRequestDispatcher.{h,cpp} and one Keeper integration test.

Check / test Reason (breadth from CIDB) Owner
AST fuzzer (amd_debug) / STID 2508-368d logical error on SELECT arr.nested.b ... ORDER BY arr.nested; 2 hits on 2 unrelated PRs, 0 on master a fix task is created, fixing-PR link to follow here
Stress test (arm_asan_ubsan) / Hung check failed, possible deadlock found chronic trunk class: 216 hits, 150 unrelated PRs, 37 on master in 14 days. Its latest fixing PR #111909 is already an ancestor of this head, so it did not resolve this occurrence a fix task is created, fixing-PR link to follow here
Integration tests (arm_binary, distributed plan, 2/4) / test_nats_restore_failed_connection_without_losses_on_write lost messages on write after a restored connection (87650 == 100000); 14 hits on 11 unrelated PRs plus 2 on master, all after #112464 restored the suite a fix task is created, fixing-PR link to follow here

Session id: cron:our-pr-ci-monitor:20260731-040000

@al13n321

al13n321 commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

@groeneai please edit the comments down to ~1/5 the current total length.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

Done. My comments on this PR went from 17363 to 3541 characters, a bit under a fifth. What went is the
internal process narrative and most of the validation table; what is left is the repro, the
both-directions mutation evidence, the generality check and the CI finish ledger. Happy to cut further
if it is still more than you want to read.

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer (amd_debug) line of the ledger above (STID 2508-368d): #112769, merged 2026-08-01.

That failure was not caused by this PR. The fuzzer had mutated the in-tree test 03742_test_flattened_crash into SELECT arr.nested.b FROM test_flatten_nested_crash ORDER BY arr.nested ASC, which read a Nested element subcolumn beside its parent column after the column had been dropped and re-added. fillMissingColumns matched the post-convertToSubcolumns name_in_storage against lists keyed by full column name, so it took the shared-offsets branch and put a ColumnTuple in a slot still declaring the element type.

Verified on two real binaries: the pre-fix debug build (inplaceBlockConversions.cpp at the fix parent) aborts on that exact query, and current master 26.8.1.621 runs it cleanly and reproduces 03742_test_flattened_crash byte-for-byte against its reference. This PR head 3f7020cf4114 predates the fix, which is why the check was red. No further sightings of the identifier since the merge.

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (arm_asan_ubsan) line above: #112976.

Two corrections to that row. The stack fragment I quoted from test_context_raw pointed at
joinGet overload resolution, but that frame is a truncation artifact: CIDB keeps only the last
32 KiB of hung_check.log, which preserved the report's "Top short messages" table (where the
joinGet stack is merely attached to a log message) and dropped the processlist dump 700 lines
earlier. The joinGet query threw Code: 43 and finished normally.

The query that actually hung is
SELECT sum(length(geohashesInBox(...))) from 04648_geohashes_in_box_cancellation.sh, 714.25 s
elapsed with is_cancelled already set, stack at GeoHash.cpp:333. It was spinning, not
deadlocked: 666 ms of user time and 1983 query-profiler runs, which a blocked thread does not
accumulate. A zero-area box collapses one axis' item count to zero while the other stays at
2^29, so geohashesInBox walked 536 million iterations per row to produce one geohash, below
the caller's cancellation throttle the whole time. #112976 skips the loops in that case.

@al13n321
al13n321 enabled auto-merge August 4, 2026 00:32
@al13n321
al13n321 added this pull request to the merge queue Aug 4, 2026
Merged via the queue into ClickHouse:master with commit 2da8c2e Aug 4, 2026
181 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 4, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Backport ask: @alexey-milovidov, could you apply v26.6-must-backport here, if you agree it is worth it?

This fix is absent from 26.6 and 26.7, and the assertion it removes fired again on 26.7 last night: Keeper aborted at cluster.shutdown() in Integration tests (amd_tsan, 3/6) at 8b239572, failing test_keeper_opentelemetry_tracing[xid32] (report). The carrier test is incidental; four different tests have been blamed for this abort across its five recorded occurrences.

Per branch: master and 26.8 have the fix (26.8 was cut 20 days after this merged, so it inherited it); 26.7 and 26.6 carry the chassert without the fix; 26.3 is not affected, since response_bytes_in_all_queues does not exist there at all (0 hits across all 65 source files under src/Coordination). So the floor is 26.6 and the 26.8 arm of the label is a no-op.

To be accurate about what this buys: chassert is compiled out unless DEBUG_OR_SANITIZER_BUILD, and all 5 occurrences of this signature in CIDB over 90 days are tsan/msan builds, so a release binary does not abort. The gain is release-branch CI signal, and the rate is low: 5 occurrences in 90 days across all refs, one of them on 26.7.

The port looks cheap. A three-way apply of this diff is clean on both branches, the result orders shutdownRequests() -> server->shutdown() -> drainAndCheckQueues() as intended rather than half no-opping, and the new test's dependencies are all present there (keeper_utils.get_leader, grep_in_log(only_latest=), and NuRaft's commit thread stopped. at the 26.6/26.7 pin).

If a shutdown-ordering change in two stable branches is not worth a CI-only benefit, that is a fine answer and I will drop it.

pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Sep 12, 2026
Pull in the fix for the Keeper logical error `response_bytes_in_all_queues.load() == 0`
on shutdown (ClickHouse#112668), which was the only red check on the previous head.
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 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.

4 participants