Skip to content

Fix segmentation fault in RefreshTask::startup() racing a parallel shutdown - #121037

Merged
al13n321 merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-refreshtask-startup-shutdown-race
Sep 23, 2026
Merged

al13n321 merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-refreshtask-startup-shutdown-race

Conversation

@groeneai

@groeneai groeneai commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #105588

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

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 DATABASE rolls the database back, or when the server shuts down while tables are still loading asynchronously.

Description

shutdown() nulls the raw view member under mutex, and its declaration allows it to run in parallel with startup() or before it ("Ok to call even if startup() wasn't called or failed"). startup() dereferenced view three times before taking that mutex, so when a shutdown wins the race, the load of WithContextImpl::context traps instead of getContext() 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 null this plus the offset of WithContextImpl::context, so view was null rather than dangling.

The fix does startup()'s state work under mutex, and moves the dependent notification out of RefreshSet::emplace to its one caller, after the unlock, because notifyDependents ends in notify() on another task's mutex. Registering under mutex also closes a write-write race on the "Not thread safe" RefreshSet::Handle, which emplace assigned holding RefreshSet::mutex while shutdown() resets it holding RefreshTask::mutex.

Every other unguarded view read is reachable only from the scheduling_task and execution_task callbacks, which shutdown() joins through deactivate() (BackgroundSchedulePool.cpp:98 takes the exec_mutex execute() holds across the callback at :141) before nulling view; the AsyncLoader job that calls startup() is not. collectDependencyStates stays unguarded on purpose, its view read sitting behind if (is_shutdown) return;.

The regression test calls flushAndPrepareForShutdown() then startup() 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 TABLE builds a fresh IStorage and RefreshTask, and an ATTACH DATABASE rollback joins the outstanding startup jobs before sweeping (DatabaseOnDisk::shutdown calls stopLoading), measured over 300 cycles with fault injection raised.

Stack trace, and the two CIDB rows this source line has produced in 90 days
DB::WithContextImpl<std::shared_ptr<DB::Context>>::getContext() const  @ 0x000000000e5ffc95
DB::RefreshTask::startup()                                            @ 0x000000001c2c6250
DB::StorageMaterializedView::startup()                                @ 0x000000001b67c000
DB::DatabaseOrdinary::startupTableAsync(...)::$_0
DB::AsyncLoader::worker(DB::AsyncLoader::Pool&)
ThreadPoolImpl<ThreadFromGlobalPoolImpl<false, true>>::ThreadFromThreadPool::worker()
SELECT check_start_time, check_name, test_name, pull_request_number
FROM default.checks
WHERE position(test_context_raw, 'RefreshTask::startup') > 0
  AND check_start_time > now() - INTERVAL 90 DAY
check_start_time check_name test_name pull_request_number
2026-09-19 11:11:23 Stress test (arm_release) Segmentation fault (STID: 1805-2619) 119839
2026-06-24 19:00:20 Stress test (arm_debug) Segmentation fault (STID: 1805-2d15) 108345

The debug row carries line numbers and names RefreshTask.cpp:243, which was the same view-> statement that is :329 today.


Workflow [PR]
Sync PR [sync-upstream/pr/121037]

Version info

  • Merged into: 26.10.1.507-master (included in 26.10 and later)
  • Backported to: 26.9.2.21, 26.8.11.28, 26.7.14.27, 26.3.33.136

groeneai and others added 2 commits September 19, 2026 14:15
…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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings), plus my own
cold review of the resulting tree (3 findings). No blocker and no major from either pass,
so no fix round was needed.

