Skip to content

Avoid a one-minute shutdown delay after writing an access entity to disk - #118099

Merged
fm4v merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-disk-access-storage-shutdown-stall
Nov 1, 2026
Merged

fm4v merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-disk-access-storage-shutdown-stall

Conversation

@groeneai

@groeneai groeneai commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

clickhouse-local and clickhouse-server no longer take an extra minute to exit when the last operation before shutdown created, dropped or renamed an access entity (a user, role, settings profile, row policy, quota or masking policy) in the local_directory access storage.

Description

DiskAccessStorage writes its .list files from a background thread that first waits up to a minute, so that several list updates can be batched. stopListsWritingThread asked that thread to exit by calling notify_one on lists_writing_thread_should_exit, holding no lock and recording nothing. If the thread had not reached its wait_for yet, the notification was dropped, the thread waited out the whole minute, and join held shutdown open for it. clickhouse-local reaches this most easily, because the DDL is usually the last thing the process does, so shutdown starts about a millisecond after the thread is created.

I now record the request in a mutex-guarded flag before notifying, and pass the wait_for the predicate that reads it. The same line previously let a spurious wakeup return early and skip writeLists, which this also settles.

CREATE and DROP always schedule a list write and ALTER does when it renames, so every access entity type reaches this through the single scheduleWriteLists. The constructor and SYSTEM RELOAD USERS write the lists inline and start no thread. The code is from 2020.

In CI it appears as 04902_access_entity_map_setting_round_trip being killed at the 60 s per-test cap in Fast test, which drops the rest of the matrix: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116793&sha=a1ada61eaceb3825f95652b597d18c8920b07f5e&name_0=PR&name_1=Fast%20test

Validation: the new unit test fails on master with shutdown() took 60000 ms and passes 400 iterations with the fix, the slowest shutdown taking 1 ms. End to end, 6144 clickhouse-local invocations at 32-way concurrency with default settings gave 5 runs over 55 s before the fix and 0 after, with nothing between 30 s and 55 s in either arm.

A shell test cannot force this interleaving: the one setting that makes it deterministic (--max_thread_pool_size=1) makes that single pool thread the bottleneck for the rest of shutdown, so it stalls with the fix too.

The same stall is already visible in CI as a slow pass (click to expand)
SELECT countIf(test_duration_ms BETWEEN 6000 AND 29999) AS d_6_30s,
       countIf(test_duration_ms BETWEEN 30000 AND 54999) AS d_30_55s,
       countIf(test_duration_ms BETWEEN 55000 AND 85000) AS d_55_85s,
       count() AS total
FROM default.checks
WHERE test_name = '04902_access_entity_map_setting_round_trip'
  AND test_status = 'OK' AND check_start_time > now() - INTERVAL 7 DAY
  AND check_name IN (
    SELECT check_name FROM default.checks
    WHERE test_name = '04902_access_entity_map_setting_round_trip'
      AND test_status = 'OK' AND check_start_time > now() - INTERVAL 7 DAY
    GROUP BY check_name HAVING quantile(0.9)(test_duration_ms) < 25000);

d_6_30s  d_30_55s  d_55_85s  total
14541    0         44        24946

In the suites whose per-test timeout is far above 60 s, the same event is recorded as a slow OK:
44 runs at baseline plus a minute, and not a single run in the whole 30 s to 55 s band. Load
produces a continuum; one fixed timeout produces a gap and a cluster. For Fast test itself the
same 7 days give 4268 passing runs with p50 2760 ms, p90 3310 ms and a maximum of 5960 ms, so the
two 60 s failures are ten times the slowest pass ever observed.


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

Version info

  • Merged into: 26.11.1.1009-master (included in 26.11 and later)

groeneai and others added 4 commits September 4, 2026 08:21
…sStorage

DiskAccessStorage writes its .list files from a background thread that first
waits up to a minute so that several list updates can be batched.
stopListsWritingThread asked that thread to exit by calling notify_one on
lists_writing_thread_should_exit while holding no lock and recording no state,
and the thread waited on the plain wait_for overload with no predicate. A
notify_one with no waiter armed is a no-op, so whenever the thread had not yet
taken mutex and entered its wait, the request was lost: the thread waited out
the full minute, and join() held shutdown open until it did.

