Repository navigation
Cherry pick #114826 to 26.3: Hold the table lock across a lightweight UPDATE pipeline - #116463
Merged
robot-clickhouse-ci-2 merged 14 commits intoAug 28, 2026
Merged
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 #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.
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.
…pdate-pipeline Hold the table lock across a lightweight UPDATE pipeline
…ypick/26.3/114826 # Conflicts: # src/Interpreters/InterpreterAlterQuery.cpp # src/Interpreters/InterpreterUpdateQuery.cpp # src/Storages/MergeTree/ReplicatedMergeTreeSink.cpp
1 task
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Original pull-request #114826
Do not merge this PR manually
This pull-request is a first step of an automated backporting.
It contains changes similar to calling
git cherry-picklocally.If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.
The check results does not matter at this step - you can safely ignore them.
Troubleshooting
If the conflicts were resolved in a wrong way
If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:
pr-cherrypicklabel from the PRYou also need to check the Original pull-request for
pr-backports-createdlabel, and delete if it's presented thereThe PR source
The PR is created in the CI job