# Sev Finding Verdict Evidence / action
1 💡 A server segmentation fault should be Critical Bug Fix, not Bug Fix DISAGREE I do not self-assign the critical category; a maintainer who wants it can flip the label. The entry itself opens with "Fixes a segmentation fault", so the severity is not hidden.
2 💡 Same finding, second half: the changelog entry must be present tense AGREE, fixed docs/changelog_entry_guidelines.md:48-56 rejects exactly the draft's form ("Instead of: Fixed a crash ... / Write: Fixes a crash where ..."). Entry rewritten in the present tense.
3 💡 Comments should write shutdown, startup, emplace without parentheses, and backtick notifyDependents DISAGREE The convention is the other way in these files: 23 comment lines in RefreshTask.cpp and 21 in RefreshTask.h already cite functions as fn(), and RefreshSet.h:64 reads "Calls notify() on all tasks that depend on id". The new emplace comment is a verbatim copy of the sibling comment 38 lines below it, which writes a bare unbackticked notifyDependents; backticking mine would make the two inconsistent.
4 💡 PR body was over its length budget and offered unrelated work on DatabaseOrdinary::stopLoading() AGREE, fixed Body condensed, and the offer dropped: its premise is wrong. IDatabase.h:279-281 documents stopLoading() as "Cancels all load and startup tasks and waits for currently running tasks to finish ... prevent race with startup", so the wait is the contract, not a LoadTask-destructor side effect.
5 💡 notifyDependents now runs after scheduleRefresh(), so a throw from the latter would skip it DISAGREE scheduleRefresh sets a state field and calls scheduling_task->schedule(), which takes a mutex, checks two flags and enqueues. The only throw is bad_alloc, and it propagates out of startup() and fails the table's startup job whatever the notification order.
6 💡 view is declared above the mutex whose comment says "Protects all fields below", so the field this guard relies on sits outside the documented contract DISAGREE The protection holds in fact: view has exactly two writers, the constructor and shutdown() under mutex, and the new comment states the property at the point of use. Reordering the declaration would grow a three-hunk crash fix for no behaviour change.

What I checked myself beyond the findings, because a lock-scope widening is the risky part of
this change: the new outbound edges from RefreshTask::mutex are RefreshSet::mutex (already
entered under mutex by shutdown, rename and alterRefreshParams through set_handle),
IStorage::id_mutex (already entered at alterRefreshParams), and
StorageMaterializedView::target_table_id_mutex, which is a leaf with two trivial users. There
is no RefreshSet::mutex to RefreshTask::mutex edge left: notifyDependents,
setRefreshesStopped and joinBackgroundTasks each release the lock before touching a task,
and setRefreshSetHandleUnlock takes no lock at all. emplace has exactly one caller in the
tree, so moving the notification to the caller loses no notification.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20260919-141900

@clickhouse-gh clickhouse-gh Bot closed this Sep 19, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 1/1 rather than a rate. A temporary one-line instrumentation (refresher->shutdown() immediately before refresher->startup() in StorageMaterializedView::startup()) forces the interleaving the CI stack trace shows, and a single CREATE MATERIALIZED VIEW ... REFRESH EVERY 1 SECOND then faults every time.
b Root cause explained? Yes. RefreshTask::startup() read its raw view member three times before taking mutex, while shutdown() nulls that member under mutex (RefreshTask.cpp:398). A database-wide shutdown sweep nulls view while an AsyncLoader startup table job is inside startup(), so the load of WithContextImpl::context through a null this traps before that function's own null check can raise a clean error.
c Fix matches root cause? Yes. The unsynchronised accesses become synchronised: the check, the three reads and the RefreshSet registration all happen under mutex. Not a guard at the crash site. A bare if (!view) return; at the top was rejected (narrows the window without closing it, and leaves the handle race); a snapshot-and-recheck shape was rejected too (the recheck cannot repair a torn Handle move).
d Test intent preserved / new tests added? No existing test modified. No new test, deliberately: I wrote the integration test, measured it at 0 of 10 runs reddening against the unfixed binary, and dropped it rather than ship an oracle that cannot fail. A DETACH/ATTACH DATABASE loop cannot reach the window because the attach's own rollback joins the outstanding startup jobs before sweeping the tables. Same precedent as #105588.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. Without the fix (099197af...): exit 139, Address: 0x140. Access: read. Address not mapped to object., frames Context_fwd.cpp:16:18 under RefreshTask.cpp:329:31. With the fix (d4c3328f...): clean start, and system.view_refreshes holds no row for the view, which is the predicted early return.
f Fix is general across code paths? Yes, by proof rather than by grep. All 48 view uses in RefreshTask.cpp were classified; the 3 in startup() are fixed. The other 13 unguarded reads are reachable only from the scheduling_task / execution_task pool callbacks, and shutdown() joins both via deactivate() (BackgroundSchedulePool.cpp:98 takes the exec_mutex that execute() holds across the callback at :141) before nulling view. The doScheduling entry was already fixed in #105588. collectDependencyStates is deliberately NOT guarded: its read sits behind if (is_shutdown) return;, so a guard there would be unreachable.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A on the type axis: view is a single raw pointer, not a typed value, so there is no Nullable / LowCardinality / Array / Map / Const matrix. The behavioural axes that exist are covered: isAppend() both ways, start_paused, stop_refreshable_materialized_views_on_startup, and the coordinated (Replicated) path, which shares this same startup().
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no changed default, no SettingsChangesHistory.cpp entry, no serialized or on-disk format, no Keeper state. Behaviour changes only for a view whose shutdown() has already run, where the current behaviour is a segmentation fault.
i Invariants and contracts preserved? Yes. The invariant is that view and set_handle are accessed only under mutex, and it now holds on every path including the new early return, which leaves scheduling.stop_requested and set_handle as shutdown() left them and skips scheduleRefresh (correct, since schedule() is already a no-op after deactivate()). No new lock edge: RefreshTask::mutex to id_mutex, to target_table_id_mutex and to RefreshSet::mutex all already existed at other sites, and there is no RefreshSet::mutex to RefreshTask::mutex edge anywhere, which is why moving notifyDependents to the caller is what makes the widened section safe. startup() writes no on-disk or Keeper state.