clickhouse-local reaches this most easily, because an access-entity DDL is
usually the last thing the process does, so shutdown starts about a
millisecond after the thread is created. Measured on a debug build, 6144
invocations of "CREATE SETTINGS PROFILE ... SETTINGS http_response_headers"
at 32-way concurrency with default settings: 5 processes took just over 60
seconds and nothing at all took between 30 and 55 seconds. In CI the same
event kills 04902_access_entity_map_setting_round_trip at the 60 second
per-test cap of Fast test, which then drops the rest of the matrix; in the
suites whose cap is far above a minute it is instead recorded as a slow pass,
44 times in 7 days against 24946 runs.

Record the request in a mutex-guarded flag before notifying, and give the
wait_for the predicate that reads it. Because the predicate is checked before
the thread blocks, a request that arrived early is observed instead of lost.
The same line previously let a spurious wakeup return early and skip
writeLists(), which the predicate also settles: only a real exit request
returns early now, and a timeout falls through to the write as intended.

The flag is never reset because shutdown() is terminal, and mutex is released
before join() since listsWritingThreadFunc acquires it. All of CREATE, ALTER
and DROP of a user, role, settings profile, row policy and quota are covered,
since insertNoLock, removeNoLock and updateNoLock share one scheduleWriteLists.

The behaviour dates from 2408c8c (2020-02-27).

Co-Authored-By: Claude Opus 5 <[email protected]>
…meout

Insert an entity and then shut the storage down immediately. In that ordering
the request to stop the background lists-writing thread is issued before the
thread has started waiting for it, which is the interleaving that used to lose
the request. Writing the lists takes a millisecond, so a 20 second bound
separates a healthy shutdown from one that waits out the one-minute batching
timeout by a wide margin in both directions.

A stateless test cannot force this: from a shell only server settings and
machine load are available, and the one setting that makes the ordering
deterministic, max_thread_pool_size=1, makes that single pool thread the
bottleneck for the rest of shutdown instead, so it stalls either way.

Measured on a debug build: 20 of 20 iterations fail without the preceding
commit, each reporting "shutdown() took 60000 ms", and 20 of 20 pass with it
in 1 ms.

Co-Authored-By: Claude Opus 5 <[email protected]>
…eadable

The stalling interleaving is not guaranteed on a single pass: if the background
thread reaches its wait before the stop request is issued, even the unfixed
code delivers the request and shuts down promptly. Twenty iterations, each with
its own directory and storage, make one lucky ordering insufficient, and the
bound is a fatal assertion so the unfixed build pays one one-minute wait rather
than twenty.

Checking that need_rebuild_lists.mark is absent and users.list exists could not
distinguish a shutdown that wrote the lists from one that never scheduled them,
because the constructor's recovery path creates users.list before the code under
test runs. Reopen the directory and resolve the inserted user instead: with the
marker absent the second storage reads the .list files rather than rebuilding
from the <id>.sql files, so it finds the user only if users.list names her.
Making scheduleWriteLists return immediately passes the old assertions and
fails this one.

Correcting the scope stated in the preceding commit message: creating or
dropping any of the six access entity types always schedules a list write,
while an ALTER does so only when it renames the entity, and the six include
masking policies.

Measured on a debug build: 400 iterations pass with the fix, the slowest
shutdown() taking 1 ms; the unfixed build fails on the first iteration of all
5 runs with "shutdown() took 60000 ms".

Co-Authored-By: Claude Opus 5 <[email protected]>
The comment said which of the two orderings wins varies per pass. That is not
what the measurement shows: on a debug build the unfixed code stalled on the
very first iteration in all 25 samples taken, so on this machine the order is
in practice stable. The property the loop relies on is the weaker and correct
one, that neither ordering is guaranteed, which is why one pass is not a
reliable probe.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Reviewed cold against the code, then adjudicated. The src/ change was clean in both rounds; two real
problems in the regression test were found and fixed before publishing.

❌ The test could have passed on master by luck. Without the fix stopListsWritingThread holds no
lock, so the worker can arm its wait before the stop request is issued, and in that ordering even the
unfixed code shuts down promptly. A single pass was therefore not a reliable probe, and
Bugfix validation needs the test to fail on master. The insert-and-shutdown pair now runs twenty
times with a fatal assertion, so one lucky ordering is not enough and the unfixed build still pays
only one one-minute wait.

❌ The test passed even with list scheduling neutered. Checking that need_rebuild_lists.mark is
absent and users.list exists asserted a fact established before the code under test ran: the
constructor's recovery path already creates an empty users.list, and nothing scheduled means no
marker either. It now reopens the directory and resolves the inserted user, kept paired with the
marker check, since with the marker present the reopen would rebuild from the <id>.sql files and
resolve regardless. Verified in both directions: making scheduleWriteLists return immediately fails
this assertion and no other.

