Skip to content

Fix server startup after a crash during EXCHANGE TABLES on an object storage database disk - #124937

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:fix-124833-interrupted-rename-exchange
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:fix-124833-interrupted-rename-exchange

Conversation

@groeneai

@groeneai groeneai commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124833
Related: #123832

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):

Fixed the server failing to start with INCORRECT_FILE_NAME (a leftover *.sql_tmp_rename_exchange file) after it was killed during EXCHANGE TABLES, CREATE OR REPLACE TABLE, REPLACE TABLE or a refresh of a refreshable materialized view, in a database whose metadata is on an object storage disk. The interrupted exchange is now finished when the database is loaded again.

Description

On 26.8.18.2, a server whose database metadata is on an object storage disk (database_disk or SETTINGS disk) cannot start after it is killed during EXCHANGE TABLES or CREATE OR REPLACE TABLE: Code: 79 ... Incorrect file extension: a.sql_tmp_rename_exchange ... (INCORRECT_FILE_NAME), until the file is removed by hand (26.3.42.3 too).

DiskObjectStorage::renameExchange does three moves persisted one by one; after the second, the counterpart's name is in no file, so no loader rule can repair it.

The disk is unchanged. On such a disk DatabaseAtomic::renameTable writes a record .<file>.exchange next to the metadata files with both paths and their contents after the exchange (as .tmp, then replaced; before the Replicated commit point; in both directories for an exchange between databases), then does the three moves and removes the record. DatabaseAtomic::loadTablesMetadata finishes a leftover exchange before listing: while its temporary file exists, two writes from the record complete it. A file with neither recorded content throws CORRUPTED_DATA. After a failed exchange whose undo may have left the temporary file, both databases refuse CREATE, RENAME, EXCHANGE, ALTER, DROP and DETACH until a restart finishes it.

Engines: Atomic (incl. system), Replicated, MaterializedPostgreSQL; Ordinary rejects them. DiskLocal keeps renameat2. Cost on S3: 49 instead of 30 requests per exchange.

Tests: 05340_interrupted_exchange_on_object_storage_database_disk (fails on master) builds every crash state on plain_rewritable and local metadata from a real record. kill -9 loops on S3: master 12/20 (EXCHANGE), 3/20 (CREATE OR REPLACE), 11/20 (cross-database), 17/60 (Replicated) restarts fail; this PR 0/40, 0/40, 0/40, 0/60, and 0/60 on local metadata. Lost Replicated replicas (kill between the Keeper commit and the first move, an existing window): 7/60, master 9/60.

A leftover written by an older server has no record and still fails as before. I can also make the loader move such a file back when its .sql name is free.

Raw timed logs (S3 plain_rewritable database disk, kill -9 during EXCHANGE TABLES, restart)

master:

21:30:46.032 iter 2: server killed with SIGKILL 201 ms after the stream started
      files in store/6c9/6c976fac-b7fd-45f3-9efb-33963923c6c0/: [ a.sql a.sql_tmp_rename_exchange b.sql ]
21:30:52.818 iter 2: SERVER START FAILED
      err.log: 2026.10.09 21:30:52.686133 [ 1931355 ] {} <Error> Application: Caught exception while loading metadata: Code: 79. DB::Exception: Incorrect file extension: a.sql_tmp_rename_exchange in metadata directory store/6c9/6c976fac-b7fd-45f3-9efb-33963923c6c0/. (INCORRECT_FILE_NAME)

this PR:

21:04:42.803 iter 2: server killed with SIGKILL 157 ms after the stream started
      files in store/1f3/1f367b82-3d04-4209-b653-7762b5c12746/: [ .a.sql.exchange a.sql.tmp_exchange b.sql ]
21:04:47.898 iter 2: server started; "db.a",...,6,30 "db.b",...,6,30
      server.log: 2026.10.09 21:04:47.691380 [ 804369 ] {} <Warning> DatabaseAtomic (db): Finished the interrupted exchange of store/1f3/1f367b82-3d04-4209-b653-7762b5c12746/a.sql and store/1f3/1f367b82-3d04-4209-b653-7762b5c12746/b.sql

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

