Skip to content

Refuse a second writable table_disk table on one disk root - #124298

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:table-disk-single-writer
Oct 16, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:table-disk-single-writer

Conversation

@groeneai

@groeneai groeneai commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #98512

Changelog category (leave one):

  • Backward Incompatible Change

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

A writable disk with table_disk = true now holds the data of only one table: creating or attaching another table on the same path of the same storage, or on a path inside or above it, throws BAD_ARGUMENTS; tables over a read-only disk on that path are still allowed. Previously such tables returned each other's rows, lost inserts and deleted each other's files. A table dropped or detached without SYNC keeps its disk until its instance is gone. An ALTER can no longer change the disk of such a table. If existing metadata has two such writers, the table loaded second fails to load: before upgrading, recreate all but one of them over a read-only disk. Closes #98512.

Description

On 26.3.42.3 and 26.8.18.2, two tables with table_disk = true on one writable plain_rewritable disk return each other's rows and lose inserts; with two cache disks over one s3_plain_rewritable disk (#98512) reading the first table fails with CANNOT_READ_ALL_DATA.

Found as S3_ERROR No such key in Stress test (arm_release) on #124103 (report): the AST fuzzer cloned the 05137 table as dedup__fuzz_N on the same disk, the original's DROP deleted __root/format_version.txt between a clone's blob write and its metadata commit.