💡 The other join in this file, inside scheduleWriteLists, runs while holding mutex and is
unaffected. It can only join a worker that has already returned, because
lists_writing_thread_is_waiting is cleared by the worker under mutex, and the new predicate can
become true only from stopListsWritingThread.

💡 Noted, not fixed: these commit messages should have wrapped identifiers in inline code blocks per
the repository instructions. Correcting them would need an amend, which the same instructions forbid,
and a reword-only commit is noise.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [61af973]

Summary: ✅


AI Review

Summary

This PR fixes a lost wakeup in DiskAccessStorage: shutdown now latches the exit request under mutex and uses the predicate overload of wait_for, so clickhouse-local and clickhouse-server no longer wait out the one-minute batching timeout when the last access-entity operation started the lists-writing thread. The repeated reopen-based regression test matches that contract well, and I did not find any unresolved correctness, concurrency, or coverage issues in the current diff.

PR Metadata
  • 💡 Changelog category should be Bug Fix, not Improvement: this is a user-visible fix for long-standing stable-release misbehavior rather than a net-new behavior change.
  • 💡 Changelog entry is required for that category and the current text is already specific and user-readable; only the category needs changing.
  • 💡 Exact replacement: change - Improvement to - Bug Fix.
Final Verdict
  • Status: ✅ Approve
  • Minimum required actions: None for the code. Optionally switch the changelog category to Bug Fix so the metadata matches the actual change.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vitlibar, could you review this? stopListsWritingThread notified the background lists-writing thread while holding no lock and recording no state, so a stop request issued before that thread had armed its wait_for was lost and shutdown waited out the full one-minute batching timeout; the fix records the request in a mutex-guarded flag and gives the wait a predicate that reads it.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 61af97321 with master 9e058f845 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

9 translation units recompiled, 29 s compile time in total, 9 of them have a recent master baseline.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. label Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2174b39

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.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) job-level ERROR: the 9000 s wall-clock cap, at duration 9055 s, after the run reached test 12638 of 13502 with no failing test. The lane is un-batched, so the whole suite runs in one job #116209 (mine, open)
LLVM Coverage DROPPED at duration 0 - praktika's own cascade closure of the row above, attributed to it in the report's ext.notes, not an independent failure #116209 (mine, open)

This head carries no failing test. The suite was killed mid-run, so its per-test rows never reached
the database: a FAIL/ERROR count of 0 here is unmeasured rather than clean, against a
261,431-row control that proves the head is otherwise ingested.

CH Inc sync is success at this head, so it is deliberately not rowed.

Session id: cron:our-pr-ci-monitor:20260904-200000

@protomn

protomn commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

another occurance of this on #119167.
04902_access_entity_map_setting_round_trip killed at the 60 s cap, with clickhouse-local stuck after CREATE SETTINGS PROFILE ondisk SETTINGS http_response_headers = … and all threads parked in the lldb dump.

CI report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the report. It is the same mechanism this PR fixes, so it can keep happening until this lands.

CREATE SETTINGS PROFILE reaches scheduleWriteLists, which starts the background lists-writing thread; that thread then waits up to std::chrono::minutes(1) before writing the .list files. When clickhouse-local exits, shutdown() calls stopListsWritingThread(), which notifies while holding no lock and recording no state, so a stop request that arrives before the thread has armed its wait_for is lost, and the join() right after it waits out the full minute. The 60 s per-test cap fires first, which is the parked clickhouse-local in your lldb dump.

Your build cannot carry the fix: master still has the unpredicated wait (src/Access/DiskAccessStorage.cpp:354), and this PR is not merged, so every PR build races the same way.

In practice it is rare (CIDB, last 30 days: 6 failures against 117,394 OK), and 04902 passed on every other head of #119167, so a re-run should be green. Nothing is needed from your side; this PR only needs a review.

groeneai and others added 2 commits October 13, 2026 12:20
…rage-shutdown-stall

Resolve the conflict in `src/Access/tests/gtest_disk_access_storage.cpp` by keeping
both sides: the recovery tests added on master and the shutdown test of this branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The helper was added to the same test file on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Fix one-minute shutdown delay after writing an access entity to disk Avoid a one-minute shutdown delay after writing an access entity to disk Oct 13, 2026
@groeneai
groeneai requested a review from pufit October 13, 2026 12:40
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 13, 2026
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-rbac Authorization: roles, grants, quotas, row-level security, access checks. groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-improvement Pull request with some product improvements 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.

4 participants