Repository navigation
Conversation
…shuts down ContextSharedPart::shutdown waits for the four MergeTree background executors so that no background task touches a storage while DatabaseCatalog::shutdown destroys it. MergeTreeBackgroundExecutor::threadFunction checks its shutdown flag only before popping a task, so a task that is already running is never interrupted, and the underlying ThreadPool::wait is unbounded. MergeTreeIndexAggregatorVectorSimilarity is the one skip-index aggregator that can hold that wait for minutes: updateImpl enqueues one usearch add per row onto a global pool and drains it at the end of the merge block. Both cancellation checks on that path, in MergeTreeIndexVectorSimilarity.cpp and in MergeTreeDataPartWriterOnDisk.cpp, resolve a process-list element first, and their comments name KILL QUERY and "a KILLed INSERT": they were written for the query path. A merge has no process-list element, so on a merge both are dead and the server can sit past the 60 s grace window of clickhouse stop before being SIGKILLed. Give the row loop a signal that is armed at the stall. shutdown_called is an atomic set by shutdown()'s first statement, roughly fifty lines before the wait, so Context::isShutdownCalled exposes it and add_vector_to_index throws ABORTED when it is set. The accessor deliberately takes no lock: shutdown() holds shared->mutex while doing its work, so a locking accessor would contend with the very shutdown it reports. The global-context handle is hoisted out of the per-row lambda beside the two calls updateImpl already makes, leaving one relaxed atomic load per row. Because the flag is global, projection sub-merges, mutations and replicated merges are covered without per-caller plumbing, and the foreground path is unchanged. A REGULAR failpoint makes one add slow enough for a test to observe cancellation mid-build without a very large fixture; it expands to nothing when USE_LIBFIU is off. The new integration test pins the horizontal merge algorithm and a single-thread build pool, because a vertical merge builds the index in a stage the fixture does not gate and the build pool otherwise divides the injected delay across its threads: with either unpinned the assertion holds even without this fix. Its second case is a positive control that an uncancelled merge still completes and the merged index still returns the same neighbours as a brute-force scan. This addresses the MergeTreeBackgroundExecutor::wait class of the "Possible deadlock on shutdown" CI signature, which is 14 of the 23 occurrences censused over thirty days. The other classes are different subsystems, so the signature will keep appearing. Co-Authored-By: Claude Fable 5 <[email protected]>
… build The shutdown interruption point added by the previous commit was reached by writes that ContextSharedPart::shutdown performs itself, after it has already set the flag the check reads. Two such paths reach the vector similarity index aggregator. The async insert queue is re-scheduled and waited on at Context.cpp:968-969 under the default-true async_insert_queue_flush_on_shutdown. StorageBuffer tables are flushed later, from DatabaseCatalog::shutdown, and that flush is their last chance to persist: flushBuffer puts the block back in the in-memory buffer and rethrows on the premise that a later write will retry, flushAndPrepareForShutdown swallows the exception, and StorageBuffer declares no shutdown() override, so an abort there dropped the rows with no error anywhere. Measured on the previous commit: a Buffer holding 1000 rows destined for an indexed MergeTree persisted 0 of them across a graceful restart. Gate the throw on Context::isBackgroundContext, which is true for merges and mutations (all four carriers build their task context from getBackgroundContext) and false for both flush paths. Measured at the seam: background merge true, foreground INSERT false, Buffer shutdown flush false, async insert flush-on-shutdown false. The value is resolved once on the calling thread; the build pool workers inherit that thread's group, so the per-row cost is unchanged. The regression test asserts a buffered insert still lands in its indexed destination across a restart; it fails on the previous commit and on a mutant that drops the new conjunct, while the shutdown witness stays green on both, which is what shows the conjunct is specific rather than merely sufficient. The shutdown witness also re-asserts its preconditions immediately before stopping the server (the failpoint is enabled, the merge is still running, both source parts are still active). Without that it passed for the wrong reason whenever the injection was ineffective - for instance in a build without libfiu, where the failpoint is never registered - because the shutdown is then fast. The positive control now proves the merged index was actually used, comparing ProfileEvents['USearchSearchCount'] per query: above zero for the indexed query and zero for the brute-force control. Row equality alone held even when the index was never consulted, since a vector index only prunes granules.
A wrapped call in assert_slow_index_build_is_still_in_flight fits on one line, so black joins it. No behaviour change: the arm that exercises this assertion still fails on it, and the whole file still passes on the fixed binary.
stop_clickhouse silently rewrites any graceful bound below 180s to 180s on LLVM coverage builds, so the timing arm's two legs enforced different budgets: the helper allowed 180s while the elapsed assertion still demanded 30s. Pass a single resolved bound to both, using exactly 180 on sanitizer and coverage builds, where the helper's own `stop_wait_sec < 180` guard is false and no override can apply. Scale the fixture's row count with the bound so the merge still outlives it. Also drop a justification in Context::isShutdownCalled that does not describe the window it names. The stall this interruption point addresses is outside every critical section of shutdown, so the lock-free load is not about avoiding contention there; it is simply a flag set once at the start of shutdown. The bound pair is measured to be insufficient on its own: at 180s an unfixed server finishes the fixture's merge and passes the witness, and raising the row count does not close it because a container-wide SIGTERM can take the test container down mid-poll, which hands the helper an early success. Recorded for re-adjudication rather than papered over by loosening the assertion.
stop_clickhouse returns True as soon as the process id disappears, by any means, so a wall-clock bound over that boolean cannot distinguish a shutdown that ran to completion from one whose container died mid-poll. Assert instead that the server logged "Background threads finished", which Server.cpp emits after Context::shutdown returns and therefore strictly after the merges executor wait that stalls, so a wedged server can never write it. Read it from the host, where the bind-mounted copy survives a dead container, and with only_latest so the scan stays off the rotated files that rotateOnOpen fills with earlier arms' shutdowns. Keep a second, separate assertion that the interruption point was reached. The two are not redundant and each is the discriminating one on a different build flavour: at the 30 s bound an unfixed server is still wedged when the bound expires and the completion line is missing, while at the 180 s bound it finishes the merge on its own and only the missing interruption tells the two apart. Keep the elapsed assertion as a budget rather than the oracle. Drop SLOW_BUILD_ROWS. Its only purpose was to outlive a wall-clock bound, the preconditions already prove the build is in flight when the server is stopped, and 6000 rows is the configuration under which the test container was observed exiting mid-poll for reasons unrelated to the server.
Internal second-model review — 4 rounds, clean on the last (1 blocker, 4 majors, 4 nits raised and resolved)Before publishing, this change went through four review rounds: an independent cold code ❌ Blocker (round 1) — the first version of the predicate lost data silentlyThe original check was
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260806-142804 |
|
Workflow [PR], commit [14d623e] Summary: ❌
AI ReviewSummaryThis PR adds a shutdown-specific interruption point to Findings
Tests
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 28/29 (96.55%) · Uncovered code |
Build profile diff (arm_release)Comparing Binary sizes
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. Object file sizes568 object files changed (+321.11 KiB total), 1 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units
|
CI finish ledger - f4a6ac4CI is fully finished on this head and there are no failures to own.
One clarification so the CIDB rows are not misread: Session id: cron:our-pr-ci-monitor:20260807-130000 |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…hutdown Resolves the conflict in src/Common/FailPoint.cpp. Master renamed the neighbouring entry ONCE(create_empty_part_inject_stale_dir) to REGULAR(claim_inject_stale_part_dir); this branch had added REGULAR(vector_similarity_index_slow_add) immediately above it. Both sides are kept: the rename from master, plus this branch's new failpoint.
| /// A background merge or mutation has no process list element, so the check above cannot reach it. | ||
| /// Background only: shutdown flushes the async insert queue and Buffer tables after setting the | ||
| /// flag, and those writes must still be allowed to finish. | ||
| if (is_background_operation && global_context->isShutdownCalled()) |
There was a problem hiding this comment.
Context::isShutdownCalled() is too narrow here: it fixes only full server shutdown. Table-local teardown still waits on the same loop. StorageMergeTree::flushAndPrepareForShutdown() / StorageReplicatedMergeTree::partialShutdown() cancel merges and then BackgroundJobsAssignee::finish() calls removeTasksCorrespondingToStorage(), which blocks until the active merge or mutation returns, but MergeTask only notices ctx->is_cancelled() between blocks and calculateAndSerializeSkipIndices() still has no background cancellation source beyond a process-list element. If DROP TABLE ... SYNC, replica partial shutdown, or SYSTEM STOP MERGES lands mid-vector_similarity build, this path still has to wait for the whole block. This needs to consult the existing merge/mutation cancellation carrier here as well, not just the global shutdown flag.
There was a problem hiding this comment.
The symptom is real and I reproduced it on this head: with a background merge inside a
vector_similarity granule, DROP TABLE ... SYNC blocked 97.3s and DETACH TABLE ... SYNC 97.6s,
with the new ABORTED line firing 0 times. isShutdownCalled() is indeed false during table-local
teardown, and unlike the server-shutdown stall this PR fixes, merges_blocker.cancelForever()
(StorageMergeTree.cpp:288) does run before the wait, so the carrier is armed here.
Two corrections to the magnitude, both measured.
The wait is bounded by one index granule, not "the whole block". Varying only
index_granularity: 500 -> 21.8s, 1000 -> 46.8s, 2000 -> 97.3s, linear, against 200s of total
merge work. Changing merge_max_block_size from 4000 to 100 left it at 97.5s, so the bound does
not track the merge block. calculateAndSerializeSkipIndices calls the aggregator once per
granule, and that call is the uninterruptible unit. Merged 2 parts appears 0 times in every
arm, so the merge is cancelled at the granule boundary rather than running to completion.
SYSTEM STOP MERGES does not exhibit this. It returned in 0.09s: it only takes an action lock
and never waits on the active task.
The 97s figures come from the test failpoint pinning 50ms per row. With a realistic index
(dim 96, M=128, efConstruction=2048, 32768 rows per part, no failpoint) DROP TABLE ... SYNC
returned in 3.8s.
On the remedy: the aggregator here holds only index name, sample block, dimensions, metric and
scalar kind, hnsw params and the index. There is no MergeListElement, no blocker and no merge
context at this seam, and no thread-local merge accessor exists in src/. Consulting the
per-merge carrier means threading a cancellation callback through createIndexAggregator, which
has 7 overrides and 5 call sites, two of them not merge paths. That also has to be reconciled
with the narrowing this PR already needed: an earlier round here caused silent StorageBuffer data
loss with a predicate that fired on teardown flush paths, and flushAndPrepareForShutdown is
reachable from DatabaseCatalog::shutdown too.
So I am leaving this PR at server shutdown. The table-local case is a bounded few-second wait on
a realistic index and needs a cancellation carrier plumbed through the skip-index interface, which
I do not think belongs in this change.
CI finish ledger - 14d623eCI is fully finished on this head:
Neither failure is caused by this diff, which changes
CIDB has ingested this commit. The two Moving to review. Session id: cron:our-pr-ci-monitor:20260808-170000 |
|
Fixing PR for the Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) test_concurrent_watches row in the ledger above: #114041 |
|
Closing this as superseded: master now does both halves of it. #115733 cancels the merge list before I checked it with this PR's integration test on master |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a hang on server shutdown while a background merge was building a
vector_similarityindex. The index build had no interruption point on the background path, soSIGTERMcould take minutes to take effect andclickhouse stopfell back toSIGKILL. Only background operations are interrupted; foreground writes, including the flushes that shutdown itself performs, are unaffected.Description
ContextSharedPart::shutdownwaits for the four MergeTree background executors(
Context.cpp:1008-1011) so no background task touches a storage whileDatabaseCatalog::shutdowndestroys it.MergeTreeBackgroundExecutor::threadFunctionchecksits
shutdownflag only before popping a task, so a running task is never interrupted andthat wait is unbounded.
MergeTreeIndexAggregatorVectorSimilaritycan hold it for minutes:updateImplenqueues oneusearch
addper row and drains the pool at the end of the block. Both existing cancellationchecks on that path go through
getProcessListElementSafe(), and their comments nameKILL QUERY: they were written for the query path. A merge has no process-list element, soboth are dead there.
This adds the missing interruption point.
shutdown_calledis an atomic set byshutdown()'sfirst statement, ~50 lines before the wait, so it is true during the stall;
Context::isShutdownCalled()exposes it as a relaxed load.add_vector_to_indexthrowsABORTEDwhen it is set and the operation is a background one(
Context::isBackgroundContext()). That conjunct is load-bearing: shutdown deliberatelywrites after setting the flag, re-scheduling the async insert queue and flushing
Buffertables into their destinations, and a
Bufferflush that throws puts its block back andrelies on a retry shutdown never makes, so aborting it loses rows silently. Both chains
measure as non-background; all four background carriers take theirs from
getBackgroundContext()and stay covered.Validated on a background merge of two 32768-row parts with a vector index: pristine master is
still alive after 60 s (3/3, main thread parked in
Shutting down merges executor); with thefix it shuts down in 0.5-6.5 s (3/3). Reverting only the throw, and making only the predicate
false, each restore the hang; dropping only the conjunct loses all 1000 rows of a
Bufferflush the fix persists. An uncancelled merge still builds an index the reader actually uses
(
USearchSearchCount > 0,== 0for the brute-force control).Scope: this fixes 61% of the
Possible deadlock on shutdownsignature, not all of itThe CI signature
Possible deadlock on shutdown (see gdb.log)is a pool of severalunrelated defects. Classifying thread 1 in
gdb.logfor 23 of 23 unique(pr, sha)occurrences in a 30-day window, the complete population, not a sample:
ContextSharedPart::shutdown->MergeTreeBackgroundExecutor::wait->ThreadPool::waitwaitServersToFinishwaitForTerminationRequest(shutdown never started)BackupsWorker::waitConfigReloader::stop~MergeTreeDataPartWide->clearCachesThis PR addresses the first row (14/23). The others are different subsystems and are out of
scope, as is the single non-vector busy frame inside that row
(
SerializationObjectSharedData::serializeBinaryBulk...) and thefetch/moves/commonexecutors. The signature will therefore keep appearing after this merge; that is
expected and not a sign the fix regressed. The 63 runnable
vector_searchstateless testsare unchanged versus master.