groeneai and others added 3 commits October 9, 2026 13:48
…pened

DiskObjectStorage::renameExchange emulates the exchange with three moves
(old -> old_tmp_rename_exchange, new -> old, tmp -> new) that are persisted
one by one; a plain_rewritable move copies the object before it removes the
source. A server killed in between (EXCHANGE TABLES, REPLACE TABLE,
CREATE OR REPLACE over an existing object, a refreshable view refresh) left
<old>_tmp_rename_exchange behind, DatabaseOnDisk::iterateMetadataFiles
rejected it with INCORRECT_FILE_NAME, and the server could not start again
until the file was removed by hand. After the second move the name of the
counterpart is recorded nowhere, so the loader cannot repair it.

renameExchange now writes a record naming both paths to
clickhouse_rename_exchange_journal/<sipHash128(old)> before the moves and
removes it, best effort, after the commit (DatabaseAtomic::renameTable
updates its catalog only after renameExchange returns, so this must not
throw). The object storage disk creator finishes every recorded exchange
right after startup, before any database on the disk is loaded, except for
read-only and write-once disks. Recovery always rolls forward. It removes a
file only when another of the three holds the same bytes and moves only onto
a path it has just read as absent, so it never destroys unique bytes; any
other combination throws CORRUPTED_DATA before touching anything. An entry
of the journal directory that is not a valid record is left as is.

Because recovery runs at the disk layer, it covers every engine that
exchanges metadata files (Atomic incl. system, Replicated,
MaterializedPostgreSQL), both metadata types that implement moves
(plain_rewritable and local), and exchanges between two databases on one
disk. A new exchange is refused while a leftover of the previous one exists,
so the record always names the right counterpart. A torn copy on backends
that stream copies (local object storage, HDFS) is reported, not repaired.

Measured with kill -9 on an S3 plain_rewritable database disk: on master
22/40 (EXCHANGE TABLES) and 8/40 (CREATE OR REPLACE TABLE) restarts fail,
12/20 on 26.8.18.2; with this change 0/60 and 0/60, and 0/90 for a
Replicated database. Cost: 37 instead of 30 S3 requests per exchange.

Closes ClickHouse#124833

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop a line narrating the journal record write and condense the recovery invariant in finishRenameExchange.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 9, 2026
@groeneai

groeneai commented Oct 9, 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; round 1: 3 findings, round 2 on the fix: 0) plus my own cold review (nits only).

# Sev Finding Verdict Evidence / action
1 ❌ A record whose first move never landed is removed instead of rolled forward, leaving a Replicated replica behind Keeper DISAGREE Same local state as master and DiskLocal for that crash point (Keeper committed, nothing moved; NOTE at DatabaseAtomic.cpp:383), recovered by the default check_consistency lost-replica path; rolling it forward would also swap tables after a cleanly failed EXCHANGE. Description sentence made exact.
2 ⚠️ The test writes its own record, so the real writer and the post-commit removal are not covered AGREE, fixed @ 03f087a The test now counts records on the raw storage without opening the disk, and fails a real EXCHANGE with plain_object_storage_fail_after_copy_on_file_move. Deleting the record write, or the post-commit removal, now fails the test.
3 ⚠️ No test for the CORRUPTED_DATA branch DISAGREE Guards hand-corrupted states only; shown live by deletion mutations that routed valid states into it
4 💡 A torn local-metadata record file fails disk creation noted Same exposure as every local-metadata file on master; plain_rewritable records are single PUTs
5 💡 A second opener of the same storage (clickhouse-disks on a live disk) runs the recovery noted Two writers over one storage are already unsupported
6 💡 Byte-identical old/new files after the second move throw CORRUPTED_DATA instead of finishing noted Fails closed, and unreachable: the only caller is DatabaseAtomic::renameTable, whose metadata files each embed their own UUID

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