Session id: cron:clickhouse-impl-slot-5:20260919-125800

@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cdec423]

Summary: ✅


AI Review

Summary

This PR fixes the RefreshTask::startup/shutdown race by moving the view dereferences and RefreshSet registration under RefreshTask::mutex, and adds a focused gtest that exercises the sanctioned shutdown()-before-startup() ordering. I did not find a new correctness, locking, or coverage defect in the current diff; the only remaining issue is a changelog-category nit that was already discussed on the PR.

Findings

💡 Nits

  • [PR metadata] [dismissed by author -- https://github.com/Fix segmentation fault in RefreshTask::startup() racing a parallel shutdown #121037#issuecomment-5742921179] The PR body still selects Bug Fix, but the template reserves Critical Bug Fix for crashes and this patch fixes a reproducible segmentation fault. Suggested fix: switch the selected changelog category to Critical Bug Fix.
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 Report

Measured on commit cdec423.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 19/20 (95.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-refreshable-materialized-view Refreshable materialized views: scheduled/periodic refresh, refresh state machine, refresh orches... labels Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit cdec423293030782feda4d388d909616bad99aec was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 878834b

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Finish Workflow / Post Hooks new_tests_check.py PR-caused: this PR is labelled pr-bugfix and changes only RefreshSet.cpp, RefreshSet.h and RefreshTask.cpp, so the merge gate refuses it with "No new tests have been added". It requires a new functional, integration or unit test (or an integration Docker image change) on a bug-fix PR #121037 (mine, this PR: the fix lands here)
Performance Comparison (arm_release, master_head, 5/6) / iceberg_suite_tpch 10 errors, 4 too long, 1 unstable, not PR-caused: the measurement loop raises when one query overruns the harness max_query_seconds cap (perf.py:1067 -> :473) and the report publishes that traceback's head as "10 errors" for the single failing test. Onset 2026-09-18 00:32:42Z, right after #120176 merged; 1620 error rows over 120 distinct PRs in 24h, 240 of them true-master rows #120923 (external, merged 2026-09-19T18:34:47Z)
Mergeable Check, PR praktika rollups of the two rows above, no independent failure #121037 (mine, this PR) and #120923 (external, merged)

The tested tree predates that revert, measured rather than inferred: the failing job's confirmed
checkout 6062a198c49d does not contain 0b3b89d07744, and the run was created 15:07:38Z against a
merge built before 18:34:47Z. I am deliberately not pushing a separate master merge for it, because
the first row already brings a commit to this branch; master comes with that commit, in one CI run
rather than two.

Every CANCELLED check on this commit belongs to the superseded run 35450827515, dispatched 7 seconds
before the live run 35450833288 and cancelled; the live run is 148 pass / 24 skipped / 4 failures.

Session id: cron:our-pr-ci-monitor:20260919-203235

groeneai and others added 3 commits September 19, 2026 21:22
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

The new_tests_check.py post-hook was the only PR-caused failure on the previous head, and it is addressed at 2297970: this adds a unit regression test (RefreshTaskStartupAfterShutdown) and merges master to pick up #120923, the owner of the iceberg_suite_tpch row in the ledger above.

It is a gtest rather than a stateless test because the ordering has no SQL route: ATTACH TABLE builds a fresh RefreshTask, and a database sweep joins the outstanding startup jobs before it begins (DatabaseOnDisk::shutdown() calls stopLoading()), measured at 0 reproductions over 10 integration runs of 30 detach/attach cycles each with thread-allocation fault injection raised. The test calls flushAndPrepareForShutdown() and then startup() on a refreshable view directly: it aborts on the merge-base binary and passes with the fix, which is what Bugfix validation (unit tests) re-measures here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2297970

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
BuzzHouse (amd_tsan) / Logical error: RWLockImpl::getLock(): RWLock is already locked in exclusive mode (STID 2043-396f) RWLock.cpp:159's self-acquisition guard, reached through the database-wide truncate fan-out: IStorage::lockExclusively (IStorage.cpp:185) from InterpreterDropQuery::executeToTableImpl (:339) under executeToDatabaseImpl (:786). An Alias is a name without data, so the alias entry and its target entry converge on one storage and both take its exclusive lock under one shared query id; whichever task runs second aborts. This is the mirror ordering of the master occurrence STID 2043-36a4 (e6b360bb5d27, 2026-09-20 01:04:40Z), which aborts at StorageAlias.cpp:310 instead. The fix removes the convergence, so it covers both orderings. Not reachable from this diff, which touches only src/Storages/MaterializedView/Refresh{Set,Task} #121134 (mine, open)
Build profile diff RuntimeError: CI logs cluster query failed, raised at ci/jobs/build_profile_diff_job.py:234 under compare_symbols: the binary_symbols read against the CI logs cluster failed and the job aborts instead of skipping. Independent of branch content #118708 (mine, open)
Performance Comparison (arm_release, master_head, 1/6) / order_by_read_in_order #1, polymorphic_parts_m #0 Shard summary is 3 too long, 1 slower, 1 unstable; 1 confirmed regression(s) on the performance dashboard. order_by_read_in_order #1 is called slower on 249 distinct PRs and 57 master rows over 14 days, and over 7 days every one of the 187 shards whose summary carries confirmed regression is red while shards saying unstable without it are green in 9889 of 10112 runs. Neither query touches a refreshable materialized view #121090 (mine, open)

Mergeable Check and PR are the workflow aggregators of the rows above.

Session id: cron:our-pr-ci-monitor:20260920-113109

@al13n321
al13n321 enabled auto-merge September 23, 2026 02:24
@PedroTadim PedroTadim added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 23, 2026
@al13n321
al13n321 added this pull request to the merge queue Sep 23, 2026
Merged via the queue into ClickHouse:master with commit 21fd300 Sep 23, 2026
176 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 23, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 23, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 23, 2026
Backport #121037 to 26.9: Fix segmentation fault in `RefreshTask::startup()` racing a parallel shutdown
PedroTadim added a commit that referenced this pull request Sep 23, 2026
Cherry pick #121037 to 26.8: Fix segmentation fault in `RefreshTask::startup()` racing a parallel shutdown
PedroTadim added a commit that referenced this pull request Sep 23, 2026
Cherry pick #121037 to 26.7: Fix segmentation fault in `RefreshTask::startup()` racing a parallel shutdown
PedroTadim added a commit that referenced this pull request Sep 23, 2026
Cherry pick #121037 to 26.3: Fix segmentation fault in `RefreshTask::startup()` racing a parallel shutdown
robot-clickhouse added a commit that referenced this pull request Sep 23, 2026
robot-clickhouse added a commit that referenced this pull request Sep 23, 2026
robot-clickhouse added a commit that referenced this pull request Sep 23, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 23, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 23, 2026
Backport #121037 to 26.8: Fix segmentation fault in `RefreshTask::startup()` racing a parallel shutdown
PedroTadim added a commit that referenced this pull request Sep 24, 2026
Backport #121037 to 26.3: Fix segmentation fault in `RefreshTask::startup()` racing a parallel shutdown
PedroTadim added a commit that referenced this pull request Sep 24, 2026
Backport #121037 to 26.7: Fix segmentation fault in `RefreshTask::startup()` racing a parallel shutdown
NIKTONIKTO717 added a commit that referenced this pull request Sep 24, 2026
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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 25, 2026
…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]>
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 25, 2026
…hTask::startup()` racing a parallel shutdown
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-refreshable-materialized-view Refreshable materialized views: scheduled/periodic refresh, refresh state machine, refresh orches... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants