Skip to content

Interrupt a background vector-similarity index build when the server shuts down - #113692

Closed
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/interrupt-vector-index-build-on-shutdown
Closed

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/interrupt-vector-index-build-on-shutdown

Conversation

@groeneai

@groeneai groeneai commented Aug 6, 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 a hang on server shutdown while a background merge was building a vector_similarity index. The index build had no interruption point on the background path, so SIGTERM could take minutes to take effect and clickhouse stop fell back to SIGKILL. Only background operations are interrupted; foreground writes, including the flushes that shutdown itself performs, are unaffected.

Description

ContextSharedPart::shutdown waits for the four MergeTree background executors
(Context.cpp:1008-1011) so no background task touches a storage while
DatabaseCatalog::shutdown destroys it. MergeTreeBackgroundExecutor::threadFunction checks
its shutdown flag only before popping a task, so a running task is never interrupted and
that wait is unbounded.

MergeTreeIndexAggregatorVectorSimilarity can hold it for minutes: updateImpl enqueues one
usearch add per row and drains the pool at the end of the block. Both existing cancellation
checks on that path go through getProcessListElementSafe(), and their comments name
KILL QUERY: they were written for the query path. A merge has no process-list element, so
both are dead there.

This adds the missing interruption point. shutdown_called is an atomic set by shutdown()'s
first statement, ~50 lines before the wait, so it is true during the stall;
Context::isShutdownCalled() exposes it as a relaxed load. add_vector_to_index throws
ABORTED when it is set and the operation is a background one
(Context::isBackgroundContext()). That conjunct is load-bearing: shutdown deliberately
writes after setting the flag, re-scheduling the async insert queue and flushing Buffer
tables into their destinations, and a Buffer flush that throws puts its block back and
relies 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 the
fix 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 Buffer
flush the fix persists. An uncancelled merge still builds an index the reader actually uses
(USearchSearchCount > 0, == 0 for the brute-force control).

Scope: this fixes 61% of the Possible deadlock on shutdown signature, not all of it

The CI signature Possible deadlock on shutdown (see gdb.log) is a pool of several
unrelated defects. Classifying thread 1 in gdb.log for 23 of 23 unique (pr, sha)
occurrences in a 30-day window, the complete population, not a sample:

Thread-1 state dumps
ContextSharedPart::shutdown -> MergeTreeBackgroundExecutor::wait -> ThreadPool::wait 14
waitServersToFinish 3
waitForTerminationRequest (shutdown never started) 2
BackupsWorker::wait 2
ConfigReloader::stop 1
~MergeTreeDataPartWide -> clearCaches 1

This 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 the fetch/moves/common
executors. The signature will therefore keep appearing after this merge; that is
expected and not a sign the fix regressed. The 63 runnable vector_search stateless tests
are unchanged versus master.

groeneai and others added 5 commits August 6, 2026 05:54
…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.
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
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
review each round plus a separate second-model gate, adjudicated against the recorded
measurements. The final round found nothing (gate findings 0). The substantive findings and
their verdicts, for auditability:

❌ Blocker (round 1) — the first version of the predicate lost data silently

The original check was isShutdownCalled() alone. ContextSharedPart::shutdown sets that
flag as its first statement (src/Interpreters/Context.cpp:958) and then by design
performs two writes that reach the same aggregator:
AsynchronousInsertQueue::flushAndShutdown (:968-969, which re-schedules every queued batch
under the default-true async_insert_queue_flush_on_shutdown), and the Buffer-table flush
via DatabaseCatalog::shutdown (:1023) → StorageBuffer::flushAndPrepareForShutdown →
optimize() → writeBlockToDestination. The second loses rows outright: flushBuffer
returns the block to the in-memory buffer and rethrows on the premise that a later write will
retry (src/Storages/StorageBuffer.cpp:1166-1173), flushAndPrepareForShutdown swallows the
exception (:911-914), and StorageBuffer declares no shutdown() override — so during
shutdown there is no retry and the rows die with the storage.
src/Interpreters/DatabaseCatalog.cpp:313 states the intent this would break verbatim.
Not pre-existing: the older cancellation check was process-list-gated and fired only on
KILL, and chain A is re-scheduled before killAllQueries(). Verdict: AGREE. Resolved by
gating the throw on Context::isBackgroundContext() as well, which needs no plumbing and is
false for both chains. A test arm now asserts a Buffer table's shutdown flush still reaches
its indexed destination; dropping the conjunct reddens that arm and only that arm (0 of 1000
rows persisted instead of 1000).

⚠️ Major (round 2) — the shutdown witness enforced two different budgets