Change:

  • MergeTreeData: a writable table_disk table owns its disk root until the instance is destroyed.
  • ALTER cannot change the disk of a table_disk table: on master, RESET SETTING disk put it on the server's data directory, which DROP TABLE then deleted.
  • DatabaseCatalog: a dropped table is destroyed before DROP ... SYNC returns.
  • DatabaseOverlay (clickhouse-local's default database) forwards the detached-table check and wait, so DETACH t; ATTACH t works there.

With async_load_databases = 0, such existing metadata stops the server from starting.

Not covered: a config reload that makes a read-only disk over an owned root writable. The reload skips the check DiskSelector runs at startup; I can add it to the reload if wanted.

Validation: both new tests fail on master, pass with the fix; with the AST fuzzer on, 05137 left two dedup__fuzz_N writers on master, none with the fix.

Raw timed lines from the stress server log (clone `dedup__fuzz_4` = query 46b07e5e, the original's drop = thread 67164)
2026.10.06 04:02:08.181737 [ 116372 ] {dd8b9953-261b-4702-bdd3-a4c041fc1138} <Debug> executeQuery: (from [::1]:52786) (comment: 05137_table_disk_drop_deduplication_log.sh-test_1) (query 1, line 1) DROP TABLE dedup SYNC (stage: Complete)
2026.10.06 04:02:08.255950 [ 67164 ] {} <Information> test_1.dedup (60613701-1ecc-444e-a862-79b5aec3621f): dropAllData: remove format_version.txt, detached, moving and write ahead logs
2026.10.06 04:02:08.261992 [ 21085 ] {46b07e5e-9121-4054-852a-5007bc694d01} <Test> DiskObjectStorageTransaction: Writing blob for path format_version.txt, key 05137_table_disk_drop_deduplication_log_test_1/__root/format_version.txt, size 1
2026.10.06 04:02:08.309302 [ 67164 ] {} <Debug> deleteFileFromS3: Object with path 05137_table_disk_drop_deduplication_log_test_1/__root/format_version.txt was removed from S3
2026.10.06 04:02:08.310425 [ 21085 ] {46b07e5e-9121-4054-852a-5007bc694d01} <Test> MetadataStorageFromPlainObjectStorageWriteFileOperation: Creating metadata for a file 'format_version.txt', size: 1, blob key: '__root/format_version.txt'
2026.10.06 04:02:08.352658 [ 21085 ] {46b07e5e-9121-4054-852a-5007bc694d01} <Test> DatabaseAtomic (test_1): Counting attached table dedup__fuzz_4 to database test_1
2026.10.06 04:02:11.443691 [ 7278 ] {2d00798a-1987-443e-8338-86d0125a4925} <Error> executeQuery: Code: 499. DB::Exception: The specified key does not exist. This error happened for S3 disk: while reading key: 05137_table_disk_drop_deduplication_log_test_1/__ro

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

Version info

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

A table with `table_disk = true` keeps its parts and its root files
(`format_version.txt`, `detached/`, `deduplication_logs/`, mutation entries) at
the root of its disk, so two writable tables on one root overwrite and delete
each other's data (issue ClickHouse#98512), and the stress test's AST fuzzer clones of
such a table (`<name>__fuzz_N`, same disk) raced the original's `DROP` and left
a metadata entry whose object was gone (`S3_ERROR` No such key on
`__root/format_version.txt` in `Stress test (arm_release)`).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124103&sha=60474c44812b8fadcb983207ab8e87a4a1af41f5&name_0=PR&name_1=Stress%20test%20%28arm_release%29
PR: ClickHouse#124103

A writable `table_disk` table now owns the root of its disk (storage endpoint +
namespace + disk path; nested paths conflict) until the instance is destroyed;
another writable table on that root is refused with `BAD_ARGUMENTS`. Read-only
and write-once disks are not owners, so the one-writer/many-readers setup keeps
working.

The root is not released when `dropAllData` finishes: the rest of the drop
(`dropReplica`, removing `store/<uuid>` and the metadata) can still throw and
re-queue the table, and after a restart the dropped table is rebuilt from
`metadata_dropped` before the other tables are loaded, so a released root could
be taken by another table whose parts the retried drop would then delete.
`DatabaseCatalog` destroys the dropped storage before it notifies the
`DROP ... SYNC` waiters, so `DROP ... SYNC` followed by a `CREATE` on the same
disk works; the new `database_catalog_drop_finally_after_notify` failpoint
pauses the drop job right after that notification, so a test can check it. A
table dropped or detached without `SYNC` keeps the root until its instance is
gone, and the error says to retry after that (`SYNC` waits for it).

An `ALTER` cannot change the disk or the storage policy of a `table_disk`
table: the new disks would join the table without being owned, and
`RESET SETTING disk` moved the table onto the `default` disk with the server's
data directory as its data path, so a later `DROP TABLE` deleted that whole
directory.

The default database of `clickhouse-local` is a writable `Overlay` over an
`Atomic` database, which keeps a detached table instance until no query uses
it. `Overlay` did not forward `checkDetachedTableNotInUse` and
`waitDetachedTableNotInUse`, so an `ATTACH` did not first destroy the unused
detached instance and `DETACH ... SYNC` did not wait; with the ownership above
that refused `DETACH TABLE t; ATTACH TABLE t`. Both are now forwarded to every
member, as the server's `Atomic` database does.

Co-Authored-By: Claude Opus 5.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 Oct 6, 2026
@groeneai

groeneai commented Oct 6, 2026

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

Pre-publication review by an independent model (engine: codex) plus my own cold passes; rounds 1-6 (heads fb40f5aa3fd6, 865aa8c35478, 5c39ceb6be64, 0d0b3641f755, 131bd5758a0d, dc5642104a59).

Round 7 (e156982d40c0, test files only): my own pass, no further gate run. Bounce cap reached: published as is; the residual findings, noted and not blocking, are rows 15, 19 and 20.

# Sev Finding Verdict Action
1 ❌ Releasing the root at the end of dropAllData let a re-queued drop, rebuilt after a restart (loadMarkedAsDroppedTables runs before loadMetadata), re-acquire the root and delete a replacement table's parts AGREE Ownership now ends only when the instance is destroyed; the catalog destroys a dropped table before DROP ... SYNC returns; failpoint test
2 ⚠️ The test did not cover the root identity it promises (the #98512 cache shape, nested vs sibling encrypted paths) AGREE Added those arms to the test
3 ⚠️ A table dropped or detached without SYNC keeps the root, and the refusal suggested a read-only disk instead of SYNC AGREE Remedy now depends on the owner's state
4 💡 Empty path in the message for a bucket-root disk, no disk names AGREE Message names both disks
5 ⚠️ No test proved that DROP ... SYNC returns only after the dropped instance is destroyed AGREE Pause failpoint after the notify; the test goes red without the reset
6 ⚠️ The test covered only the nested direction, not the parent path or the write-once exemption AGREE Added the parent-path and write-once arms
7 ⚠️ A refused nested encrypted table has already created its directory in the owner's root DISAGREE The encrypted disk creates it when the disk is resolved (DiskEncrypted.cpp:381), for any CREATE naming it and on master too; part loading skips non-part names (MergeTreeData.cpp:3256). The description no longer says "before it writes anything"
8 💡 The dropped/detached remedy named a command that only helps the next operation AGREE The message says to retry after the drop/detach finishes
9 ⚠️ The test's DROP ... SYNC arm ran the drop in the foreground under a server-wide pause of the drop queue, so another table's drop reaching the pause first would hang it AGREE The drop runs in the background; the failpoint is disabled if it has not returned in time
10 💡 The setting description named only the same path, not nested or parent paths AGREE Description updated
11 ⚠️ An ALTER could still change the storage policy of a table_disk table (RESET SETTING disk, optionally with MODIFY SETTING storage_policy), adding a disk whose root the table does not own AGREE ALTER refuses any change of the disks of a table_disk table; test arm plus a control that unrelated MODIFY SETTING still works
12 ❌ The root identity is a snapshot, so a config reload that re-points an Azure disk at another endpoint lets another disk on that endpoint pass DISAGREE Re-pointing a live disk at another account already strands the table's loaded parts and metadata, independently of this change; for the same account under another URL it is the URL-aliasing false negative that exists without a reload (the identity is the one the server keeps immutable, AzureObjectStorage.h:166-171). A false negative is master behaviour, never a false refusal
13 💡 The detached-owner remedy says DETACH ... SYNC waits, which holds only for tables with a UUID AGREE The message says it applies in an Atomic database
14 ⚠️ The test's RESET SETTING disk arm ran on the shared server, so on a binary without the check the following DROP would delete the server's data directory instead of failing one test AGREE The arm runs in its own clickhouse-local process with its own --path
15 ⚠️ A config reload that makes a read-only disk over an owned root writable turns its table into a second writer AGREE, not changed here The reload skips the check DiskSelector::recordDisk runs at startup against two writable plain_rewritable disks on one prefix, for any table on them; offered in the description. Raised again in round 6, same disposition
16 💡 The setting description does not say that ALTER cannot change the disk AGREE Description updated
17 ⚠️ Both tests run under the Ordinary database variant, where drops do not go through the catalog queue: the pending arm fails and SYSTEM WAIT FAILPOINT would block AGREE Tagged no-ordinary-database, like the other tests on these failpoints
18 ⚠️ SYSTEM WAIT FAILPOINT returns for any paused drop, so another table's drop paused first let the first arm check the root before its own DROP had taken the table out of the database AGREE The arm also waits until the table is gone from system.tables
19 ⚠️ The same foreign pause in the SYNC arm could let a mutant without the reset pass DISAGREE It can only hide a mutant, never fail the test; the mutant is red when run alone
20 💡 CREATE OR REPLACE TABLE of such a table over its own writable disk is now refused, naming the temporary _tmp_replace_* table Noted The replacement is a second table on the root; without the check the replaced table's drop removes the parts both tables use

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Two table_disk tables on one local plain_rewritable disk: master (and official 26.3.42.3 / 26.8.18.2) return the other table's rows and lose an insert; #98512 verbatim on MinIO: reading t1 fails Code: 33 ... Too many marks. The new tests 05331_table_disk_single_writer and 05332_table_disk_drop_keeps_root_until_finished fail on master every run.
b Root cause explained? table_disk keeps the table at the disk root, so root files (format_version.txt, deduplication_logs/, mutation entries) have fixed paths, and nothing stopped a second writable table on that root. In the stress run the AST fuzzer cloned the 05137 table as dedup__fuzz_N on the same disk; the original's DROP removed __root/format_version.txt between a clone's blob write and its metadata commit, and the next CREATE read the missing object.
c Fix matches root cause? Yes. A writable table_disk table owns its root until the instance is destroyed; a second writable table is refused (a refused CREATE on a plain_rewritable disk leaves the object storage byte-identical). A dropped table is destroyed before DROP ... SYNC returns, so DROP ... SYNC then CREATE on the same disk works (0 of 50 refused). An ALTER that would change the table's disk or storage policy is refused too: on master RESET SETTING disk moved the table onto the default disk with the server's data directory as its data path, and a later DROP TABLE deleted that whole directory.
d Test intent preserved / new tests added? New tests 05331 (server and clickhouse-local legs, cache and encrypted wrappers, nested and parent paths, a write-once disk, drop and detach without SYNC) and 05332 (a drop paused after its data was removed keeps the root; the root is free when DROP ... SYNC returns). Both tests are tagged no-ordinary-database. 05137 is unchanged and passes 50/50, also with 8 parallel workers.
e Both directions demonstrated? Yes: 05331 and 05332 fail on master and pass with the fix. Mutations turn them red: either DatabaseOverlay override or the throw removed; releasing the root at the end of dropAllData (05332); comparing disk names instead of storage and path (cache arm); exact path equality instead of the prefix check (nested encrypted arm); a one-directional prefix check (parent arm); write-once disks as owners (write-once arm); no storage reset before the DROP ... SYNC notification (05332 SYNC arm); the ALTER check removed (05331 ALTER arm). With the AST fuzzer on, 05137 leaves two dedup__fuzz_N writers on master and none with the fix.
f Fix is general across code paths? One check in initializeDirectoriesAndFormatVersion, shared by StorageMergeTree and StorageReplicatedMergeTree. It covers every loading level (CREATE, ATTACH, RESTORE, startup, a dropped table rebuilt at startup), and an ALTER cannot add or swap the table's disks afterwards; an ALTER that keeps the disk (MODIFY SETTING old_parts_lifetime) still works. Ownership ends only in the destructor, so a re-queued drop (in-process or after a restart) never cleans a root another table took. DatabaseOverlay now forwards the detached-table guard. Atomic, Ordinary and Memory databases: DROP then CREATE on one root works, and UNDROP works.
g Fix generalizes across inputs (params/datatypes/wrappers)? cache wrappers over one disk are refused (same root); encrypted disks on sibling paths are allowed, nested and parent ones refused; read-only and write-once disks are never owners (two tables on one write-once plain disk work); table_readonly = 1 on a writable disk is an owner.
h Backward compatible? (maintainer-approved exception only) No setting or format change, and single-writer setups are unchanged. Existing metadata with two writers on one root (already corrupt) now fails to load the second table, with the remedy in the message. A table dropped or detached without SYNC keeps the root until its instance is gone; the message says to retry after that, and that SYNC waits for it (for a detached table, in an Atomic database). An ALTER that changes the disk or storage policy of a table_disk table is now refused.
i Invariants and contracts preserved? The registry changes under one mutex. Release removes only the instance's own entry, in ~MergeTreeData. The drop job destroys the storage before it erases the id and notifies the DROP ... SYNC waiters; a drop that throws keeps the instance and so the root. The overlay forwarding takes no lock of its own.

Session id: cron:clickhouse-impl-slot-7:20261006-183200

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e156982]

Summary: ✅


AI Review

Summary

This PR closes the main corruption path behind table_disk by making writable roots single-owner, refusing disk-changing ALTER on such tables, and making DROP ... SYNC wait until the dropped storage instance is actually destroyed. I did not find any new correctness or safety issues in the current diff, and the added regression coverage matches the stated scope.

Missing context / blind spots
  • ⚠️ The PR description explicitly leaves live SYSTEM RELOAD CONFIG transitions from read-only to writable on an overlapping object-storage root out of scope. If the single-writer invariant is meant to hold across config reloads too, that still needs a follow-up in the disk-reload path.
Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit e156982.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 72/75 (96.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-backward-incompatible Pull request with backwards incompatible changes comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Oct 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e156982d4 with master 28e35c5af (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of eb03aea3a; 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.

Object file sizes

8 object files changed (+43.96 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeData.cpp.o 4.18 MiB 4.22 MiB +40.47 KiB (+0.94%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@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.

Looks good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 16, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 16, 2026
Merged via the queue into ClickHouse:master with commit 3d7002b Oct 16, 2026
149 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 Oct 16, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

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. groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-backward-incompatible Pull request with backwards incompatible changes 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.

Multiple table_disk tables with s3_plain_rewritable disk with shared endpoint corrupt each other's data

4 participants