Skip to content

Tolerate a concurrently removed mutation entry on a readonly shared directory - #119154

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:fix-loadmutations-readonly-shared-directory
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:fix-loadmutations-readonly-shared-directory

Conversation

@groeneai

@groeneai groeneai commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

A readonly MergeTree table over the directory of a live table (table_disk = 1 on a shared plain_rewritable disk) now attaches when the live table removes a mutation entry that no part of the readonly table still needs, and no longer writes to that directory while loading mutations.

Description

Related: #110939, #119304.

Not for changelog: enable_hard_links exists only on master (#110939 was reverted before 26.9 and relanded by #119304), so no release has mutation entries in a shared plain_rewritable directory.

With table_disk = 1, a readonly table over the same plain_rewritable endpoint shares the directory of the live table that writes it. The live table removes mutation_*.txt entries at any moment (KILL MUTATION, clearOldMutations), also between the readonly listing and its read. Since #119304 the CREATE/ATTACH then fails with FILE_DOESNT_EXIST and a retry hint.

This PR, on top of loadMutationEntry from #119304:

  • An entry proven removed is skipped when no active part of the readonly table is below its version: it supplies no on-the-fly conversion to any loaded part. Otherwise the Revert "Revert "Support real hard links for plain_rewritable metadata."" #119304 error stands, because a part below it needs its commands.
  • This also covers a read failure that is not a DB::Exception (Azure rethrows the SDK's own).
  • An empty unique id (a file without a backing object) is not taken as proof of removal, so the original read failure stays.
  • loadMutations no longer writes to a directory the table does not own: the CSN is kept in memory, an uncommitted entry is ignored rather than removed, and tmp_mutation_* is left alone. Only the temporary-entry removal is reachable here (a plain-rewritable disk does not support transactions); the other two are defensive.

Test 05161 runs on a local and on an Azure disk. On master the first arm fails at ATTACH with Code: 107 for a finished entry; with the change it passes. The second arm keeps the #119304 error for an entry a part still needs. Without the std::exception catch the Azure arm fails with Code: 1001. Same on s3_plain_rewritable over MinIO; the stress check for lost S3 keys finds nothing. 05227 passes.


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

…irectory

`table_disk = 1` leaves `relative_data_path` empty, so a MergeTree table's data
directory is the root of its disk. A readonly table over the same
plain_rewritable endpoint therefore shares one directory with the live table that
writes it. That is a supported topology, not a misconfiguration:
`DiskSelector::recordDisk` permits a second plain-rewritable disk on an
overlapping prefix only when that disk is readonly or write-once,
`MergeTreeData::loadDataParts` arms a background part refresh when all disks are
readonly, `SYSTEM RESTART DISK` exists to reload such a table, and six stateless
tests use it.

`loadMutations()` was never adapted to it and still assumes it exclusively owns a
quiescent directory. It lists the directory and then reads every `mutation_*.txt`
the listing returned. The owning table removes its own entries at arbitrary
moments, through `killMutation` (from `KILL MUTATION` and from
`MergeTreeTransaction::rollback`) and through `clearOldMutations`, so a removal
landing between the listing and the read makes the read fail and takes the
readonly table's `CREATE`/`ATTACH` down with it. Seen on master as
`Code: 499 ... The specified key does not exist ... __root/mutation_5.txt` raised
by `CREATE TABLE reader`, 63 ms after the stress harness's random `KILL MUTATION`
deleted that object.

An unreadable entry is now ignored only when all three of these hold, and the
read failure stands otherwise:

  * the disk is readonly, so this table does not own the directory,
  * the object is proven absent at the backend,
  * no active part of this table is still below the mutation version.

The third condition is what keeps the fix from trading an error for wrong
results. The owning table decides that a mutation is finished from its own active
parts, while this table cached its part set earlier, so a removed entry can still
be owed as an on-the-fly alter conversion to an older part here; ignoring it
would serve pre-mutation column data.

The absence probe has to be `checkUniqueId(getUniqueId(...))` rather than
`existsFile`: this disk's cached metadata is not invalidated when another disk
instance over the same endpoint removes an object, and it was measured still
reporting the removed entry as present while the backend reported it gone. A probe
that cannot answer counts as "not proven absent": an empty unique id means the file
has no backing object, which a present file can legitimately have when a metadata
storage inlines small content or the file has zero blobs, so it must not be read as
absence. The decision is taken entirely by the three conditions and never by the
exception type, which also covers backends whose read failure is not a
`DB::Exception`.
The tolerated exception is deliberately not logged verbatim, because emitting its
text would reproduce the object storage "key does not exist" message that log
checks read as a server-side error.

The same function also wrote to a disk it does not own. It persisted a CSN for a
committed transactional mutation and removed uncommitted and temporary entries,
and all three throw on `ReadOnlyDiskWrapper`, so a readonly table failed to
attach over a directory holding such a file even with no race at all. Those
writes are now skipped when the disk is readonly, with the CSN still assigned in
memory so `system.mutations` reports it. The guard stays at this call site rather
than inside `MergeTreeMutationEntry::writeCSN`, which is also the persistence
step of transaction commit through `setMutationCSN`, where silently skipping it
would hide a durability failure.

One residual is accepted deliberately: a mutation cancelled above the readonly
table's minimum part version is genuinely not owed to it, but a file that is
simply gone cannot be told apart from a finished one, so that case still raises.

Co-Authored-By: Claude Opus 5 <[email protected]>
@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 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds; 2 findings agreed and fixed before publishing)

Fixed in round 2:

  • object_id.empty() was read as proof that the object is absent. It only means "no backing
    object", which a present file can legitimately have (inline content, zero blobs), so a present
    but unreadable entry could be skipped. Now !object_id.empty() && !checkUniqueId(object_id), a
    no-op for plain_rewritable, where getStorageObjects returns one object or throws.
  • The new test's negative arm could pass without testing anything: grep -q "$unapplied" with an
    empty id is an empty pattern. It now requires ATTACH to have failed and the id to be non-empty.

Coverage, stated plainly: removing the tolerance, removing the minimum-part-version guard, or
replacing the backend probe with existsFile each redden a shipped arm. Removing the readonly gate
is killed by no test: a second writable plain-rewritable disk on an overlapping prefix is refused
outright (DiskSelector.cpp:52-56), so that gate preserves behaviour rather than guarding a
reachable race, and its failing direction would need a hand-placed corrupt file.

For whoever judges backporting: the race half needs a mutation_*.txt on a shared
plain_rewritable directory, which only became possible with enable_hard_links (#110939, master
only). The write-suppression half needs neither a race nor hard links.

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

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @Michicosun, could you review this? StorageMergeTree::loadMutations lists a directory and then reads every mutation_*.txt the listing returned, so a readonly table sharing a live table's directory (table_disk = 1 over the same plain_rewritable endpoint) fails its CREATE/ATTACH when the owner removes one of its own entries in between. An unreadable entry is now ignored only when the disk is readonly, the object is proven absent at the backend, and no active part of this table is below the mutation version, and the three writes this function made to a disk it does not own are skipped.

@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7bbdde4]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 1/6) FAIL Performance dashboard
and_function #0 slower query history
generate_random_json #1 unstable query history
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
iceberg_suite_s3_rw_features #9 unstable query history
Performance Comparison (arm_release, master_head, 3/6) FAIL Performance dashboard
encrypt_decrypt #5 unstable query history
Performance Comparison (arm_release, master_head, 4/6) FAIL Performance dashboard
aggregation_two_level_bucket_merge #3 unstable query history
iceberg_suite_local_rw_features #5 unstable query history
iceberg_suite_local_rw_features #9 unstable query history
merge_tree_insert #13 unstable query history
Performance Comparison (arm_release, master_head, 5/6) FAIL Performance dashboard
dynamic_field_serialization_cache #0 unstable query history
min_max_index_with_cast #0 unstable query history
Performance Comparison (arm_release, master_head, 6/6) FAIL Performance dashboard
Check Results FAIL