Session id: cron:clickhouse-review-slot-8:20261009-145400

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test builds each intermediate state of the emulated exchange with clickhouse-disks and reopens the database; on master every state fails with INCORRECT_FILE_NAME. A real kill -9 loop on an S3 (MinIO) plain_rewritable database disk fails 22/40 (EXCHANGE TABLES) and 8/40 (CREATE OR REPLACE TABLE) restarts on master, 12/20 on 26.8.18.2.
b Root cause explained? DiskObjectStorage::renameExchange emulates the exchange with three moves persisted one by one (a plain_rewritable move copies, then deletes). A crash leaves <old>_tmp_rename_exchange, which DatabaseOnDisk::iterateMetadataFiles rejects, and after the second move the counterpart's name is recorded nowhere.
c Fix matches root cause? Yes. The emulation becomes recoverable at its own layer: a record naming both paths is written before the moves, and the disk finishes recorded exchanges when it is created, before any database is loaded. No loader workaround.
d Test intent preserved / new tests added? New 05340_interrupted_exchange_on_object_storage_database_disk (every state on plain_rewritable and local metadata, the happy path, and a non-record entry that must survive). It also counts the records on the disk's raw files after a finished EXCHANGE and after one failed by a failpoint. Deleting any recovery branch, the creator call, the record write or its removal after the commit reddens it (8 mutations).
e Both directions demonstrated? Test: FAIL on master, OK with the fix (50/50, 8-way parallel). Kill loop: master 22/40 and 8/40 restart failures, fix 0/60 and 0/60.
f Fix is general across code paths? DiskObjectStorage::renameExchange is the only emulation (DiskLocal uses renameat2); its only caller is DatabaseAtomic::renameTable, which serves EXCHANGE, REPLACE, CREATE OR REPLACE and refreshable views for Atomic, Replicated and MaterializedPostgreSQL (Replicated: 0/90 restart failures). Ordinary rejects these statements.
g Fix generalizes across inputs (params/datatypes/wrappers)? Both metadata types with moves (plain_rewritable incl. its copy-then-delete states, local), same- and cross-database exchanges on one disk. Read-only disks (readonly, read_only wrapper) and write-once metadata skip recovery (measured: files untouched). A torn copy on streamed-copy backends (local, HDFS) is reported, not repaired.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no format change of existing files. An older server ignores the record directory (measured); a leftover from an older server has no record and fails as before.
i Invariants and contracts preserved? Recovery never destroys unique bytes: it removes a file only when another of the three holds the same bytes and moves only onto a path just read as absent; any other combination throws CORRUPTED_DATA before touching anything. The record removal after the commit is best effort, because DatabaseAtomic::renameTable updates its catalog only after renameExchange returns.

Session id: cron:clickhouse-impl-slot-7:20261009-142700

@groeneai
groeneai requested review from CheSema and alesapin October 9, 2026 15:18
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0c471b0]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_tsan, targeted) FAIL
test_refreshable_mv/test.py::test_backup_outer_table FAIL cidb
test_refreshable_mv/test.py::test_backup_inner_table FAIL cidb
test_refreshable_mv/test.py::test_backup_skips_rmv_target_when_view_storage_unresolved FAIL cidb
test_refreshable_mv/test.py::test_adding_replica FAIL cidb
test_refreshable_mv/test.py::test_backup_skips_rmv_target_when_target_storage_unresolved FAIL cidb
test_refreshable_mv/test.py::test_replicated_db_startup_race FAIL cidb
test_refreshable_mv/test.py::test_system_view_refreshes_on_not_running_replica FAIL cidb
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
05210_lightweight_update_materialized_cte_in_ignore FAIL cidb
01513_optimize_aggregation_in_order_memory_long NOT_FAILED cidb
01283_max_threads_simple_query_optimization NOT_FAILED cidb
02884_create_view_with_sql_security_option NOT_FAILED cidb
02346_non_negative_derivative NOT_FAILED cidb
Stateless tests (arm_binary, AsyncInsert, s3 storage, parallel) FAIL
05239_written_rows_quota_interval_rollover FAIL cidb
00952_insert_into_distributed_with_materialized_column NOT_FAILED cidb
03008_deduplication_cases_from_docs NOT_FAILED cidb
03008_deduplication_insert_into_partitioned_table NOT_FAILED cidb
02046_low_cardinality_parallel_group_by NOT_FAILED cidb
02912_ingestion_mv_deduplication NOT_FAILED cidb

