Repository navigation
Cherry pick #121037 to 26.7: Fix segmentation fault in RefreshTask::startup() racing a parallel shutdown - #121743
Conversation
…utdown RefreshTask::startup() dereferenced its raw `view` member three times before taking `mutex`, while shutdown() nulls that member under `mutex` (RefreshTask.cpp:398). The header already sanctions that ordering: shutdown() is documented "Ok to call multiple times, including in parallel. Ok to call even if startup() wasn't called or failed." So a database-wide shutdown sweep (DatabaseWithOwnTablesBase::shutdown() -> flushAndPrepareForShutdown() -> RefreshTask::shutdown()) can null `view` while an AsyncLoader `startup table` job is still inside startup(), and the load of WithContextImpl::context through a null `this` traps before that function's own null check can turn it into a clean exception. Reported as `Segmentation fault (STID: 1805-2619)` in Stress test (arm_release), and previously as STID 1805-2d15 in an arm_debug build, which named RefreshTask.cpp:243, the same statement that is :329 today. Do startup()'s state work under `mutex`, and move the dependent notification out of RefreshSet::emplace to the caller, after the unlock. The move is what makes widening the critical section safe: notifyDependents() ends in notify() on another task's mutex, so holding `mutex` across emplace() as it stood would have created a RefreshTask(A)::mutex -> RefreshTask(B)::mutex edge that exists nowhere else, and that collectDependencyStates() and notifyDependentsIfNeeded() both unlock specifically to avoid. emplace() has exactly one caller, so the contract change costs one line, and its declaration now states the obligation in the wording RefreshSet.h already uses for addTaskLocked(). Registering under `mutex` also closes a second, worse race on the same window. RefreshSet::Handle is documented "Not thread safe"; emplace() assigned it via setRefreshSetHandleUnlock() while holding RefreshSet::mutex only, whereas shutdown() reads getID() and calls reset() holding RefreshTask::mutex only. Handle's move assignment moves a std::list iterator that reset() then feeds to std::list::erase, so a torn move meant heap corruption, not just a null read. Alternatives rejected: a bare `if (!view) return;` at the top narrows the window without closing it and leaves the handle race untouched; a snapshot-unlock-register-recheck shape cannot repair a torn Handle move; a second RMT-style startup_shutdown_mutex buys nothing here, since `view` and `set_handle` already live under `mutex`; and guarding StorageMaterializedView::startup() instead would move the race rather than fix it, because that class has no mutex covering the state. No test. The window needs a database sweep to overlap an executing AsyncLoader startup job, and a DETACH/ATTACH DATABASE loop cannot arrange it: the attach's rollback goes through DatabaseOnDisk::shutdown() -> stopLoading(), whose LoadTask destructor waits for the outstanding startup jobs before the sweep begins. Measured over 300 attach cycles with thread-allocation fault injection raised and startup_mv_delay_ms active: 1143 sweeps, 120 rollbacks, zero overlap. Verified instead by forcing the interleaving with a temporary instrumentation, which faults without this change at the reported frame and starts cleanly with it. #105588 fixed the same defect family in this file the same way, also without a test. Every other unguarded `view` read is reachable only from the scheduling_task or execution_task pool callbacks, which shutdown() joins through deactivate() before nulling `view`: deactivate() takes the exec_mutex that execute() holds across the callback (BackgroundSchedulePool.cpp:98 vs :141 and :169). startup()'s caller is an AsyncLoader job, which that barrier does not cover. collectDependencyStates() is deliberately left unguarded, because its `view` read sits behind `if (is_shutdown) return;` and a guard there would have an unreachable precondition. Co-Authored-By: Claude Opus 5 <[email protected]>
Drop the clause justifying the emplace() placement; keep the set_handle thread-safety property as a standalone invariant.
This supersedes the "No test." paragraph of 4c78c7f. The ordering is not reachable from SQL, but it is reachable through the two IStorage methods the database-wide shutdown sweep itself calls, so the test drives those directly: flushAndPrepareForShutdown() nulls RefreshTask::view, and an AsyncLoader `startup table` job can still call startup() afterwards, which is the interleaving the reported stack trace shows. A functional test cannot host it. ATTACH TABLE builds a fresh IStorage with a fresh RefreshTask, so it never calls startup() on a shut-down task, and an ATTACH DATABASE rollback joins the outstanding startup jobs before it sweeps (DatabaseOnDisk::shutdown() calls stopLoading()): measured zero reproductions over 10 integration runs of 30 detach/attach cycles each, with thread-allocation fault injection raised and startup_mv_delay_ms active. The fixture is a plain constructor call: an explicit TO target means no inner table is created, LoadingStrictnessLevel::ATTACH skips the engine and access sanity checks, and a non-Replicated database leaves the refresh uncoordinated, so no Keeper is involved. Measured both directions on a debug build: the test aborts the process on the merge-base binary and passes with the fix, which is what `Bugfix validation (unit tests)` re-measures in CI. Co-Authored-By: Claude Opus 5 <[email protected]>
The first version said a database-wide sweep produces the startup-after-shutdown order, then said the same sweep joins the in-flight startup jobs, which reads as a contradiction. State the RefreshTask contract that licenses the order instead (shutdown() is documented callable before or during startup()), and keep the measured reason the two calls are made directly. The CI provenance and the measurements stay in the commit message of the test and in the PR body, not in the source. Co-Authored-By: Claude Opus 5 <[email protected]>
…down-race Fix segmentation fault in `RefreshTask::startup()` racing a parallel shutdown
Resolved: real divergence, not a missing prerequisiteThe conflict is one hunk, in Resolution pushed to my fork as The three touched translation units, including the new gtest, compile clean on the 26.7 tree with 26.7's own pinned clang-21. The full both-directions run was done on the 26.3 arm (#121742), the divergent one, where the regression test passes 3/3 with the fix and segfaults 3/3 without it. I hold |
The conflict was the head of `startup()`, which the change rewrites wholesale. Took the new body, with one adaptation: this branch has no `isAppend()` and reads the `refresh_append` member directly. That call had auto-merged into the new body outside the conflict region, so it would not have compiled. The rest applies as upstream: this branch's `RefreshSet::emplace` still called `notifyDependents` internally, so moving that call out to `startup()` after the unlock preserves the behaviour while keeping the widened critical section free of a task-to-task lock edge. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Original pull-request #121037
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.
Before you resolve anything
Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.
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