stop_clickhouse silently raises any graceful bound below 180 s to 180 s on LLVM coverage
builds (tests/integration/helpers/cluster.py:5409-5417), and that flavour does run this
module: it is not matched by LLVM_COVERAGE_SKIP_PREFIXES and does not call
is_built_with_llvm_coverage(), so integration_test_excluded_from_llvm_job does not claim it
(ci/jobs/integration_test_job.py:450-455) while integration_test_llvm_coverage_jobs
(ci/defs/job_configs.py:1216-1230, wired in both pull_request.py:142 and master.py:50)
does. An uninterrupted build needs 2 * 1000 * 50 ms = 100 s, so at an effective 180 s window
the old assert node.stop_clickhouse(...) passed on an unfixed binary, while an
elapsed < 30 leg could fail a fixed one. Verdict: AGREE. The bound is now resolved once
and passed to both legs, at exactly 180 on sanitizer and coverage builds — the value at which
the helper's own < 180 guard is false, so no override can apply. Skipping the arm on those
flavours was considered and rejected: it would delete the only witness on the flavour that
produces most of the observed CI rows.

⚠️ Major (round 3) — stop_clickhouse's return value is not an oracle

It returns True the instant get_process_pid() is None
(tests/integration/helpers/cluster.py:5424-5429), so it conflates "shutdown completed" with
"the process is gone by any means". A wall-clock bound over that boolean cannot be repaired
by tuning the fixture, and raising the row count to outlive the bound was measured into a
container death (exit 137 — not memory: peak 950 MiB of 12 GiB, OOMKilled=false).
Verdict: AGREE. The witness now keys on the server's own log instead: the
Background threads finished line (LOG_INFO, programs/server/Server.cpp:1573) is written
by a scope guard registered at :1568, before the guard that contains
global_context->shutdown() at :1674; being registered earlier it is destroyed later, so
the line is emitted strictly after the executor wait that stalls and a wedged server can never
produce it. The shape follows the in-tree precedent
test_database_catalog_shutdown_system_logs/test.py:115-141. A second assertion on the
ABORTED line covers the mechanism. Both are kept because each is load-bearing on a different
flavour: at the fast-build bound the terminal assertion reddens a reverted fix, at the wide
bound the mechanism assertion does.

⚠️ Major (round 3) — one stated mechanism was wrong, and the verdict got stronger

The exit 137 above was attributed to pkill -15 clickhouse reaching PID 1 because PID 1's
command line contains clickhouse. That would require pkill -f; the call is a bare
pkill {} clickhouse (cluster.py:5419-5422), which matches the process name, and PID 1's
name is bash. Confirmed on procps-ng 4.0.4: a process with comm=bash whose command line
contains a marker gives no match without -f and a match with it. The misreading is easy
because the sibling helper get_process_pid does use -f (:5785). Verdict: AGREE — and
because the container death is therefore unexplained, no row count can be argued safe
either, which is exactly why the oracle rather than the fixture was changed.

💡 Nits, all resolved

  • The accessor comment claimed ContextSharedPart::shutdown "holds shared->mutex while
    doing its work". Brace-matched, that function takes the mutex at exactly :965, :1042 and
    :1110, and the executor waits this PR is about (:1008-1011) are outside all three. The
    lock-free accessor stays; the justification was rewritten to the accurate one.
  • A prescribed test helper turned out to be a vacuous oracle and was substituted after
    measurement: contains_in_log globs the rotated log set (cluster.py:5627-5632), and with
    rotateOnOpen plus the arm's own restart each iteration leaves a marker in a rotated file,
    so after 10 iterations the glob saw 10 markers where the live file had 0 — it would have
    passed on any binary. Both assertions use
    grep_in_log(..., from_host=True, only_latest=True): from_host keeps the oracle readable
    if the container dies, only_latest keeps the scan off the rotated files.
  • A fixture constant introduced by an earlier round became dead once the oracle no longer
    raced the fixture duration, and was removed; the helper it had parameterised was verified
    byte-identical to its previous form.
  • Two countables were stated without the predicate that reproduces them, and one predicate was
    described wrongly. Corrected: the suite figure is 63 runnable tests (60 .sql + 3 .sh
    by filename), against 268 files in that directory whose names match vector_search at
    all and 192 matching lines — three different numbers, so the predicate has to be named.
    A mutant count also disagreed with its own enumeration (three: the check removed, the
    predicate forced false, the conjunct dropped) and was fixed. Every file:line in the body
    was re-verified against origin/master.

Noted, not blocking

