Skip to content

Refresh statistics cache for read-only MergeTree tables - #119559

Merged
alexey-milovidov merged 49 commits into
ClickHouse:masterfrom
rorylshanks:fix/readonly-statistics-cache
Sep 24, 2026
Merged

alexey-milovidov merged 49 commits into
ClickHouse:masterfrom
rorylshanks:fix/readonly-statistics-cache

Conversation

@rorylshanks

@rorylshanks rorylshanks commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Read-only MergeTree tables skip the task that refreshes the statistics cache. Queries then load statistics repeatedly. Start this task for read-only tables when refresh_statistics_interval is enabled.

Keep statistics refresh separate from background writers. Read-only tables reject new data changes and suppress new background scheduling; already scheduled merges, mutations and moves may finish. Cleanup waits for its active iteration to finish. Making the table writable restarts workers that were not started on read-only attachment.

If a settings-only metadata write fails, restore the old settings and in-memory metadata before propagating the exception. Functional regressions cover statistics refresh, read-only attachment and toggling, cleanup, outdated part loading, and failed read-only transitions in both directions.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Refresh the statistics cache for read-only MergeTree tables.


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

Version info

  • Merged into: 26.10.1.564-master (included in 26.10 and later)

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 11, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reasonable. Thank you!

@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e0cc351]

Summary: ✅


AI Review

Summary

This PR now does two things: it starts the statistics refresh and streaming-enrichment background work for read-only MergeTree tables, and it hardens table_readonly toggles so background workers, outdated-part loading, and foreground mutating entrypoints stay consistent across commit, rollback, and restart/attach paths. After reading the current diff and every existing review thread/reply, I do not see any remaining correctness, safety, or concurrency issue on the current HEAD (e0cc3518f39f3240436a8451819a77fb04a3d152).

Missing context / blind spots
  • ⚠️ I did not rerun the new read-only regression suite locally. Style check and Fast test are green on the current head, but the broader CI matrix is still pending, so this verdict is based on source inspection plus the focused regression coverage added in the PR.
Final Verdict

✅ No new findings on the current HEAD.

LLVM Coverage Report

