Repository navigation
Hold the table lock across a lightweight UPDATE pipeline - #114826
alexey-milovidov merged 12 commits into
Conversation
A lightweight UPDATE racing a DROP TABLE aborted the server with "Logical error: Part patch-... doesn't exist" from MergeTreeData::modifyPartState, reached through MergeTreeData::Transaction::commit inside ReplicatedMergeTreeSinkPatch::finishDelayed. The modifyPartState calls in Transaction::commit sit inside NOEXCEPT_SCOPE, whose catch-all is std::terminate, so release builds died too. InterpreterUpdateQuery::execute acquired the table's shared drop lock into a function-local TableLockHolder and parked only the storage in the returned pipeline. QueryPlanResourceHolder keeps storage_holders and table_locks as separate members, so the lock was released when execute() returned, before any row was pushed and long before the sink committed the patch part. A concurrent DROP was then free to take the exclusive lock; dropAllData() cleared data_parts_indexes and removed the part directory, and the sink's commit could no longer find the part it had just renamed. Move the already-acquired lock into the pipeline's resources, the way InterpreterInsertQuery already does for INSERT. Three entry points reach IStorage::updateLightweight: InterpreterUpdateQuery::execute, InterpreterAlterQuery::executeToTable for the lightweight ALTER UPDATE rewrite, and StorageAlias::updateLightweight, which resolves a different storage and therefore needs the target's own lock, mirroring StorageAlias::read. DELETE FROM needs no change of its own: it rewrites to UPDATE or ALTER UPDATE and re-enters those interpreters. The abort requires a database without a UUID (Memory, Ordinary), because only there does InterpreterDropQuery take the table's exclusive lock and remove the data inline; for an Atomic database the drop is deferred to DatabaseCatalog::enqueueDroppedTableCleanup, whose isSharedPtrUnique gate is held off by the pipeline's own storage holder. In the reported CI run the test database had been recreated as ENGINE = Memory by an unrelated test, which is why the failure was intermittent. The new test opens the failing window deterministically with sleep_before_commit_local_part_in_replicated_table_ms, which the sink honours immediately before the commit that used to fail. It has one arm per fixed entry point; on a binary carrying only the two interpreter fixes the Alias arm is the only one that still aborts, which is what pins the StorageAlias change. Reported by alexey-milovidov on ClickHouse#104431 (STID 3208-458f).
Each arm previously slept a fixed three seconds before issuing its DROP and asserted a constant string. On a slow or loaded run the updater had not yet reached the window between the patch-part rename and the commit, so the DROP took the exclusive lock first, the update failed with an ordinary exception, and the arm still printed its expected line: it passed without exercising the race, even on a binary without the fix. Each arm now runs its update under a deterministic query id, polls system.text_log for the sink's pre-commit pause announcement for that id, and only then drops. The arm prints the real update and drop outcomes, or "commit window never observed" when it never got there, which mismatches the reference and fails the test instead of passing quietly. The poll pins enable_parallel_replicas off. The randomizer otherwise enables parallel replicas with a cluster of other hosts, and the poll then reads a system.text_log that never contained this server's message, which reported the window as missed on 10 of 50 randomized runs. Verified: master still fails with the reported abort, the interpreters-only build still fails only on the alias arm, disabling the window makes the fixed build fail with the "never observed" signal, and 50 randomized runs pass. Also drops the claim that a concurrent TRUNCATE waits for an in-flight lightweight update. TRUNCATE of a MergeTree table takes no exclusive lock (InterpreterDropQuery.cpp:332) and StorageReplicatedMergeTree::truncate releases the holder it is given, so the claim was wrong. Co-Authored-By: Claude Fable 5 <[email protected]>
The stress runner appends ignore_drop_queries_probability=0.2 to every non-upgrade run's client options, and clickhouse-client --fake-drop sets it to 1. When the roll fires on a storage that keeps data on disk, the drop interpreter logs and returns success without dropping anything. The racing DROP would then take no exclusive lock, the updater would complete normally, and the arm would print the expected line without having raced at all. Pin the setting to 0 on every drop the test's logic depends on, and assert the table is really gone afterwards so a drop that silently did nothing is reported as drop=ignored instead of drop=ok. Also halve the poll's worst-case FLUSH LOGS count while keeping its wall-clock budget, so a run that never reaches the window costs the shared shard less.
Internal second-model review (3 rounds, all findings resolved)An independent model reviewed this change cold in three rounds, plus a separate cold review of the resulting code. Every finding below was verified against the source before being accepted or rejected. ❌ Blockers /
💡 Rejected, with evidence
Also checked
Session id: cron:clickhouse-review-slot-8:20260814-135700 |
|
Workflow [PR], commit [0999a9d] Summary: ✅
AI ReviewSummaryThis PR fixes the real lifetime bug behind concurrent lightweight Findings
Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 35/35 (100.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260814-100800 |
|
cc @yariks5s @scanhex12, could you review this? A lightweight UPDATE parked only the storage in its pipeline and let its lockForShare die when the interpreter returned, so a concurrent DROP could clear data_parts_indexes before the sink committed the patch part, and the commit then threw inside NOEXCEPT_SCOPE. The lock now lives in the pipeline's resources, as the INSERT path already does. |
Build profile diff (arm_release)Comparing ✅ No significant changes. 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. Compile time of recompiled translation units11 translation units recompiled, 56 s compile time in total, 11 of them have a recent master baseline. |
The poll that waits for the sink's pre-commit pause keyed on a query_id built only from the database name, plus event_date >= yesterday(). Both are stable across runs on one server, so a rerun matched a row written by an earlier invocation and dropped the table before the current updater had entered the window. Two lanes make that reachable rather than theoretical: the stress runner pins a fixed --database=test_<i> on half its threads (ci/jobs/scripts/stress/stress.py), and the flaky check runs a test many times in one server lifetime. Measured on the same server with rows from three earlier runs present: the old form matched on poll iteration 1, 94 ms after launching the updater, while the updater needs ~600 ms to reach the pause. The new form returns 0 on iteration 1 and matches its own row on iteration 2. With the drop winning outright the update fails, and the reference expects it to succeed, so the stale match turns into a spurious failure on a correct build. Adding $RANDOM to the id is the idiom 38 other stateless tests already use. Co-Authored-By: Claude Fable 5 <[email protected]>
Observing the sink's pre-commit pause proves the pause was entered, not that the drop overlapped it. Flushing and reading system.text_log is unbounded, so on a loaded runner the observation can land after the 10 s pause has elapsed. The drop then runs against no held lock, every arm still prints the expected tuple, and the arm proves nothing on either binary. The drop's own RWLockWritersWaitMilliseconds separates the two cases, and unlike wall-clock it is specific to the lock rather than to everything the statement does. Measured on one server: 0 ms without the fix, 9345-9363 ms with it. Constructed the previously-silent state by delaying the drop past the window: each arm now reports "did not wait for the lock (0ms)" where it used to report drop=ok, on the fixed and the unfixed binary alike. Co-Authored-By: Claude Fable 5 <[email protected]>
The style checker requires every query to system.query_log in a stateless test to constrain current_database, because the test is parallel-safe and an unscoped read can observe a concurrent copy's rows. The predicate has to be currentDatabase() rather than the database holding the table: query_log records the client's current database, which shell_config sets to CLICKHOUSE_DATABASE, while the table under test lives in CLICKHOUSE_DATABASE_1. Pinning the latter finds no row, the wait counter reads as absent, and every arm reports that the drop did not block, so a correct build fails. Measured both ways: currentDatabase() keeps base at 0ms and the fixed build above the bound, the other form returns -1ms on all three arms. Co-Authored-By: Claude Fable 5 <[email protected]>
…-table-lock-across-update-pipeline
The lock-wait assertion required the drop to have waited at least half the pre-commit window. That bound is a wall-clock magnitude, and the time it leaves for the test to notice the window is the same time the test spends noticing it: flushing and reading system.text_log costs about 0.7 s on an idle server, but on a loaded sanitizer runner it is seconds. The flaky check reported 22 failing copies whose waits were 1519 ms to 4783 ms, i.e. every one of them did queue behind the table lock and only the magnitude fell short. Assert that the wait counter is non-zero instead. RWLockImpl::getLock advances it only while a request sleeps on the lock, so it is exactly zero when the drop took the lock uncontended, whatever the machine was doing at the time. A zero on its own cannot separate a server without the fix from a run whose window closed before the drop got there, because neither contends. So a zero no longer prints a verdict: the arm is set up again with a longer window and retried, and only running out of attempts is reported. Two attempts at 10 s and 30 s keep the worst case inside the per-test time limit while covering a delay almost four times the largest one seen in CI. Co-Authored-By: Claude Fable 5 <[email protected]>
Accepting any non-zero wait leaned on the counter being exactly zero whenever the drop did not queue. The timer is started before the lock is requested and reports whole milliseconds off a clock with millisecond resolution, so a drop preempted between those two points can report a small positive value without ever having waited for anything. Require a tenth of the window instead. A drop that overlapped the pause waits out the remainder of it, which is most of the window, so the margin is three orders of magnitude above what scheduling can fabricate. Falling short stays a retry rather than a failure, so this keeps the property that a slow observation does not fail a correct server. Co-Authored-By: Claude Fable 5 <[email protected]>
The test drove the racing DROP into the pre-commit pause installed by
sleep_before_commit_local_part_in_replicated_table_ms, then required the drop's
RWLockWritersWaitMilliseconds to be a large fraction of that window. The
quantity that bounds is
measured wait = window - time spent noticing the window
so the slower the runner, the smaller the measured value. Noticing the window
meant polling system.text_log, and every poll issued a server-global
SYSTEM FLUSH LOGS; the flaky check runs 50 copies at once, so the polling was
itself the load that drove the observation cost up. Under ASAN the test averaged
126s and peaked at 252s against the 180s per-test limit, while every other build
stayed under 82s. Sizing the bound cannot fix that: a threshold low enough to
survive a slow runner is also met by a drop that never contended, and the retry
ladder that covered a missed window is what crossed the limit.
Park the sink instead. rmt_pause_before_commit_local_part stops it between the
patch-part rename and the commit, where the caller still holds the table lock,
and it stays parked until the test resumes it, so the drop cannot miss the window
and slowness no longer eats the signal.
The test now asserts state rather than duration:
- the hook is armed, before anything depends on it being armed,
- the sink has parked (the one-shot failpoint reports itself spent),
- the drop is blocked on the lock. RWLockWaitingWriters is raised on the way in,
before RWLock decides whether the lock is free, so one sample would also match
a drop about to take it uncontended; a blocked drop is the one that stays
blocked, which it must while the sink holds the lock.
Each condition fails with its own diagnostic. SYSTEM WAIT FAILPOINT is bounded so
an update that never reaches the hook says so instead of hanging, and the
failpoint is released from an EXIT trap because it is server-global and would
otherwise park the sink of every later test. That global scope is also why the
test is now no-parallel: it waits on the failpoint, so a concurrent copy could
satisfy this copy's wait or be released by its resume.
One arm takes 5s instead of 60-70s; the slowest of 50 randomized runs was 9.4s.
Mutation-checked: leaving the hook unarmed, pointing it at another failpoint, and
resuming the sink before the drop each report a distinct failure instead of
passing.
The check that the drop was queued behind the table lock sampled the server-wide RWLockWaitingWriters metric. RWLockImpl::getLock raises that counter before it takes internal_state_mtx and before it decides whether the lock is already free, so a positive reading does not establish that the sampled writer had to sleep, nor that it was waiting for this table. The sink is released right after the check, so a reading that did not come from the racing drop leaves the lock handoff untested while the arm still reports success. Read the drop's own ProfileEvents['RWLockWritersWaitMilliseconds'] from system.query_log under its query_id instead. The wait is charged to the statement that blocked, so the value is attributable to that drop and cannot be supplied by another writer. Measured on this tree: 2014-2022 ms when the drop is issued into the held commit window, 0 ms across 200 uncontended drops and 4189 samples with nothing parked. Releasing the sink before the drop is issued, which is the case the check exists to reject, now reddens all three arms; it was caught in one of three before. A lookup that finds no row reports zero and fails closed. The polling loop is gone, so the arm no longer flushes logs while it waits: 30/30 runs pass at 10.0-10.5 s, 12/12 under load at 10.6-10.8 s, and 20/20 with randomised settings.
The style check requires every test reading system.query_log to carry a current_database = currentDatabase() condition, and it is a literal grep over the four accepted spellings rather than a semantic analysis, so filtering on a unique query_id alone fails it (ci/jobs/scripts/check_style/various_checks.sh). The condition also holds for this test by construction: the DROP and this read run through the same client, so both record the session database, while the table being dropped lives in the _1 database. Measured on a debug server, the row matches with the clause and does not match from any other session database. has(databases, currentDatabase()) would not have worked, because the DROP records the target database in databases, not the session one.
CI finish ledger - 0999a9dCI is fully finished on this head and it is clean: 177 check-runs, 160 success / 17 skipped,
The regression test added here, Session id: cron:our-pr-ci-monitor:20260816-003000 |
|
Added backporting label. The issue appears in the 26.7 branch during the upgrade check. |
Cherry pick #114826 to 26.3: Hold the table lock across a lightweight UPDATE pipeline
Cherry pick #114826 to 26.6: Hold the table lock across a lightweight UPDATE pipeline
Backport #114826 to 26.6: Hold the table lock across a lightweight UPDATE pipeline
Backport #114826 to 26.7: Hold the table lock across a lightweight UPDATE pipeline
Backport #114826 to 26.3: Hold the table lock across a lightweight UPDATE pipeline
Related: #104431
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a server abort (
Logical error: Part patch-... doesn't exist) when aDROP TABLEruns concurrently with a lightweightUPDATEon aReplicatedMergeTreetable. The update now holds the table's shared lock until its patch part is committed, so theDROPwaits instead of removing it.Description
Reported by @ alexey-milovidov on #104431: an
Upgrade check (amd_release)abort with no fix on master, STID3208-458f, 4 hits on 4 unrelated PRs in 6 days (report).What breaks. A lightweight
UPDATEracing aDROP TABLEaborts the server, release builds included:Transaction::commit'smodifyPartStatesits inNOEXCEPT_SCOPE, whose catch-all isstd::terminate.Root cause.
InterpreterUpdateQuery::executetakeslockForShareinto a function-local holder and parks only the storage in the returned pipeline;QueryPlanResourceHolderkeepsstorage_holdersandtable_locksseparately, so the lock dies whenexecute()returns, long before the sink commits the patch part. A concurrentDROPthen takes the exclusive lock,dropAllData()clearsdata_parts_indexes, and the commit cannot find its own part. It needs a UUID-less database (Memory/Ordinary), whereDROPremoves data inline, hence the intermittency.The change. Move the already-acquired lock into the pipeline's resources, as the INSERT path does at
InterpreterInsertQuery.cpp:1297. Three entry points:InterpreterUpdateQuery::execute,InterpreterAlterQuery::executeToTable, andStorageAlias::updateLightweight, which resolves a different storage and so needs the target's own lock, asStorageAlias::readdoes.DELETE FROMrewrites toUPDATEand is covered transitively. A concurrentDROPorDETACHnow waits for an in-flight lightweight update, as it already does forINSERT.TRUNCATEtakes no exclusive lock forMergeTree.Validation. New test
04905_lwu_drop_race_table_lock.sh, one arm per fixed carrier. A pauseable failpoint parks the replicated sink between the patch-part rename and the commit, while the update still holds the lock; the arm then drops the table and waits for the drop to block on that lock. Nothing is timed, so an arm cannot miss a window or pass quietly. Aborts without the fix, passes with it, 50/50 green.Both-directions matrix (every cell measured, Build IDs asserted against the running server)
UPDATEALTER ... UPDATEAliasea8e869d3651f11d1884b944The middle row is the control that shows the
StorageAliaschange is necessary: with both interpreter fixes applied, the alias arm is the only one that still aborts.The lock demonstrably serializes the two queries: with the sink parked after the patch-part rename, the
DROPbecomes a waiting writer and stays one until the sink is released, then completes.Deadlock check: the change only extends the lifetime of a Read acquisition, and no sink on this path takes the table lock.
update_sequential_consistency = 1and a followingOPTIMIZE TABLE ... FINALboth complete normally.Version info
26.8.1.1813(included in26.8and later)26.7.6.35,26.6.4.34,26.3.33.39