The mechanism assertion greps for the ABORTED message text, and the executor logs that
exception at LOG_DEBUG (src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp:198-199) —
the same property for which a Shut down storages. marker was rejected. It is not fragile
here, because MergePlainMergeTreeTask::executeStep logs the same message at error level
first (MergePlainMergeTreeTask.cpp:72) and rethrows, so the string is present independently
of the debug branch.

The predicate's carrier set was re-enumerated independently each round and matches the shipped
code: is_background_operation has one writer tree-wide (Context.cpp:3808), it is true for
all four plain and replicated merge and mutation carriers and reaches the build-pool worker via
the merge thread group, and it is false for every write shutdown itself performs — the Buffer
and async-insert flushes named above, and also BackupsWorker, the DDL worker, system logs,
refreshable materialized views and the streaming storages shut down at Context.cpp:1000.

Final round: cold review plus an independent gate pass on f4a6ac4be549abf, gate findings
0, with the reviewed diff scope matching the intended change exactly. Source is untouched
by the last round and the build id is unchanged, as a test-only change requires.

Session id: cron:clickhouse-review-slot-10:20260806-151600

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A background merge of two 32768-row parts with a vector_similarity index, SIGTERM mid-build: pristine master is still alive at the 60 s bound 3/3, the fix shuts down in 0.5-6.5 s 3/3. The shipped integration test is deterministic too (pristine master fails it on every run). Not a "~1%" repro.
b Root cause explained? ContextSharedPart::shutdown waits unbounded on the MergeTree executors (Context.cpp:1008-1011); MergeTreeBackgroundExecutor::threadFunction checks shutdown only before popping, so a running task is never interrupted. The running task is a vector-index build whose only two cancellation checks go through getProcessListElementSafe(), and a merge has no process-list element (src/Storages/MergeTree/ has exactly one setProcessListElement, in the foreground EXPLAIN WHATIF estimator).
c Fix matches root cause? Yes: it adds the missing interruption point at the per-row seam, using shutdown_called, which is set by shutdown()'s first statement ~50 lines before the wait. The throw is gated on Context::isBackgroundContext, so it reaches only the operations the process-list check cannot see. No widened bound, no timeout on ThreadPool::wait (that would reintroduce the #85433 SIGBUS class the four waits exist to prevent), no no-random-* tag, no dataset reduction, no defensive check at the crash site.
d Test intent preserved / new tests added? New tests/integration/test_vector_similarity_index_shutdown with three cases: the witness; a positive control asserting an uncancelled merge still completes, returns the same neighbours as a brute-force scan and actually consulted the index (ProfileEvents['USearchSearchCount'] > 0 for the indexed query, == 0 for the control); and a regression arm asserting a Buffer table's shutdown flush still reaches an indexed destination. No existing test weakened: the 63 runnable vector_search stateless tests (60 .sql + 3 .sh) are identical on both arms (0 verdict changes).
e Both directions demonstrated? Yes, on separate binaries, one docker container per arm, with the test's own preconditions (failpoint enabled, merge still in system.merges, still 2 active parts) asserted immediately before every verdict. Pristine master: hang past the bound. Fix: shutdown proceeds, and the log shows Code: 236 ... ABORTED 0.10 s after Shutting down merges executor. Three mutants each redden exactly one arm and nothing else: removing the check, or making the predicate runtime-false, reddens only the shutdown witness; dropping the isBackgroundContext conjunct reddens only the Buffer arm (0 of 1000 rows persisted instead of 1000). The witness keys on the log, not on stop_clickhouse's return: it asserts the Background threads finished line the server writes after the wait that stalls, plus the ABORTED line, both read from the host with only_latest=True. Measured on both build flavours: at the fast-build bound the terminal assertion reddens the mutants, at the slow-build bound the ABORTED one does.
f Fix is general across code paths? Fixed at the source (the shared add_vector_to_index lambda), not at the crash site. Censused all six MergeTreeIndexAggregator*::update overrides: only the vector one drives a parallel per-row pool. A mutant arm measured text and set(0) merges shutting down promptly on pristine master too (5.5 s), so the optional second check site in calculateAndSerializeSkipIndices was deliberately not added: no mutant distinguishes it.
g Fix generalizes across inputs (params/datatypes/wrappers)? All three updateImpl instantiations (ColumnFloat32, ColumnFloat64, ColumnBFloat16) share the fixed lambda. Every background carrier derives its context from getBackgroundContext() (MergePlainMergeTreeTask.cpp:223, MergeFromLogEntryTask.cpp:362, MutatePlainMergeTreeTask.cpp:207, MutateFromLogEntryTask.cpp:239), so projection sub-merges (which bypass MergeList::insert entirely), mutations, and replicated vs plain merges are all covered by construction; measured isBackgroundContext = true on the background merge path.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting (so no SettingsChangesHistory.cpp entry), no serialization or format change, no interface change. fiu_do_on expands to nothing when USE_LIBFIU is off, so the test failpoint costs release builds nothing.
i Invariants and contracts preserved? The throw happens in a task enqueued by ThreadPoolCallbackRunnerLocal; waitForAllToFinishAndRethrowFirstError() surfaces it and MergeTreeBackgroundExecutor::routine's catch (...) already handles a throwing executeStep by calling item->cancel(), verified in the log, where the exception is reported and shutdown then proceeds. MergePlainMergeTreeTask::cancel already handles new_part->removeIfNeeded() and temp-dir cleanup, and the positive control shows no bad part is left behind. No noexcept boundary is crossed. The accessor takes no lock and reads an atomic set once at the start of shutdown, so it needs no coordination with the shutdown it reports. The writes shutdown itself performs are excluded rather than aborted: isBackgroundContext measures false for both the async-insert flush-on-shutdown and the StorageBuffer flush, so neither loses rows. Foreground behaviour is unchanged (shutdown_called is false while running); KILL QUERY on an indexed INSERT still cancels in 0.27 s via the pre-existing check, with zero occurrences of the new abort.