AI Review

Summary

This PR moves interrupted object-storage metadata exchanges into DatabaseAtomic: it writes hidden *.exchange records before the metadata swap, replays them during database load, and fences later DDL with UNFINISHED after a failed exchange. The replay approach looks directionally right, but the current UNFINISHED checks still fire after some mutating paths have already started teardown or catalog rewiring, and the cross-database replay path still has a two-owner race during parallel database startup, so I would not merge this as-is.

Findings

❌ Blockers

  • [src/Databases/DatabaseAtomic.cpp:335] The UNFINISHED fence for DROP/DETACH still sits inside dropTableImpl(), after dropInnerTableIfAny() has already run (src/Databases/DatabaseAtomic.cpp:316-320). That means the internal _tmp_replace_* cleanup DROP in InterpreterCreateQuery still runs into the same late guard on a failed publish (src/Interpreters/InterpreterCreateQuery.cpp:3232-3238), and user DROP TABLE / DROP DATABASE / DETACH DATABASE can still stop replication or flush tables before being refused (src/Interpreters/InterpreterDropQuery.cpp:525-633). Suggested fix: reject these entrypoints before any storage teardown starts, not inside dropTableImpl().
  • [src/Databases/DatabaseAtomic.cpp:623] The UNFINISHED fence for ALTER is also too late. DatabaseOrdinary::alterTable() already calls DatabaseCatalog::updateDependencies() before this hook (src/Databases/DatabaseOrdinary.cpp:1053-1065), so a rejected ALTER can still leave referential/loading/view dependencies matching the uncommitted definition. Suggested fix: move the check to an earlier DatabaseAtomic::alterTable() override, or teach the base path to roll back dependency rewrites on failure.
  • [src/Databases/DatabaseAtomic.cpp:785] Cross-database recovery still has two owners. With async_load_databases = 1, both databases can enter finishInterruptedExchanges() at the same time, both pass the primary_file equality check, and both race on rewriting the two metadata files and deleting tmp_path. The loser of removeFile(tmp_path) turns a recoverable interrupted exchange back into a startup failure. Suggested fix: make only the primary record perform replay/removal, and let the copy side only garbage-collect itself after it observes recovery has finished.
Tests
  • ⚠️ Add a focused restart test where both databases participating in a cross-database EXCHANGE TABLES load concurrently with async_load_databases = 1; that is the missing coverage for the replay race above.
  • ⚠️ Add a regression that exercises a failed publish followed by the internal _tmp_replace_* cleanup path, so the UNFINISHED fence is proven to trigger before any DROP-side teardown.
Final Verdict

Status: ❌ Block
Minimum required actions:

  • Move the UNFINISHED checks for DROP/DETACH and ALTER to entrypoints that run before teardown or catalog rewrites.
  • Make cross-database replay single-owner under parallel database startup.
  • Re-test the failed publish / _tmp_replace_* cleanup path after the early DROP fence is in place.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 9, 2026

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

disks shoul know nothing about tables/exchanges and high level logic.

@Michicosun Michicosun self-assigned this Oct 9, 2026
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

Agreed, I will move this out of the disk. DiskObjectStorage goes back to the master code (no journal, no step at disk startup), and DatabaseAtomic makes its own exchange recoverable when the disk cannot exchange atomically: it writes a small record next to the metadata files naming both tables before renameExchange, removes it after, and the database loader finishes a leftover exchange before it lists the .sql files.

A loader rule alone is not enough: after the second move the counterpart's name is in no file (Atomic metadata stores ATTACH TABLE _ UUID ... and the name is the file name, DatabaseOnDisk.cpp:230), so that state needs the record.

@clickhouse-gh clickhouse-gh Bot added the comp-multidisk Multiple disks/volumes storage policies, disk abstractions. label Oct 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0c471b0d6 with master d741c9860 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of aa47c060d; 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

