Repository navigation
Fix segmentation fault in RefreshTask::startup() racing a parallel shutdown - #121037
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. ClickHouse#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.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 findings), plus my own
What I checked myself beyond the findings, because a lock-scope widening is the risky part of Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260919-141900 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260919-125800 |
|
Workflow [PR], commit [cdec423] Summary: ✅
AI ReviewSummaryThis PR fixes the Findings💡 Nits
Final Verdict✅ No code blockers in the current patch. The only follow-up I would ask for is the changelog-category correction above. LLVM Coverage ReportMeasured on commit cdec423.
Changed lines: Changed C/C++ lines covered: 19/20 (95.00%) · Uncovered code |
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - 878834bEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
The tested tree predates that revert, measured rather than inferred: the failing job's confirmed Every Session id: cron:our-pr-ci-monitor:20260919-203235 |
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]>
|
The It is a gtest rather than a stateless test because the ordering has no SQL route: |
CI finish ledger - 2297970Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260920-113109 |
Backport #121037 to 26.9: Fix segmentation fault in `RefreshTask::startup()` racing a parallel shutdown
Cherry pick #121037 to 26.8: Fix segmentation fault in `RefreshTask::startup()` racing a parallel shutdown
Cherry pick #121037 to 26.7: Fix segmentation fault in `RefreshTask::startup()` racing a parallel shutdown
Cherry pick #121037 to 26.3: Fix segmentation fault in `RefreshTask::startup()` racing a parallel shutdown
…rtup()` racing a parallel shutdown
…rtup()` racing a parallel shutdown
…rtup()` racing a parallel shutdown
Backport #121037 to 26.8: Fix segmentation fault in `RefreshTask::startup()` racing a parallel shutdown
Backport #121037 to 26.3: Fix segmentation fault in `RefreshTask::startup()` racing a parallel shutdown
Backport #121037 to 26.7: Fix segmentation fault in `RefreshTask::startup()` racing a parallel shutdown
Master brings #121037 (`RefreshTask::startup` does its state work under `mutex`). The conflict is in `startup`: `start_paused` no longer sets `stop_requested` there; it holds the view in the scheduling gate until the rename that commits the `CREATE OR REPLACE`. The PR is re-applied onto master as a smaller diff (src +126/-51, previously +164/-58): - The data of `requested-<replica>` counts the statements not started yet (`count: N`). `run` sets the count in a multi that also checks the root znode's version (a consume re-creates the request znode at version 0); the start multi removes it against its version and re-creates it with `count: N-1`, so master's czxid takeover clock restarts for the rest unchanged. - The scheduling gate lets an own request through `stop_requested` only. Holds: `not_ready` (uncoordinated restore, lifted by `finalizeRestoreFromBackup` or `start`), `start_paused` (`CREATE OR REPLACE`, lifted by the committing `rename`, so master's post-drop `start` loop in `InterpreterCreateQuery` goes), `shutdown_requested` (never lifted), and `unexpected_error`. - `out_of_schedule` is read once, before the gate; the interrupt flag is reset right after the gate. - `last_attempt_out_of_schedule` replaces `ExecutionState::out_of_schedule`. `wait` returns early on a Disabled view only after a scheduled attempt, and never reports an attempt that ended with `cancelled`. - `finalizeCreateOrReplace`, `markReady` and the `SCOPE_EXIT` in `InterpreterCreateQuery` are gone. Tests: the PR's sections of 04319, 04162 and 05024 move into the new tests 05241, 05242 and 05243, so those master tests keep their tags; 04319 only loses its section 4b, which asserted the deferral this PR removes. 04319 4c and 4f and the second new section of 04887 are dropped as redundant. `test_takeover_waits_for_recreated_request` counts two requests before the first takeover, so it also pins the re-created znode. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ed-rmv-refresh-schedule Conflicts in RefreshTask.h and RefreshTask.cpp, both against ClickHouse#112979 (per-replica RANDOMIZE FOR) and ClickHouse#121037 (startup/shutdown race). SchedulingState: kept both sides, the fields are independent. startup(): took master's shape, which does every view-dependent step under `mutex` and returns early when shutdown() has already nulled `view`. The local-state resolve/load/save moved inside that lock and now reads the captured `context`/`view_id` rather than dereferencing `view` unlocked, which is the access ClickHouse#121037 made safe. DatabaseCatalog does not reach back into RefreshTask, so the catalog lookup under `mutex` cannot invert a lock order. Co-Authored-By: Claude Opus 5 <[email protected]>
…hTask::startup()` racing a parallel shutdown
Related: #105588
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a segmentation fault that happens when a refreshable materialized view is started up and shut down at the same time, for example when a failed
ATTACH DATABASErolls the database back, or when the server shuts down while tables are still loading asynchronously.Description
shutdown()nulls the rawviewmember undermutex, and its declaration allows it to run in parallel withstartup()or before it ("Ok to call even ifstartup()wasn't called or failed").startup()dereferencedviewthree times before taking thatmutex, so when a shutdown wins the race, the load ofWithContextImpl::contexttraps instead ofgetContext()raising a clean exception.Provenance:
Stress test (arm_release), praktika report.Address: 0x158. Access: <not available>. Address not mapped to object.is a small unmapped address, a nullthisplus the offset ofWithContextImpl::context, soviewwas null rather than dangling.The fix does
startup()'s state work undermutex, and moves the dependent notification out ofRefreshSet::emplaceto its one caller, after the unlock, becausenotifyDependentsends innotify()on another task's mutex. Registering undermutexalso closes a write-write race on the "Not thread safe"RefreshSet::Handle, whichemplaceassigned holdingRefreshSet::mutexwhileshutdown()resets it holdingRefreshTask::mutex.Every other unguarded
viewread is reachable only from thescheduling_taskandexecution_taskcallbacks, whichshutdown()joins throughdeactivate()(BackgroundSchedulePool.cpp:98takes theexec_mutexexecute()holds across the callback at:141) before nullingview; the AsyncLoader job that callsstartup()is not.collectDependencyStatesstays unguarded on purpose, itsviewread sitting behindif (is_shutdown) return;.The regression test calls
flushAndPrepareForShutdown()thenstartup()on a refreshable view, the ordering a database-wide sweep produces: it aborts on the merge-base binary and passes with this change. It is a unit test because no query sequence reaches that ordering:ATTACH TABLEbuilds a freshIStorageandRefreshTask, and anATTACH DATABASErollback joins the outstanding startup jobs before sweeping (DatabaseOnDisk::shutdowncallsstopLoading), measured over 300 cycles with fault injection raised.Stack trace, and the two CIDB rows this source line has produced in 90 days
The debug row carries line numbers and names
RefreshTask.cpp:243, which was the sameview->statement that is:329today.Workflow [PR]
Sync PR [sync-upstream/pr/121037]
Version info
26.10.1.507-master(included in26.10and later)26.9.2.21,26.8.11.28,26.7.14.27,26.3.33.136