Session id: cron:clickhouse-impl-slot-7:20260806-142804

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 7, 2026
@PedroTadim PedroTadim self-assigned this Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [14d623e]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) FAIL
test_keeper_back_to_back/test.py::test_concurrent_watches FAIL cidb
Stress test (arm_msan) FAIL
Logical error: Bad cast from type A to B (STID: 3520-4525) FAIL cidb

AI Review

Summary

This PR adds a shutdown-specific interruption point to vector_similarity skip-index builds and a focused integration suite around full server shutdown. The main shutdown hang is addressed, but the implementation hard-codes the global-shutdown signal and still misses the existing table-local/background cancellation paths, so I do not think it is ready to merge as-is.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp:405] The new interruption point only checks Context::isShutdownCalled(). StorageMergeTree::flushAndPrepareForShutdown() / StorageReplicatedMergeTree::partialShutdown() cancel merges and then block in BackgroundJobsAssignee::finish() -> removeTasksCorrespondingToStorage() waiting for the active merge or mutation to return, but MergeTask only latches ctx->is_cancelled() between blocks and calculateAndSerializeSkipIndices() still has no background cancellation source besides a process-list element. If DROP TABLE ... SYNC, replica partial shutdown, or SYSTEM STOP MERGES lands while a block is inside the vector_similarity add loop, this PR still waits for the whole block to finish.
    Suggested fix: make the per-row check consult the existing background-task cancellation carrier (the merge/mutation cancel predicate or an equivalent signal exposed through the query context) in addition to the global shutdown flag, and add a focused repro for one storage-local path.
Tests
  • ⚠️ Add one focused integration test that triggers a slow background vector_similarity build and then exercises a storage-local cancellation path such as DROP TABLE ... SYNC or SYSTEM STOP MERGES. The current suite only proves full server shutdown and the Buffer-flush exclusion.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.90% +0.10%