11 object files changed (+69.20 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Databases/DatabaseAtomic.cpp.o 458.93 KiB 527.94 KiB +69.01 KiB (+15.04%)

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

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

Job report

groeneai and others added 2 commits October 9, 2026 21:40
…disk

The disk should know nothing about tables and exchanges, so the disk is back
to master and `DatabaseAtomic` makes its own exchange recoverable.

When the database disk is a `DiskObjectStorage`, which cannot exchange two
files atomically, `DatabaseAtomic::renameTable` writes a record
`.<file>.exchange` next to the metadata files, naming both files and the
content each must have after the exchange, then moves them through its own
temporary file `<file>.tmp_exchange` in one disk transaction and removes the
record. For an exchange between two databases the record is written to both
directories, because the other database can be loaded first. The record is
written as `<record>.tmp` and then replaced, like a table's metadata file,
because writing it in place tore it on `local` metadata (a kill left a
0-byte record and the next start failed to read it); a leftover `.tmp` is
removed at load.

The records are written before the commit point of a `Replicated` database,
and only the moves follow it. A crash between the Keeper commit and the
first move loses the replica (the existing NOTE there), and writing the
records after the commit made that window longer (8 of 40 kill -9 restarts
on an S3 `plain_rewritable` database disk recovered a lost replica). With
the records before the commit, a concurrent run gave 7 of 60 against 9 of 60
on master. A record left by a crash before the commit has no temporary file
and is only removed at load, and the DDL entry is executed again from the
log.

`DatabaseAtomic::loadTablesMetadata` finishes a leftover exchange before the
metadata files are listed: the temporary file exists exactly from the first
copy until the last move, so if it exists the record holds both target
contents and recovery is two writes plus the removal of the temporary file,
the same in every state a crash can leave. A file that has neither recorded
content stops the load with CORRUPTED_DATA and nothing is changed. Record
removal is best effort; a leftover record is skipped by every listing.

If an exchange fails and its undo may have left the temporary file, both
databases refuse RENAME/EXCHANGE, ALTER, DROP and DETACH until the server
restarts, whose load finishes the exchange from the untouched state.

`DiskLocal` keeps `renameat2(RENAME_EXCHANGE)` and other disks keep
`renameExchange`, exactly as before.

Closes ClickHouse#124833

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove two comments in DatabaseAtomic.cpp that restate what the code below already says.

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

groeneai commented Oct 9, 2026

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

Review of the reworked change (exchange records in DatabaseAtomic, disk unchanged) by an independent model (engine: codex; round 1: 3 findings, round 2: 1 new) plus my own cold review (nits only).

# Sev Finding Verdict Evidence / action
1 ❌ The fence does not cover CREATE/ATTACH, so a Replicated CREATE after a failed exchange commits a digest derived from the stale value DISAGREE The only exit from the fence is a restart, which finishes the exchange as Keeper committed it; the stale-based digest then mismatches, and the check_consistency recovery keeps every table whose metadata matches Keeper (all of them). PR body narrowed to the statements the fence refuses.
2 ❌ The fence throws after DROP/DETACH/ALTER already shut the storage down or updated dependencies DISAGREE The fence needs a failed undo (impossible on plain_rewritable, whose undo retries until it succeeds); the refused statement changes no .sql, and the restart the error asks for reloads the table and its dependencies. Master has the same ordering for any dropTable failure and for CANNOT_ASSIGN_ALTER. A preflight needs a new IDatabase check in the interpreters; I can add it if you prefer.
3 ⚠️ The test never fails the real moves, so replacing the mover or deleting the fence keeps it green DISAGREE No existing failpoint fires inside the moves (each fires first at the record's write or replace, or needs an existing target); the moves are pinned by the kill -9 logs (temporary file in the killed state, Finished the interrupted exchange on restart, 0 failed starts).
4 💡 The loader lists the metadata directory of every Atomic database, also on disks that never get a record noted One extra listing per database at startup; it can be gated on the same disk check as the writer.
5 💡 49 instead of 30 S3 requests per exchange on an object storage database disk noted Stated in the PR body.

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

Session id: cron:clickhouse-review-slot-8:20261009-214300

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The test builds every state a crash can leave between the three moves of the exchange, from a record written by a real EXCHANGE, and reloads the database: master fails each one with INCORRECT_FILE_NAME. A kill -9 loop on an S3 (MinIO) plain_rewritable database disk fails on master (EXCHANGE, CREATE OR REPLACE, cross-database, Replicated) and on 26.8.18.2.
b Root cause explained? DatabaseAtomic::renameTable calls renameExchange, which DiskObjectStorage emulates with three moves persisted one by one. A crash leaves <file>_tmp_rename_exchange, which the metadata listing rejects, and after the second move the counterpart's name is in no file.
c Fix matches root cause? Yes, at the database layer, as the disk owner asked: the disk is unchanged; DatabaseAtomic records the exchange (both files and their contents after it) before it starts, does the moves itself, and finishes a leftover exchange before the metadata files are listed.
d Test intent preserved / new tests added? New 05340_interrupted_exchange_on_object_storage_database_disk: every crash state on plain_rewritable and local metadata, the cross-database case, a leftover temporary record, the guard and a non-record file. 10 deletion mutations of the fix each redden it.
e Both directions demonstrated? Test: FAIL on master, OK with the fix, 50/50 randomized. Kill loops (S3 MinIO, same rig): master fails 12/20 (EXCHANGE), 3/20 (CREATE OR REPLACE), 11/20 (cross-database), 17/60 (Replicated) restarts; the fix 0 of 180 Atomic (incl. 60 on local metadata) and 0 of 60 Replicated restarts.
f Fix is general across code paths? The exchange arm of DatabaseAtomic::renameTable is the only caller of renameExchange; it serves EXCHANGE, REPLACE, CREATE OR REPLACE and refreshable views for Atomic (incl. system), Replicated and MaterializedPostgreSQL. Ordinary rejects these statements; DiskLocal keeps renameat2(RENAME_EXCHANGE) (strace).
g Fix generalizes across inputs (params/datatypes/wrappers)? Both metadata types with moves (plain_rewritable incl. its copy-then-delete states, local), same- and cross-database exchanges in either load order, a crash while the record is written, and random kill points on the Replicated path. A file holding neither recorded content stops the load with CORRUPTED_DATA.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no format change of existing files. An older server skips the record (its name starts with a dot, measured); a leftover written by an older server has no record and fails as before.
i Invariants and contracts preserved? The record is complete (written as .tmp, then replaced) before the temporary file can exist, so "temporary file exists" means "interrupted" and recovery is the same two writes in every state; it never reads the temporary file and is idempotent. Records are written before the Replicated commit point, so the window between it and the first move holds no extra I/O (lost-replica restarts 7/60 vs master 9/60).

Session id: cron:clickhouse-impl-slot-5:20261009-205100

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

Done in 095f0c3: src/Disks is back to master. On a DiskObjectStorage database disk, DatabaseAtomic::renameTable writes the record before the Replicated commit point and does the three moves itself in one disk transaction instead of calling renameExchange; DatabaseAtomic::loadTablesMetadata finishes a leftover exchange before the .sql files are listed. Every other disk still calls renameExchange as before.

@clickhouse-gh clickhouse-gh Bot added comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. and removed comp-multidisk Multiple disks/volumes storage policies, disk abstractions. labels Oct 9, 2026
The previous commit removed the comment inside the catch (...) of
mayExist(), but that comment is what the catch_all style check needs
to accept a catch block that does not inspect the exception. Returning
true there is intended: when existence cannot be determined, the file is
treated as possibly present.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
auto db_disk = getDisk();
{
std::lock_guard lock(mutex);
assertNoUnfinishedExchangeUnlocked();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The new assertNoUnfinishedExchangeUnlocked() here also blocks the internal cleanup path for temporary _tmp_replace_* tables. InterpreterCreateQuery::doCreateOrReplaceTable creates the replacement under a temporary name and, if the final publish rename/exchange throws, drops that temp in its outer catch (src/Interpreters/InterpreterCreateQuery.cpp:3226).

After this change, once unfinished_exchange is set the publish step fails as intended, but that cleanup DROP now hits the same UNFINISHED guard here, is logged and swallowed, and the temporary table/data are left behind. So a single interrupted exchange can make later CREATE OR REPLACE, REPLACE, and Atomic CREATE TABLE ... AS SELECT strand _tmp_replace_* tables until manual cleanup or restart.

Can we exempt internal temp-table cleanup from this guard, or reject these create/replace flows before the temporary table is created?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 7d06a6d: a database with an unfinished exchange now also refuses CREATE, so these queries fail before their _tmp_replace_* table exists.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This still does not cover the original cleanup path. In the failing CREATE OR REPLACE / REPLACE query, the temporary table already exists before renameTable() sets unfinished_exchange on the publish failure (src/Databases/DatabaseAtomic.cpp:557-560). The outer catch then still issues DROP on that temp table (src/Interpreters/InterpreterCreateQuery.cpp:3232-3238), and DatabaseAtomic::dropTable() still runs dropInnerTableIfAny() before the first assertNoUnfinishedExchangeUnlocked() only later in src/Databases/DatabaseAtomic.cpp:316-320 / src/Databases/DatabaseAtomic.cpp:335.

So the _tmp_replace_* cleanup DROP is still blocked after teardown has already started, and the original leak/side-effect path is still present in the current code.

After an exchange whose undo may have left its temporary file, the
database refused RENAME, EXCHANGE, ALTER, DROP and DETACH, but not
CREATE. `CREATE OR REPLACE`, `REPLACE` and `CREATE TABLE ... AS SELECT`
therefore still created and filled their `_tmp_replace_*` table, then
failed to publish it and failed to drop it, so each such query left the
table and its data behind, also after the restart.

Refusing CREATE as well rejects these queries before the temporary table
exists. Scoping the refusal to the two exchanged tables instead would let
`DROP` of an exchanged materialized view remove its inner table before
the refusal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
auto db_disk = getDisk();
{
std::lock_guard lock(mutex);
assertNoUnfinishedExchangeUnlocked();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

assertNoUnfinishedExchangeUnlocked() still fires too late in the drop path. DatabaseAtomic::dropTable() already called table->dropInnerTableIfAny() before we get here, and StorageMaterializedPostgreSQL::dropInnerTableIfAny() does replication_handler->shutdownFinal() / reset() first. So DROP TABLE in a database with an unfinished exchange can permanently stop replication and only then throw UNFINISHED instead of being a no-op refusal.

There is the same late-guard problem one level up for DROP / DETACH DATABASE: InterpreterDropQuery::executeToDatabaseImpl() stops replication and runs flushAndPrepareForShutdown() before the first table-level guard fires. Can we reject these drop / detach entry points before any teardown starts, rather than only inside dropTableImpl()?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Michicosun one design question about the fence before I grow this PR further, since the AI review flags its ordering again.

When an exchange's commit fails and its undo fails too (a local I/O error for local metadata; on plain_rewritable only when the blob to restore is gone, undoWithRetries retries everything else), both databases refuse CREATE/RENAME/ALTER/DROP/DETACH with UNFINISHED until a restart finishes the exchange. The check sits in DatabaseAtomic, so DROP/DETACH of a table or a database shut the storage down before they are refused (for MaterializedPostgreSQL this drops the publication and the slot, and the restart reloads it from a new snapshot). Master has the same order for any failure in dropTableImpl.

Which do you prefer?

  1. Keep it as is.
  2. Add an IDatabase check that the DROP/DETACH/ALTER interpreters call before they touch the storage.
  3. Remove the fence: DDL after such a failure runs as on master, and the next start rewrites both files from the record (a table dropped in between comes back) or stops with CORRUPTED_DATA.

The CI runners sort with a locale that ignores the leading dot, so the
record files moved within the listing and the test failed on every run.
`LC_ALL=C sort` gives the byte order the reference was written in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
const bool fsync = getContext()->getSettingsRef()[Setting::fsync_metadata];
for (const auto & record_file : record_files)
{
const String content = readMetadataFile(db_disk, record_file);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

For exchanges between two databases, both directories get a record so either database can recover first — but with async_load_databases = true the two loadTablesMetadata jobs can also run at the same time. In that case the other database may already have finished the exchange and removed this copy before we get here, so readMetadataFile(record_file) can throw on a perfectly recoverable state; if both sides pass the tmp_path check, they can also race on removeFile(tmp_path) below. That means startup is still nondeterministically broken in the cross-database case this PR is trying to cover.

Can we make replay single-owner here (for example only the primary record repairs/removes, while the copy side only cleans itself up after recovery is complete)?

The ASan flaky check stopped the test at "Test runs too long (> 180s)":
it started clickhouse-disks 55 times and clickhouse-local 29 times, and
a start of the ASan binary costs about 0.55 s on its own (a bare `ls` /
`SELECT 1` take 539 / 590 ms), which is nearly all of the test's time.

Each listing after a load now shares one clickhouse-disks call with
the commands that build the next state, records are written with
`copy --disk-from local` instead of a separate `write` call, and the
tables are swapped back with the same three moves on the disk instead
of a clickhouse-local `EXCHANGE TABLES`. That is 20 + 20 starts instead
of 55 + 29. The file listing comes from `ls --recursive`, which prints
a header per directory and sorts by bytes, so no shell `sort` is left.

The reference is unchanged. Measured with the fix debug binary: 64
parallel runs each, old median 69.3 s / max 70.0 s, new median 40.4 s /
max 41.1 s, all 128 matching the reference. Every mutation of the
earlier rounds (M1-M8, M10, M11) still fails the new test at the same
first reference line as the old one; the master binary still fails it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
});

std::lock_guard lock{mutex};
assertNoUnfinishedExchangeUnlocked();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

UNFINISHED is supposed to make ALTER a no-op until restart, but this guard runs after DatabaseOrdinary::alterTable() has already mutated catalog state: it rewrites the dependency graph at src/Databases/DatabaseOrdinary.cpp:1053-1065 before commitAlterTable() gets here. So a rejected ALTER can still leave referential/loading/view dependencies corresponding to the uncommitted definition, even though table_metadata_path was never replaced.

Can we reject ALTER before the base implementation updates dependencies (for example by overriding alterTable() in DatabaseAtomic), or roll those dependency rewrites back on failure?

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0c471b0

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
Integration tests (amd_tsan, targeted) / test_refreshable_mv (7 tests) not from this PR: test_system_view_refreshes_on_not_running_replica hits the ThreadSanitizer report on the aws-c-common cpuid_state race (aws_common_private_has_avx2, armed by the AWS SDK bump #124678, since reverted on master by #125030), the node dies and the other 6 tests fail on it (No route to host / connect timeout). The same 7 tests failed the same way on master 0d2ade023628 #125039 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05210_lightweight_update_materialized_cte_in_ignore flaky, not from this PR: UNKNOWN_TABLE for _materialized_cte_c_* on a replica (issue #112642), 2/114 reruns fail; it fails on dozens of PRs and on master since 2026-10-08 #123121 (mine, open)
Stateless tests (arm_binary, AsyncInsert, s3 storage, parallel) / 05239_written_rows_quota_interval_rollover flaky, not from this PR: under async inserts the rollover checkpoint line 1 1 is missing; 7/7 reruns pass #124935 (mine, open)
Mergeable Check, PR praktika rollups of the rows above (Failed: 3) #125039, #123121, #124935 (mine, open)

The Stateless tests (*, flaky check) failures of 05340_interrupted_exchange_on_object_storage_database_disk on the previous heads are gone on this one: the test passes in every flavour.

Session id: cron:our-pr-ci-monitor:20261010-133005

@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Dear @Michicosun, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

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-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Killed CREATE OR REPLACE over an existing table still blocks server startup

2 participants