Measured on commit e0cc351.

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: 270/293 (92.15%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 12, 2026
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

See the job log for details.

Clarify that read-only tables still refresh the in-memory statistics cache and document `refresh_statistics_interval = 0` for disabling that task.

Related: ClickHouse#119559 (comment)
Comment thread src/Storages/StorageMergeTree.cpp Resolved
A table attached while `table_readonly = 1` starts no background workers at
all: `StorageMergeTree::startup` skips `cleanup_thread`, both background job
assignees, background moves, and the outdated/unexpected part loading task.
`MergeTreeData::changeSettings` only restarted `startStatisticsCache`, so after
`ALTER TABLE ... MODIFY SETTING table_readonly = 0` inserts worked again while
merges, mutations, TTL, moves, and empty-part cleanup stayed dead until a
server restart - `SYSTEM START MERGES` / `SYSTEM START MOVES` only `trigger`
assignees whose holders were never created.

Extract the writable-startup worker set into `StorageMergeTree::startBackgroundWorkers`
and call it again on the `1 -> 0` transition of `table_readonly`, together with
the same one-off `clearEmptyParts` / `clearOldTemporaryDirectories` that a
writable startup performs. `isTableReadonly` stays true for a static storage,
so a static storage never starts them.

Outdated (inactive) parts of a table attached read-only are not enumerated at
load time, so they are still only cleaned up after a restart; the setting's
documentation now says so instead of promising a full restoration.

The new test proves a background mutation - which only `background_operations_assignee`
can execute - completes after the toggle. Verified against a control binary
without the fix, where the mutation never runs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
Comment thread src/Storages/StorageMergeTree.cpp Resolved
Wait for active cleanup and keep it stopped until the table becomes writable.
Document that other operations already in progress can finish.
@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 13, 2026
Comment thread src/Storages/StorageMergeTree.cpp Resolved
Check the cleanup action lock before the writable transition performs
one-off cleanup. Preserve stopped cleanup while restarting background
workers. Add a regression for a temporary directory surviving the toggle
and being removed after explicit `SYSTEM START CLEANUP`.

ClickHouse#119559 (comment)

ClickHouse#119559
The stateless suite cannot modify server storage. Exercise the
`table_readonly` toggle in the existing cleanup integration suite, with a
controlled local disk, and retain both stopped and resumed cleanup checks.

Validation: focused Docker integration test, Python syntax, Ruff, and
`server_data_manipulation_in_stateless_tests` pass locally.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119559&sha=befce6be5d4c5520f8c46a11240d3785ab161281&name_0=PR&name_1=Style%20check
ClickHouse#119559
Comment thread src/Storages/StorageMergeTree.cpp Resolved
`table_readonly = 0` is already committed when cleanup runs. Start the
background workers before cleanup so a filesystem exception still
propagates without leaving a writable table unable to run mutations.

Add a regression using a temporary-directory symlink loop. The cleanup
exception occurs both before and after the change; only the fixed build
completes the subsequent mutation. Existing read-only cache, outdated-part,
and live-cleanup checks also pass. The exact source compiles; runtime
checks use the changed code with compatible existing build dependencies.

ClickHouse#119559 (comment)
Stateless tests may run against remote or encrypted disks and cannot
modify server-side data paths. Move the symlink-loop reproducer into the
existing cleanup integration suite, which controls the server filesystem.

The integration case passes locally (1 test in 13.36 seconds), preserving
the cleanup exception and verifying that the mutation worker resumes.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119559&sha=b839eeb2c0b371d685ff426db77b1fbe86846797&name_0=PR&name_1=Style%20check
ClickHouse#119559
Comment thread src/Storages/StorageMergeTree.cpp Resolved
Use the live-cleanup prefixes after starting background workers. Active part removal owns `delete_tmp_` directories; the recovery sweep must not remove them.

The new integration regression fails before this change and passes afterward. All four cleanup integration tests pass, including worker recovery after a cleanup exception.

Related: ClickHouse#119559 (comment)
Comment thread src/Storages/StorageMergeTree.cpp Resolved
Stopping cleanup alone leaves queued and active merges, mutations and moves
in the executors. Finish the existing background assignees before returning
from the read-only `ALTER`. The existing writable transition starts them again.

Add a functional test that pauses a real background mutation, waits for the
read-only transition to enter executor cancellation, then checks cancellation
and resumed mutation processing after restoring writability. Use existing
failpoints; isolation is required because they affect executors server-wide.

The changed translation unit passes syntax validation. On an unfixed CI debug
binary the test reaches the mutation pause but times out waiting for the drain
path. Full execution of the patched server remains for CI.

ClickHouse#119559 (comment)
Comment thread src/Storages/StorageMergeTree.cpp Resolved
Comment thread src/Storages/StorageMergeTree.cpp Resolved
alexey-milovidov and others added 2 commits September 20, 2026 13:39
# Conflicts:
#	src/Storages/MergeTree/BackgroundJobsAssignee.cpp
#	src/Storages/MergeTree/MergeTreeData.cpp
…y` value

`ALTER TABLE ... MODIFY SETTING table_readonly = 0` publishes the new settings in
memory through `changeSettings` before `alterTable` makes them durable, and it only
holds `alter_lock`, which does not serialize with the `lockForShare` that the write
paths take. The background workers were already fenced off that window by
`background_workers_enabled`, but foreground queries were not: a concurrent `INSERT`,
mutation, `TRUNCATE`, `MOVE PARTITION TO TABLE` or `REPLACE PARTITION` could pass
`assertNotReadonly` on the transient `table_readonly = 0` and modify a table whose
failed commit restores `table_readonly = 1`.

`StorageMergeTree::readonly_commit_in_flight` is now set for the whole settings commit
of a read-only table, and `isTableReadonly` reports the durable value while it is set.
The `ALTER` itself, which has to know what the transition is, uses the new
`isReadonlySettingSet` where it means the value currently visible in memory.

The same flag closes the cross-table partition case: `MOVE PARTITION TO TABLE` and
`REPLACE PARTITION FROM` call `waitForOutdatedPartsToBeLoaded` on the other table
without holding its `alter_lock`. That wait must keep returning at once in the window,
because nothing is loading while the workers are disabled, so instead the partition
command itself is rejected: `MergeTreeData::alterPartition` consults the new virtual
`isReadonlyCommitInFlight`, and `movePartitionToTable` already asserts on the
destination.

`loadUnexpectedDataParts` mirrors the suspension that `loadOutdatedDataParts` got in
`b9969438`: the loop re-checks the gate before handing out each part, every queued load
re-checks it before touching the disk, a part already loaded by a suspended earlier run
is skipped instead of being asserted on, and the task re-arms itself while the table
still looks writable. Unexpected parts exist only for `ReplicatedMergeTree`, which never
disables its workers, so this is defensive rather than reachable today.

New test `05233_readonly_toggle_window_rejects_writes` pauses the 1 -> 0 toggle right
before the commit and checks the two queries that do not take the paused table's
`alter_lock`: an `INSERT` and a `MOVE PARTITION TO TABLE` from another table. A control
binary with the guard compiled out inserts the row and moves the partition onto the
durably read-only table (13 rows, source emptied); with the guard both are rejected.

The merge of `master` in the previous commit also carried the `alterPartition` and
`loadUnexpectedDataParts` hunks above. Conflicts resolved there:
`BackgroundJobsAssignee` keeps this branch's all-or-nothing `start` while adopting
master's `storage_id_mutex` / `getStorageID` (the storage id is read before
`holder_mutex` so the two locks are never nested), and `loadOutdatedDataParts` keeps
this branch's `StopReason` suspension on top of master's retryable-error requeue, with
`requeue_failed_parts` moved to the single tail that already waits for the pool outside
`outdated_data_parts_mutex`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed 6f8184d8d862: master merged (the branch was CONFLICTING) plus the three findings of the AI Review on 78e88fc3 addressed. Details are in the thread replies; the short version:

  • Blocker, foreground table_readonly window — real. StorageMergeTree::readonly_commit_in_flight keeps isTableReadonly on the durable value for the whole settings commit of a read-only table, so INSERT / mutation / TRUNCATE / partition commands are rejected until the commit succeeds. Control-verified: without the guard an INSERT lands 3 rows on the durably read-only table.
  • Blocker, cross-table waitForOutdatedPartsToBeLoaded — real, fixed at the partition command rather than at the wait (the wait must keep returning, nothing is loading while the workers are disabled). MergeTreeData::alterPartition consults the new virtual isReadonlyCommitInFlight; MOVE PARTITION TO TABLE is rejected by the destination's assertNotReadonly. Control-verified: without it the partition is moved onto the read-only destination.
  • Major, loadUnexpectedDataParts — mirrored the loadOutdatedDataParts suspension, as defence in depth. It is not reachable today: a plain MergeTree passes no expected parts and so never has unexpected parts, and ReplicatedMergeTree does not override areBackgroundWorkersEnabled.

New test 05233_readonly_toggle_window_rejects_writes. 18/18 read-only tests pass locally on the merged binary; 05227/05228, master's new outdated-parts retryable-error tests that the merge brought in, pass too.

Merge conflicts resolved: BackgroundJobsAssignee keeps this branch's all-or-nothing start on top of master's storage_id_mutex / getStorageID (the storage id is read before holder_mutex, so the two locks are never nested), and loadOutdatedDataParts keeps this branch's StopReason suspension on top of master's retryable-error requeue.

The two reds on 78e88fc3 were both unrelated:

alexey-milovidov and others added 2 commits September 20, 2026 19:31
A successful `table_readonly` 1 -> 0 `ALTER` committed the setting before it
restored the background workers: `readonly_commit_in_flight` was cleared when
the settings branch of `StorageMergeTree::alter` exited, while
`enableBackgroundWorkers` and `startOutdatedAndUnexpectedDataPartsLoadingTask`
only run in the post-commit tail at the end of the method.

In that gap the table is durably writable, so `assertNotReadonly` and
`MergeTreeData::alterPartition` no longer reject a command, yet
`waitForOutdatedPartsToBeLoaded` still takes its `!areBackgroundWorkersEnabled`
fast path, because nothing is loading while the workers are disabled. A
`MOVE PARTITION ... TO TABLE` into the table, which checks the destination
without taking its `alter_lock` and therefore does not simply block on the
running `ALTER`, could run there against a table whose outdated parts were
never loaded, so those parts are skipped and reappear later.

The flag now lives for the whole `alter` call and is cleared by the tail, right
after the workers are enabled and the part loaders are rescheduled, or by a
scope guard on any path that does not reach the tail. The table therefore
accepts writes again only once the statement returned.

New `PAUSEABLE_ONCE` failpoint `mt_alter_readonly_pause_after_metadata_commit`
pauses the toggle exactly in that gap, and test
`05234_readonly_post_commit_window_rejects_partition_moves` asserts that the
cross-table move is still rejected there. Control-verified with a binary that
clears the flag at the old point: the partition moves onto the table inside the
window.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed d550a7c72006, addressing the single remaining blocker of the AI Review on f06f9851 (the post-commit half of the waitForOutdatedPartsToBeLoaded thread).

The finding was real. On a successful table_readonly 1 -> 0 toggle, readonly_commit_in_flight was cleared when the settings branch of StorageMergeTree::alter exited, while the workers are only re-enabled and the part loaders only rescheduled in the post-commit tail at the end of the method. In that gap the table is durably writable, so nothing rejects a command any more, yet the outdated-parts wait still returns immediately because nothing is loading while the workers are disabled.

Fix: the flag now spans the whole alter call and is cleared by the tail, right after enableBackgroundWorkers and startOutdatedAndUnexpectedDataPartsLoadingTask, with a SCOPE_EXIT covering every path that does not reach the tail. The table accepts writes again only once the statement returned — now documented on the setting.

The only command that can actually race in that gap is the cross-table MOVE PARTITION ... TO TABLE, since it checks the destination without taking its alter_lock; everything else blocks on the ALTER's lock. New PAUSEABLE_ONCE failpoint mt_alter_readonly_pause_after_metadata_commit plus test 05234_readonly_post_commit_window_rejects_partition_moves, control-verified against a binary that clears the flag at the old point (the partition moves in: destination 11 rows, source 1).

15/15 read-only tests pass locally on the final binary. CI on f06f9851 was fully green (124 passed, 0 failed), and the branch is 179 commits behind master with no conflicts, so no merge was needed.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed b5a1b7911f68: master merged (the branch was 423 commits behind; the merge was conflict-free). No code changes were needed — the AI Review on d550a7c7 returned ✅ No new findings on the current HEAD, and there are no unresolved review threads.

The only red on d550a7c7 was Performance Comparison (arm_release, master_head, 1/6), and it is noise, not a regression of this PR.

  • The failing query is set_index #0 — SELECT count() FROM test_in WHERE a IN (SELECT rand(1) FROM numbers(200000)), reported at +38.6% against its own +38.6% threshold. This PR touches StorageMergeTree::alter, the BackgroundJobsAssignee lifecycle and the outdated-parts loaders; nothing on that query's execution path. The only per-query cost it could add is a relaxed atomic load in scheduleDataProcessingJob, which runs once per background job, not per row.

  • set_index #0 is one of the noisiest queries in the suite on ARM. Over the last 30 days it exceeded its own threshold in 418 of 875 master-vs-master runs (47.8%), with p05 = -33.8%, p95 = +45.7% and a maximum of +90.2% — so the observed +38.6% sits inside the ordinary master-vs-master spread:

    test runs (master vs master, aarch64) over threshold p05 p95 max
    set_index #0 875 418 (47.8%) -33.8% +45.7% +90.2%
    rand #0 877 188 (21.4%) -16.8% +19.0% +85.1%
    rand Repair subtree2 #1 868 190 (21.9%) -16.1% +19.7% +81.2%
    rand Repair subtree2 #2 885 256 (28.9%) -14.4% +16.3% +57.1%
    rand BaseDaemon: terminate on double SIGINT #3 889 270 (30.4%) -14.8% +16.8% +57.7%
    min_max_wide_integers Update Docker files for Docker Hub #13 632 158 (25.0%) -7.8% +6.9% +49.9%

    (default.query_metrics_v2 on play, pr_number = 0, metric = 'client_time', event_date >= today() - 30.)

  • The same run flagged five more slower queries on the other five shards — four of them rand #0..#3 plus min_max_wide_integers #13, all in the table above, and all of those shards still passed. The job itself carries the under-utilized CPU and disk-almost-full labels, which is the usual signature of a degraded runner rather than of a code change.

Re-verified locally on the merged binary: ninja clickhouse builds clean (0 warnings, 0 errors) and 17/17 read-only tests pass — 04321_table_readonly_background_merges, 05183, 05184, 05185, 05186, 05210, 05211, 05212, 05217, 05218, 05219, 05220, 05221, 05222, 05223, 05233, 05234.

…y` toggle windows

Review pointed out that `ALTER TABLE dst ATTACH/REPLACE PARTITION ... FROM src` waits for the
outdated parts of `src` before it locks `src`, and that the wait fast-paths while the workers of
`src` are disabled, so the command runs inside both windows of the 1 -> 0 toggle of `src`.

That is safe for the source, unlike for the destination: cloning reads only the active parts of
`src`, and their set is complete once `src` is attached, because the deferred outdated parts are
exactly the parts covered by an active one. A durably read-only source skips the wait in the same
way on master already, since it never creates the loading task.

Add `05235_readonly_toggle_window_source_of_attach_partition`, which runs the command inside the
pre-commit and the post-commit window of the source's toggle and checks that the destination gets
all rows, the source stays intact, and the toggle still loads the outdated parts of the source
afterwards. Document the reasoning next to the wait in `MergeTreeData::alterPartition`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed ebfc6ba3f7ab, addressing the single blocker of the AI Review on b5a1b791 (the source side of ATTACH / REPLACE PARTITION ... FROM during the source's table_readonly 1 -> 0 toggle).

The shape is reachable, but no data can be missed: the command clones only the active parts of the source, and that set is complete as soon as the source is attached, because the parts a read-only attach defers are exactly the ones covered by an active part. Loading them later adds inactive parts to the source and nothing else; the rows "reappearing" on the source is not possible since they were in the active parts all along. A durably read-only source already skips this wait on master in the same way.

Rather than reject reads from a table that is only being read, or close a fast path that would hang SYSTEM WAIT LOADING PARTS inside the window, the push adds the focused regression the review asked for: 05235_readonly_toggle_window_source_of_attach_partition toggles the source, pauses it once before the commit and once after the commit before the workers are back, runs ALTER TABLE dst ATTACH PARTITION ID 'all' FROM src inside each window, and checks that the destination gets all rows in one part, the source keeps its rows, and the toggle still loads the two outdated parts afterwards. The whole table_readonly toggle family (05183, 05184, 05185, 05217, 05218, 05233, 05235) passes locally on this head. The reasoning is recorded next to the source-side wait in MergeTreeData::alterPartition. Details are in the review thread.

alexey-milovidov and others added 2 commits September 22, 2026 09:22
…t of them

The `failpoints_disabled_in_tests` style rule (from ClickHouse#120809, now on `master`) requires every `SYSTEM ENABLE FAILPOINT` in a stateless test to have a matching `SYSTEM DISABLE FAILPOINT`. Eight tests of this branch enabled `ONCE` fail points that disarm themselves after firing and never disabled them explicitly; a paused `ALTER` also stayed parked if a test exited early.

The seven `.sh` tests now install a `trap cleanup EXIT` that disables every fail point they enable (a disable of an unarmed fail point is a no-op), and `05210_readonly_settings_rollback.sql` disables the throw fail point after each `ALTER` that is expected to fail.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119559&sha=ebfc6ba3f7ab9ecf56874e4c5a7dea2a39a78297&name_0=PR&name_1=Style%20check
PR: ClickHouse#119559

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed c298894e3c5f: master merged (381 commits, conflict-free) plus a fix for the only red on ebfc6ba3, the Style check.

The failpoints_disabled_in_tests rule from #120809 has landed on master since the last merge, and it flagged eight tests of this branch that enable a ONCE fail point and rely on it disarming itself after firing: 05210, 05211, 05217, 05218, 05221, 05222, 05225, 05233. The seven .sh tests now install a trap cleanup EXIT that disables every fail point they enable, which also releases a paused ALTER if a test exits early; 05210_readonly_settings_rollback.sql disables the throw fail point after each ALTER that is expected to fail. No change to the code under test.

Verified locally on the merged binary: the style rule passes suite-wide, ninja clickhouse builds with 0 warnings / 0 errors, and 19/19 read-only tests pass, including the eight touched ones and 05234/05235.

The one unresolved review thread (source side of ATTACH PARTITION FROM during the source's toggle) has my reply from 2026-09-22 with the covering test 05235, awaiting the bot's re-verdict.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
alexey-milovidov and others added 2 commits September 22, 2026 20:00
`StorageMergeTree::alter` cleared `background_workers_enabled` only after
`alterTable` had durably committed `table_readonly = 1`. The cleanup thread
and the asynchronous outdated and unexpected part loaders of a table that
started writable are gated by that flag alone, so a timer wake-up or a
queued load that started between the durable commit and the flag flip could
still run `clearOldTemporaryDirectories` / `clearEmptyParts` or load one
more part on a table that was already durably read-only, contradicting the
`table_readonly` contract (cleanup is stopped, no further part is loaded).

The workers are now disabled right after `changeSettings` publishes the
new value, before the commit, so nothing that starts after that point
touches the disk. A failed 0 -> 1 commit enables them again in the
rollback; `wakeupBackgroundWorkers` now also reschedules the part loaders,
because a loader that ran in the window saw the temporary
`table_readonly = 1` and did not re-arm itself. The 1 -> 0 tail calls the
same helper, so its separate `startOutdatedAndUnexpectedDataPartsLoadingTask`
call is gone.

New test `05238_readonly_toggle_disables_workers_before_commit` pauses the
outdated part loader of a freshly attached table and the toggle right
before its commit, releases the loader inside the window, and checks that
it loads nothing before and after the commit, that the parts load on the
toggle back, and that after a rolled back commit the loader resumes on its
own. Without the fix both windows load the two parts.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`05220`, `05224`, `05234`, and `05235` enable server-global pauseable fail
points but disabled them only on the success path. An early exit under
`set -e` left the fail point armed and, for the paused `ALTER` cases, the
background query parked, which could poison the next test on the shared
stateless server. They now install the same `trap cleanup EXIT` as `05217`
and `05233`, disabling every fail point they enable and reaping the
background `ALTER`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed 7a9e377355f4 (two commits on top of the author's master merge 3bb7eef0), addressing both findings of the AI Review on 3bb7eef0.

  • Blocker, 0 -> 1 post-commit window (StorageMergeTree.cpp): real. background_workers_enabled was cleared only after alterTable had durably committed table_readonly = 1, while the cleanup thread and both part loaders of a table that started writable gate on that flag alone. The workers are now disabled before the commit, right after changeSettings publishes the new value; the rollback of a failed commit enables them again and, through wakeupBackgroundWorkers, reschedules the part loaders too (a loader that ran inside the window saw the temporary table_readonly = 1 and does not re-arm itself). New regression test 05238_readonly_toggle_disables_workers_before_commit, proved with a control binary: without the fix both windows load the two outdated parts. The table_readonly doc states the new contract.
  • Major, unconditional fail point cleanup: 05220, 05224, 05234, 05235 now use the same trap cleanup EXIT as 05217 / 05233, disabling every fail point they enable and reaping a parked background ALTER.

Verified locally on the merged branch: ninja clickhouse builds with 0 warnings / 0 errors, the failpoints_disabled_in_tests style rule passes for the whole family, and all 24 read-only tests pass (04321, 05183, 05184, 05185, 05186, 05210, 05211, 05212, 05217, 05218, 05219, 05220, 05221, 05222, 05223, 05224, 05225, 05233, 05234, 05235, 05238, plus master's 05227_load_outdated_parts_retryable_error and 05228_load_outdated_parts_cancel_on_detach).

CI on 3bb7eef0 was still running with no red job when I pushed; the only failed check was CH Inc sync, whose Style check fails on settings_changes_history. This branch does not touch SettingsChangesHistory.cpp, so that failure comes from the private side of the sync and will be re-evaluated on the new head.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
…` returns

The `table_readonly` 1 -> 0 tail cleared `readonly_commit_in_flight` before the
one-off `clearEmptyParts` / `clearOldTemporaryDirectories` cleanup. `INSERT` does
not take the `alter_lock`, so a concurrent write could pass `assertNotReadonly`
while the statement was still running, contradicting the documented contract that
the table accepts writes again only once the statement returned. Leave clearing
to the scope guard, which runs when the method returns or unwinds. Background
workers do not consult the flag, so they are unaffected.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 24, 2026
Merged via the queue into ClickHouse:master with commit fb831a1 Sep 24, 2026
176 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 24, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 27, 2026
ClickHouse#119559 added `IMergeTreeCleanupThread::isCleanupCancelled`, which returns
`cleanup_blocker.isCancelled()` exactly like the `isCleanupBlocked` this PR
added, so drop ours and call the existing one from the empty-part skip.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default 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.

3 participants