Changed lines: Changed C/C++ lines covered: 28/29 (96.55%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 14d623eee with master c8cea90a1 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 2999ffda7; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: compile time of recompiled translation units.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.38 MiB 687.39 MiB -2.99 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.

Object file sizes

568 object files changed (+321.11 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/HiveTextRowOutputFormat.cpp.o new 148.12 KiB +148.12 KiB
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationMap.cpp.o 2.16 MiB 2.18 MiB +21.09 KiB (+0.96%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationArray.cpp.o 228.85 KiB 249.85 KiB +21.00 KiB (+9.18%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp.o 508.78 KiB 529.75 KiB +20.97 KiB (+4.12%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationTuple.cpp.o 271.66 KiB 292.33 KiB +20.66 KiB (+7.61%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units ⚠️

1733 translation units recompiled, 7930 s compile time in total, 1222 of them have a recent master baseline.

Translation units without a recent master baseline:

  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp: 26.3 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp: 11.1 s
  • contrib/vectorscan-cmake/__/vectorscan/src/nfagraph/ng_violet.cpp: 6.9 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/CodeGen/AssignmentTrackingAnalysis.cpp: 6.2 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/executor/instantiate/component/component.cpp: 6.2 s
  • contrib/ai-sdk-cpp-cmake/__/ai-sdk-cpp/src/providers/openai/openai_factory.cpp: 6.0 s
  • contrib/s2geometry-cmake/__/s2geometry/src/s2/s2builder.cc: 5.9 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/utils/TableGen/GlobalISelEmitter.cpp: 5.8 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/executor/engine/threadInstr.cpp: 5.8 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/executor/instantiate/table.cpp: 5.6 s
  • contrib/vectorscan-cmake/__/vectorscan/src/rose/rose_build_program.cpp: 5.4 s

Job report

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f4a6ac4

CI is fully finished on this head and there are no failures to own.

Check / test Reason Owner / fixing PR
(none) all 175 check-runs completed: 155 success, 20 skipped, 0 failure n/a
Sync - CH Inc sync (private, not actionable by me)

Config Workflow and Finish Workflow both success; Style check, Mergeable Check and PR are
success (CH Inc sync is still pending, which is the private sync and not actionable here).

One clarification so the CIDB rows are not misread: test_vector_similarity_index_shutdown/test.py::test_shutdown_still_flushes_buffer_table_into_indexed_destination
appears as FAIL under Bugfix validation (integration tests, amd64) and (aarch64). That is the
master-binary side of bugfix validation, which must fail to prove the new test catches the bug.
Both of those jobs concluded success, as did Bugfix validation (unit tests), so this is the
intended signal rather than a failure to own.

Session id: cron:our-pr-ci-monitor:20260807-130000

@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

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
  • StressHouse run: 74637a00-b3c5-4294-bf80-80921359d7b4
  • MIRAI run: 37f806fc-beff-4afb-b7cc-a84c60094747
  • PR check IDs:
    • clickbench_355994_1786222448
    • clickbench_356000_1786222448
    • clickbench_356011_1786222448
    • tpch_adapted_1_official_356029_1786222448
    • tpch_adapted_1_official_356037_1786222448
    • tpch_adapted_1_official_356064_1786222448

…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())

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.

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.

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.

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.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 14d623e

CI is fully finished on this head: Config Workflow and Finish Workflow are both green and 0
check-runs are queued or in progress. Every failure below has an owner.

Check / test Reason Owner / fixing PR
Stress test (arm_msan) / Bad cast from DB::ColumnString to DB::ColumnNullable (STID 3520-4525) trunk bug #113925 (open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / test_keeper_back_to_back::test_concurrent_watches flaky a fix task is created (investigating at full effort, fixing-PR link to follow here)
CH Inc sync private upstream sync CH Inc sync (private, not actionable)

Neither failure is caused by this diff, which changes FailPoint.cpp, Context.{cpp,h},
MergeTreeIndexVectorSimilarity.cpp and adds one integration suite:

  • STID 3520-4525 is the Nested-member-subcolumn read crash on an unrewritten part, fixed in NestedUtils.cpp
    by Fix crash reading a Nested member subcolumn from an unrewritten part #113925. Nothing here touches Nested subcolumn resolution.
  • test_concurrent_watches fails assert 999 == 1000 at test_keeper_back_to_back/test.py:832, one watch
    of 1000 missing. This branch makes no Keeper or Coordination source change: the only keeper lines a grep
    finds are pre-existing context in the failpoint registration block next to the one entry added here.
    Breadth is 6 rows across 5 unrelated PRs and 0 master hits in 90 days, every hit on a sanitizer or
    coverage shard. An open-PR search finds no fixing PR (the one same-named fix, Fix test_keeper_back_to_back/test.py::test_concurrent_watches #60749, merged in
    March 2024, two years before every sighting), so a fix task now owns it.

CIDB has ingested this commit. The two Bugfix validation (integration tests, *) FAIL rows for
test_shutdown_still_flushes_buffer_table_into_indexed_destination are the master-binary arm of that
check, which must fail to prove the new test catches the bug; both jobs report SUCCESS, so there is
nothing to own there. Report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113692&sha=14d623eee2821f7fe35fc6ba81675c9845318ecb&name_0=PR

Moving to review.

Session id: cron:our-pr-ci-monitor:20260808-170000

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) test_concurrent_watches row in the ledger above: #114041

@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing this as superseded: master now does both halves of it. #115733 cancels the merge list before ContextSharedPart::shutdown waits for the merges executor, and #123062 (relanded in #123739) makes the vector similarity index build check the merge's cancellation for every added row.

I checked it with this PR's integration test on master f38054d23d73 plus only its failpoint, none of the fix (the mechanism assertion pointed at master's Cancelled merging parts message): all 3 tests pass, and the merge is aborted 53 ms after Cancelling merges, mutations and fetches. Removing either merge_list.cancelAll() or the per-row CurrentThread::checkIfNotCancelled() makes the shutdown test fail again.

@groeneai groeneai closed this Nov 24, 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-vector-index Vector similarity index in MergeTree: ANN/HNSW index build/query, usearch integration, vector ind... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants