Repository navigation
Conversation
…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]>
…oves it 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]>
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).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261009-145400 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20261009-142700 |
|
Workflow [PR], commit [0c471b0] Summary: ❌
AI ReviewSummaryThis PR moves interrupted object-storage metadata exchanges into Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block
|
Michicosun
left a comment
There was a problem hiding this comment.
disks shoul know nothing about tables/exchanges and high level logic.
|
Agreed, I will move this out of the disk. A loader rule alone is not enough: after the second move the counterpart's name is in no file ( |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes11 object files changed (+69.20 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units34 translation units recompiled, 280 s compile time in total, 34 of them have a recent master baseline. |
…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]>
Internal second-model review: adjudication log (click to expand)Review of the reworked change (exchange records in
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261009-214300 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20261009-205100 |
|
Done in 095f0c3: |
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(); |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Fixed in 7d06a6d: a database with an unfinished exchange now also refuses CREATE, so these queries fail before their _tmp_replace_* table exists.
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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()?
|
@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 Which do you prefer?
|
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); |
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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?
CI finish ledger - 0c471b0Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The Session id: cron:our-pr-ci-monitor:20261010-133005 |
|
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. |
Closes: #124833
Related: #123832
Changelog category (leave one):
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_exchangefile) after it was killed duringEXCHANGE TABLES,CREATE OR REPLACE TABLE,REPLACE TABLEor 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_diskorSETTINGS disk) cannot start after it is killed duringEXCHANGE TABLESorCREATE 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::renameExchangedoes 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::renameTablewrites a record.<file>.exchangenext to the metadata files with both paths and their contents after the exchange (as.tmp, then replaced; before theReplicatedcommit point; in both directories for an exchange between databases), then does the three moves and removes the record.DatabaseAtomic::loadTablesMetadatafinishes a leftover exchange before listing: while its temporary file exists, two writes from the record complete it. A file with neither recorded content throwsCORRUPTED_DATA. After a failed exchange whose undo may have left the temporary file, both databases refuseCREATE,RENAME,EXCHANGE,ALTER,DROPandDETACHuntil a restart finishes it.Engines:
Atomic(incl.system),Replicated,MaterializedPostgreSQL;Ordinaryrejects them.DiskLocalkeepsrenameat2. 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 onplain_rewritableandlocalmetadata from a real record.kill -9loops 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 onlocalmetadata. LostReplicatedreplicas (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
.sqlname is free.Raw timed logs (S3
plain_rewritabledatabase disk,kill -9duringEXCHANGE TABLES, restart)master:
this PR:
Workflow [PR]
Sync PR [sync-upstream/pr/124937]