AI Review

Summary

This PR lets a readonly MergeTree table attach when the owner has removed a mutation entry and no loaded active part needs its commands. It also avoids writes to foreign mutation files during loading and handles Azure SDK exceptions. No actionable findings remain after reviewing the current code, diff, and all prior discussion. On head 7bbdde484fafb1fabe9cdcbbe556fd74897d9b91, all 50 targeted runs of 05161_readonly_table_concurrently_removed_mutation passed, covering local and Azure disks and both the skip and refusal cases. Targeted CI report.

Final Verdict

Status: ✅ Approve. No changes requested and no new inline findings to post.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 10, 2026
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Sep 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 24d531a

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
Stress test (amd_msan) / S3_ERROR No such key thrown The signature this PR targets reproduces WITH the change present, on a different mutation number (__root/mutation_15.txt, read side: CREATE TABLE reader ... type = s3_plain_rewritable, enable_hard_links). Fix presence was probed per build rather than per branch: the failing binary is 1c96cd565a2dc08ae4ac06ad5f3b51d2c32a035f = Merge 24d531ae into 59991a41, so the change was in it. The same signature also hit three unrelated PRs within one hour (#117922 arm_release, #115547 arm_msan, #117375 arm_debug), so the underlying defect is trunk-wide and was not introduced here. a fix task is moved to pending (the change in this PR is incomplete and I am extending it to cover the read-side residual)
Fast test (arm_darwin) / 05076_error_trace_file_offsets Test-oracle defect on Darwin, unrelated to this PR: the oracle expects a frame above the last symbol end, which Mach-O address resolution does not produce. It reddened 76 runs across 75 distinct PRs in the same window, 0 on the master line. #119145 (mine, merged 2026-09-10 10:27Z); this head predates that merge, so I will pick it up with a master merge on the next push of this branch instead of spending a separate CI round on it now

Mergeable Check and PR are aggregators of the two rows above and have no independent cause.

Session id: cron:our-pr-ci-monitor:20260910-120221

@groeneai

Copy link
Copy Markdown
Collaborator Author

This does not cover a killed mutation that had not been applied yet, and I do not think a reader-side rule can

Measured on this head: the signature this PR targets fired again in Stress test (amd_msan), with the fix
present in that build (the job binary reports 1c96cd565a2dc08ae4ac06ad5f3b51d2c32a035f, which is
Merge 24d531aefd3c into 59991a415be6).

What refuses is the third condition in loadMutations. The reader's active parts were all_1_5_1_12,
all_6_6_0_12, all_7_7_0_15, all_8_8_0_15, all_9_9_0_15, so its minimum part version was 12 while
the removed entry was mutation_15.txt. The first two conditions held: the disk is readonly, and the
backend probe ran and found the object gone. In that job the stress harness had rewritten key % 2 into
2 % key, so mutations 13 to 15 failed permanently on all_6_6_0_12 and were then killed. That state is
one a readonly reader can never attach over, because the entry does not come back and the part never rises
above version 12.

Dropping the condition is not safe, and I could not find a reader-side predicate that is:

  1. An entry can equally be gone because the owner finished it on every part and clearOldMutations removed
    it, while the reader's part list, loaded moments earlier, still holds the pre-mutation part. Skipping
    then serves pre-mutation rows for a part the owner has already replaced.
  2. Reloading the namespace (dropCache) and checking each below-version part against an
    ActiveDataPartSet built from it handles case 1, but not the mixed case: KILL MUTATION does not roll
    back the parts it did finish, so one part can be advanced while another is left behind.
  3. Even the per-part check is not airtight. killMutation unlinks the entry after cancellation has only
    set is_cancelled on the MergeList entry, and MutatePlainMergeTreeTask does not re-read that flag
    between mutate_task->execute() and renameTempPartAndReplaceUnlocked plus transaction.commit, so a
    task that passed its last check still commits the covering part after the unlink. That is the same
    commit-boundary shape as the REPLACE PARTITION window fixed in 91e9ec0fe31ed.

Options as I see them, and the tradeoff is yours:

  • keep refusing, as this PR does, and accept that a readonly reader cannot attach after such a kill;
  • order the unlink after the mutate task's commit barrier, which makes the per-part reconciliation in
    loadMutations sound; I am happy to implement both;
  • record a cancellation durably in the plain rewritable layout, so a reader can distinguish an unlink from
    a missing object;
  • give a readonly table a mutation refresh path, so any staleness it inherits is repairable;
  • stop the stress disruptor from killing mutations on a table whose directory another table shares
    readonly.

Cost of leaving it as is: 15 Stress jobs in the 13 hours after #110939 merged, spread over 14 different
pull requests and one master run, and each one reds the whole job through the
S3_ERROR No such key thrown check.

My preference is the second option. Which would you prefer?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Blocked on the hard links revert; I am not making CI green by weakening the test

#119276 reverted #110939, so this PR's base has no enable_hard_links, and
DiskObjectStorage::supportsHardLinks() is now false for plain_rewritable
(MetadataStorageFromPlainRewritableObjectStorage::isPlain() is true).
MergeTreeData::checkMutationIsPossible therefore rejects the fixture's ALTER TABLE writer UPDATE,
which is the single red at this head: Fast test / 05161_readonly_table_concurrently_removed_mutation,
Code: 344 ... Mutations are not supported for immutable disk '05161_writer_...' (SUPPORT_IS_DISABLED),
with Finish Workflow as its cascade. The same test was OK in Fast test on 24d531ae, whose base
still had the feature.

I am not touching the branch for it. Tagging the test out of that configuration, or rebuilding the
fixture on a mutable disk, would either skip everywhere or stop testing the shared directory at all,
and the path is unreachable on this base anyway: a readonly disk only shares a table directory under
plain-family metadata, and plain-family disks now reject every mutation.

#119304 relands the feature as a plain revert of the revert (one commit, exactly inverse to #119276),
so the failure this PR targets comes back with it. When that lands I will merge master and re-run CI
with this diff unchanged. If the reland should carry this change instead of a separate pull request,
say so and I will close this one.

alexey-milovidov added a commit that referenced this pull request Sep 18, 2026
…while a readonly table loaded

A readonly `MergeTree` table over the directory of a live table (`table_disk`
on the same `plain_rewritable` endpoint) does not own the `mutation_*.txt`
entries there: the live table removes one at any moment (`KILL MUTATION`,
`clearOldMutations`), also between the listing and the read in
`loadMutations`. The read then failed with a raw `S3_ERROR` (`The specified
key does not exist`), which is what reverted #110939: the stress test kills
random mutations and treats every such error as a bug, see
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=3b3489bfd27660683f874666359fc92f58ca46b8&name_0=MasterCI&name_1=Stress%20test%20%28amd_debug%29

The table still cannot load without the entry - a part below its version
would miss the commands, and no reader-side rule can tell a killed mutation
from a finished one (see the analysis in #119154) - so the load still fails,
but with `FILE_DOESNT_EXIST` and the reason: the entry was removed
concurrently, and the attach can be retried after `SYSTEM DROP DISK METADATA
CACHE` reloads the metadata of the readonly disk, which still lists the entry.
The check probes the backend, because the cached metadata of the disk is
exactly what is stale. Only a readonly disk takes this path.

Related: #119154

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Resolve the conflict with ClickHouse#119304 in `loadMutations` as agreed there:

- keep the three writes this branch skips on a readonly disk (CSN kept
  in memory, an uncommitted entry ignored instead of removed,
  `tmp_mutation_*` left alone);
- drop this branch's own backend probe, and let `loadMutationEntry`
  return nothing for an entry the owner removed when the caller allows
  it; the caller allows it only when no active part of the table is
  below the entry's version, otherwise `FILE_DOESNT_EXIST` from
  ClickHouse#119304 is thrown as before;
- an empty unique id is not taken as proof that the entry is gone (a
  file without a backing object, e.g. with inline content), so the
  original read failure stays in force.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A SQL-defined local disk must now live inside `custom_local_disks_base_directory`
(5b604cb), so the test uses `CLICKHOUSE_DISKS_FILES`, as 04318 does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master with #119304 and resolved loadMutations as agreed in #119304 (comment): the three readonly write-skips stay, loadMutationEntry returns nothing for a removed entry when no active part is below its version (otherwise its FILE_DOESNT_EXIST stands), and an empty unique id no longer counts as proof of removal.

One change from that comment: 05161 still drives the removal through the readonly disk's cached listing rather than storage_merge_tree_load_mutations_pause_before_read. That failpoint pauses loadMutations of every MergeTree table on the server, so the test would need no-parallel; the cached listing gives the same ordering within the test.

The category is now Not for changelog, since enable_hard_links is not in any release.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 5, 2026
Comment thread src/Storages/StorageMergeTree.cpp Resolved
groeneai and others added 2 commits October 5, 2026 23:24
`loadMutationEntry` caught only `DB::Exception`, but the Azure read path
rethrows the SDK's `Azure::Storage::StorageException` (404 "The specified
blob does not exist") once the download fails, so on an Azure
`plain_rewritable` readonly disk a mutation entry removed by the owner was
neither skipped nor reported: `ATTACH` failed with `Code: 1001`.

Catch `std::exception` instead. The reason is taken from `what()`, which
for a `DB::Exception` is `message()`, so the rethrown `FILE_DOESNT_EXIST`
text still carries no `Code: 499.` prefix for the stress log checks.

05161 now runs its scenario on a local and on an Azure disk, and its
needed-entry arm also requires `FILE_DOESNT_EXIST`. On Azurite,
the previous head fails the Azure arm 3/3 (`Code: 1001` on the finished
entry, and the needed entry is not named), while the local arm passes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Storages/StorageMergeTree.cpp

This branch has not been deployed

No deployments
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-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants