Repository navigation
Fix EmbeddedRocksDB data loss when RENAME changes the table data path - #112224
alexey-milovidov merged 17 commits into
Conversation
The engine declared storesDataOnDisk() as true but never overrode IStorage::rename, so it inherited the default implementation, which only updates the StorageID and discards the new path. DatabaseOnDisk::renameTable passes that path precisely so the storage can move its data. The rows stayed reachable until the next restart because nothing re-derives rocksdb_dir on the live table. After a restart the constructor recomputed it from the table's new location and rocksdb::DB::Open ran with create_if_missing = true, so it created an empty database while the real rows stayed orphaned under the old directory. The predicate is "the computed data path changes", not "another database": a plain same-database RENAME inside an Ordinary database lost all data too, and the Ordinary -> Atomic direction left a table that could not be attached at all and that broke system.tables listing while its metadata existed. The Atomic cases were unaffected only because an Atomic path is keyed on the table UUID, which rename preserves. A directory given explicitly in the engine arguments is deliberately not moved: it does not belong to the table's location, may be shared, and is recomputed from the argument on every load. renameNoReplace is used rather than a check plus fs::rename because a plain fs::rename silently clobbers an existing empty destination directory, and a check-then-rename pair is also racy. The second hunk adds the missing catch (...) to DatabaseOnDisk::renameTable. That function detaches the table before calling the unrestricted virtual hook, but handled only DB::Exception and Poco::Exception, and std::filesystem::filesystem_error is neither, so such a throw left the table detached until a restart. The hole is pre-existing and shared with StorageFile::rename and with DiskLocal's bare fs:: calls used by StorageLog, StorageStripeLog and MergeTreeData, but the new RocksDB override is what makes this hook throw raw filesystem errors on this path. Closes: ClickHouse#111958 Co-Authored-By: Claude Opus 5 <[email protected]>
StorageEmbeddedRocksDB::rename closes the only handle before moving the directory. If the move or the reopen fails, the rollback tries to reopen the original directory, but that reopen can fail too, and its inner handler only logged. DatabaseOnDisk::renameTable then re-attaches the storage object under the old name, leaving a live table with a null handle. The read paths did not fail in that state, they reported emptiness: the full scan substituted a NullSource, the key lookup returned no rows, and the two trivial-count estimates returned nothing. A SELECT count() therefore answered 0 for a table whose data was intact on disk, which is the same silent loss this change set exists to remove. Record that the handle is unusable and make the four read paths throw ROCKSDB_ERROR naming the directory, so the data can be recovered by hand. The teardown paths keep tolerating a null handle: a class that accepts one for DROP and TRUNCATE is not thereby accepting one for reads. The original exception still propagates unchanged, and a later successful rename clears the state. Also pin the catch-all added to DatabaseOnDisk::renameTable. A destination collision raises ATOMIC_RENAME_FAIL or FILE_ALREADY_EXISTS, both DB::Exception, so the pre-existing handler already covered it and the new one was unpinned. A failpoint injects a raw std::filesystem::filesystem_error, the one class that escapes both typed handlers, and the test then asserts the table is still attached and still readable. Closes: ClickHouse#111958 Co-Authored-By: Claude Opus 5 <[email protected]>
The four read guards added in the previous round had no committed oracle. They fire only when a rename's rollback reopen fails too, and the existing failpoint throws before the directory is moved, so the rollback reopens the untouched original directory and succeeds. Deleting all four guards left the test green. A second, REGULAR failpoint makes the reopen itself fail. REGULAR rather than ONCE because the mechanism needs it to fire twice in one statement: once for the forward reopen and once for the rollback reopen. It lives in a private initDBForRename() wrapper instead of in initDB(), so it stays unreachable from the constructor and from truncate() and cannot be tripped by a concurrent test. The new test case asserts that the full scan and the key lookup both refuse with ROCKSDB_ERROR and that a reload still recovers every row, which is what separates "this object cannot serve the data" from "the data is gone". Deleting all four guards, or only the flag write, turns both refusal lines to zero; deleting only the full-scan guard moves only the first. optimize_trivial_approximate_count_query is pinned to 0. Its product default is already 0, but the stateless runner randomizes it to 1 in half of all runs, and with 1 a SELECT count() is answered from RocksDB's estimated key count rather than by reading the table: measured on a 37-row table, the plan drops ReadFromEmbeddedRocksDB for ReadFromPreparedSource and query_log reports read_rows 1 instead of 37. Since the test's whole subject is which directory is being read, its count assertions have to enter the read path. A comment records that, so a cleanup does not delete a pin that looks redundant against the default. handle_unusable is now cleared at the end of every successful initDB() instead of only on the rename success path, and the explicit clear there is dropped. The flag's meaning becomes exactly "the most recent open attempt failed and could not be recovered", as its comment already claimed; before, a later successful truncate() reopen left a stale true behind. That is inert today, because all four guards sit inside a null-handle check, so this change has no observable and none was invented for it.
…relocation IStorage::rename is documented as being called under the exclusive table lock, and DatabaseOnDisk::renameTable honours that, but InterpreterCreateQuery::doCreateTable published the table with createTable and then relocated it with no table lock. The published table is immediately resolvable, so a concurrent reader could take the shared lock and hold a RocksDB iterator into a database the relocation is about to close. The new EmbeddedRocksDB override is the first implementation on that path that destroys a live handle, which is what makes the missing lock reachable. The lock is taken before publication rather than between publication and the rename, because taking it later only narrows the window: a reader that resolved the table in the gap would make the acquisition block instead of excluding it. It is released before startup(), which is not part of the rename contract. None of the other engines reaching that call site takes a table lock inside its own rename (MergeTreeData, StorageReplicatedMergeTree, StorageLog, StorageStripeLog, StorageSetOrJoinBase, StorageFile, StorageProxy), so holding it for that window cannot deadlock them. Test case 13 pins the window with a new PAUSEABLE failpoint reached only from the from_path branch. Case 9 additionally asserts the reload and that the source directory is gone, so an implementation that updated the path without moving or reopening the data no longer passes it. Co-Authored-By: Claude Fable 5 <[email protected]>
The failpoint is registered as PAUSEABLE_ONCE, not PAUSEABLE. Co-Authored-By: Claude Fable 5 <[email protected]>
StorageEmbeddedRocksDB::rename decided in its rollback whether the forward move had happened by looking at the two directories. That inference is wrong whenever the old directory exists again for a reason other than "the move never happened": any statement naming it recreates it, and for ATTACH TABLE ... FROM that directory is a user-supplied path under user_files that is not a private resource. The rollback then skipped the move-back, reopened the recreated directory with create_if_missing = true, and the table came back live, readable and empty while every row sat at the new location. That is the symptom this change exists to remove, so the new code must not be able to reintroduce it. The rollback now records in a local flag whether renameNoReplace returned, and when the move-back is impossible it fails closed: the handle stays null, rocksdb_dir keeps naming the directory that holds the rows, and the four read entry points refuse with ROCKSDB_ERROR naming it. Refusing is correct there and answering zero rows is not, because the rows exist. Case 14 of the stateless test pins it with a pauseable failpoint that stops a failed rename right before its rollback, so the source directory can be recreated in that window deterministically. Restoring the old predicate turns the three refusal assertions of that case from 1 to 0. Also names the process-global failpoints as the second reason the test is tagged no-parallel. Co-Authored-By: Claude Opus <[email protected]>
…path When the forward move succeeded but the reopen failed, the rollback moved the directory back. renameNoReplace refuses any existing destination, even an empty one, so a directory recreated at the old location in that window made the move-back fail and the table fell back to its fail-closed state: null handle, rocksdb_dir naming the destination, reads refusing. That state is correct for the live object, but it is held in memory only, while DatabaseOnDisk::renameTable re-attaches the metadata under the old name. A reload therefore constructed a fresh object at the old path, forgot the flag, and opened it with create_if_missing = true, answering zero rows over data that was still on disk at the destination. Reporting an empty table for data that exists is the failure mode this branch exists to remove, so it must not be reachable through the new code. The only occupant of the old path reachable through SQL is an empty directory, which by definition holds no data. The rollback now removes such a directory and retries the move once, so the data and the metadata end up together at the old path and the table recovers, reload included. A non-empty occupant was not created by this table: it is kept, the data stays where it is, and the fail-closed state is reached as before. Case 14 of the stateless test becomes that recovery case and now asserts the reload, which is what proves the recovery is on disk rather than in the live object. New case 15 keeps the fail-closed state covered by occupying the old path with a directory that holds a file, and asserts that the file survives. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal review before opening this PR: 6 rounds, 32 findings, 19 AGREE / 12 DISAGREE adjudicatedBefore opening this PR I put the change through an independent cold code review plus a Every AGREE below is fixed in the diff and pinned by a test case. Every DISAGREE is The five findings that changed the designEach of these came from a review pass over the previous round's fix, which is why they
Coverage and hygiene findings
Where I disagreed, with the evidence
Checked independently and found correctRecorded here rather than as findings: member initialisation order for the new One coverage boundary is deliberate: the Happy to split the |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260728-043001 |
|
cc @GrigoryPervakov @tuanpach — could you review this? |
|
Workflow [PR], commit [2e30b0f] Summary: ✅
AI ReviewSummaryThis PR fixes the main Findings❌ Blockers
Final Verdict❌ Changes required before merge: |
| /// when data directory moved, but table has not been created due to some error. | ||
| if (from_path) | ||
| { | ||
| FailPointInjection::pauseFailPoint(FailPoints::attach_from_path_pause_before_relocation); |
There was a problem hiding this comment.
ATTACH TABLE ... FROM still is not atomic here. database->createTable() has already written metadata and published res before res->rename() runs, and StorageEmbeddedRocksDB::rename can now throw on renameNoReplace, initDBForRename, or the new raw-filesystem-error path. When that happens the statement returns an exception but the table stays attached under the destination name, so a retry immediately hits TABLE_ALREADY_EXISTS; in the rollback-success branch the leaked table is even fully readable from the source path. This path needs a rollback (detach/drop the just-created table and metadata on rename failure) or publication has to move after relocation succeeds.
There was a problem hiding this comment.
The mechanism is real and correctly described, but it is pre-existing and not specific to this engine, and the prescribed remedy destroys user data as written. I measured both halves.
Pre-existing. I ran the same probe on a pristine master debug build (Build ID ef52c5f831df5afc0852778006b8133546eb42c2) and on this PR's head (ea97b6ba5e64587335666349bd2a5c0255b5933d), pre-creating the destination directory so rename throws:
| engine | throw site | attach error | table left attached | live read | retry | read after reload |
|---|---|---|---|---|---|---|
MergeTree |
MergeTreeData::rename |
Code: 84 |
yes | 5 rows | Code: 57 |
0 |
Log |
DiskLocal::moveDirectory (bare fs::rename, ENOTEMPTY) |
Code: 1001 |
yes | - | Code: 57 |
- |
EmbeddedRocksDB (this PR) |
renameNoReplace |
Code: 521 |
yes | 6 rows | Code: 57 |
0 |
The MergeTree and Log rows are byte-identical on master and on this head. The leak is a property of doCreateTable publishing before relocating, which every engine with a throwing rename already hits. What this PR changes is only that EmbeddedRocksDB joins that set, because its rename used to be an inherited no-op that could not throw. That is the bug being fixed here.
The remedy as stated is destructive. In the leaked state the storage object's data path is still the user's source directory under user_files, because the relocation never happened. So a caller-side detach/drop runs the engine's drop() against the user's data:
StorageLog::dropisdisk->removeRecursive(table_path)(src/Storages/StorageLog.cpp:964-967).MergeTreeData::dropAllDataends indisk->removeRecursive(relative_data_path)(src/Storages/MergeTree/MergeTreeData.cpp:4641).
Measured, dropping the leaked table, identical on both binaries: the MergeTree source directory goes from 11 files to gone, and the Log one from 4 files to gone. The server log names the victim directly, dropAllData: removing table directory recursive to cleanup garbage pointing at the user_files source path. EmbeddedRocksDB survives that only incidentally, because StorageEmbeddedRocksDB::drop closes the handle and removes nothing.
Today the state is recoverable: DROP TABLE on the leaked table plus a retry of the same ATTACH ... FROM returns 5 rows for MergeTree and 6 for EmbeddedRocksDB in my runs. A rollback-by-drop would convert that into permanent loss for two of the three engines.
On moving publication after relocation. That ordering is deliberate and documented at src/Interpreters/InterpreterCreateQuery.cpp:2321-2322: "Wo do not move data earlier to avoid situations when data directory moved, but table has not been created due to some error." Reversing it re-opens exactly the orphaned-directory case that comment avoids, so it is a trade to argue, not a mechanical reordering.
Disposition. I agree on the mechanism and defer the fix. It belongs in InterpreterCreateQuery, it needs a rollback that removes only the metadata rather than calling IStorage::drop, and it should be decided together with the sibling ordering defect in the same function (tryCreateSymlink at :2307 runs before rename at :2312, which leaves the Atomic data/<db>/<table> symlink dangling on master today). A fix task with the measurements above, the destructive-remedy evidence, and those constraints is filed; folding a change to the interpreter's publication order into this PR would mix two concerns and would ship untested for the seven other engines on that call site.
What this PR does add to that call site is the exclusive table lock around the relocation, which is what stops a concurrent reader from holding an iterator into a RocksDB about to be closed. That is pinned by case 13 of the new test.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 113/131 (86.26%) · Uncovered code |
CI finish ledger - 1ba4edbCI has fully finished on this head: 174 check-runs, all completed, 0 queued, 0 in progress,
Not PR-caused: this PR changes Owner justification: #112045 is titled for exactly this defect and its diff is Session id: cron:our-pr-ci-monitor:20260728-120000 |
Two textual conflicts, both declaration-list unions in files where master and this branch each appended: - src/Common/FailPoint.cpp: master added the four atomic_populate failpoints in the same region where this branch added attach_from_path_pause_before_relocation and rocksdb_rename_pause_before_rollback. Kept all six. Verified per symbol against the merge base that this branch removes nothing and that master's removal of create_empty_part_inject_stale_dir is not resurrected. - src/Interpreters/InterpreterCreateQuery.cpp: the same both-appended shape in the FailPoints extern block. Master's create-path work in this window (atomic POPULATE source snapshot and DDL guard ordering) does not interact with the ATTACH ... FROM relocation this branch changes: shouldPopulateMaterializedViewAtomically requires is_materialized_view with an immediate INSERT SELECT, which cannot hold together with has_attach_from_path, and the exclusive table lock taken here is released before startup() as before.
CI finish ledger - 7ca4bbaEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task CI is fully finished on this head: 175 checks, 0 incomplete, 156 jobs OK, 18 skipped
Session id: cron:our-pr-ci-monitor:20260811-180000 |
Resolves one conflict in src/Common/FailPoint.cpp: a mid-list both-appended declaration union. Master added 46 failpoints, this branch adds 4; the union keeps all 50, each present exactly once, and does not resurrect limit_by_transform_mid_loop_pause's trailing-backslash edit. Merged tree differs from master by exactly the 7 files and 486 insertions of this PR, with zero deletions.
…ion test The Style check rule server_data_manipulation_in_stateless_tests reports 04648_rocksdb_rename_moves_data.sh: the file reads a server-side path from system.tables and also runs file-modifying commands, which stateless tests may not do because the suite runs against object storage, shared MergeTree and encrypted disks, where the local layout does not exist or does not mean what the test assumes. Three cases needed a directory planted inside the server's own table data directory: an existing destination that the rename must refuse, and the two double-failure states where the rollback finds the old location occupied by an empty and by a non-empty directory. None of them is reachable through supported SQL - renameNoReplace refuses any existing destination, and every SQL route to occupy the old path blocks on the DDL guard the paused rename holds - so they move to tests/integration/test_rocksdb_rename_data_loss rather than being rewritten. Each was checked to still fail without the fix: inferring "was the directory moved" from path existence instead of the flag reddens both rollback cases, and making the forward move replace an existing destination reddens the third. The remaining stateless cases keep their coverage and stop mutating the server's data. The mkdir of the explicit directory was redundant, since the engine calls create_directories for it. The concurrent-reader assertion in the ATTACH FROM case now names DEADLOCK_AVOIDED: it previously accepted any output other than the row count, which an unrelated failure also satisfies.
The failpoints the test arms are server-global and outlive the client, so a run that is terminated between enabling and disabling one leaves it armed for whatever executes next; case 13 could also leave a paused server query with no one to release it. An EXIT trap now disables all four and reaps the background attach. Verified in both directions with a harness that arms a failpoint and is then killed mid-run: with the trap no failpoint stays enabled, and with the trap removed the same kill leaves one behind.
Build profile diff (arm_release)Commit See the job log for details. |
|
📊 Cloud Performance Report ✅ AI verdict: This PR changes only DDL and storage-management paths: how EmbeddedRocksDB moves its data on RENAME, a catch-all rollback in DatabaseOnDisk::renameTable, and an exclusive lock taken while ATTACH TABLE ... FROM relocates data. None of the benchmark SELECT queries run this code. The only flagged rows are ClickBench Q30 (+21.5%) and Q31 (+19.5%). Both were correctly held back because the PR medians sit inside master's normal range. CPU time is unchanged for both, and the PR runs were noisier than the baseline and shared one machine across both benchmarks, so the wall-clock shift reflects test conditions rather than the code change. clickbenchFlagged queries (2 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
…rename-moves-data Two conflicts in StorageEmbeddedRocksDB, both taken as a union of the two sides: * ErrorCodes: master added CANNOT_RESTORE_TABLE next to this branch's FAULT_INJECTED; both declarations are needed, kept in alphabetical order. * alter(): master gave it a trailing DDLGuardPtr & parameter. The declaration now carries master's signature, next to this branch's rename() override. The definition came across from master unconflicted and already matches. rename() relocates the data directory only when implicit_path holds, so it never moves a directory that master's backup owner election lets several tables share.
CI finish ledger - bf9fa79Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task CI is fully finished on this head: 176 checks, 0 incomplete, 158 pass, 15 skipped, 3 failed.
Session id: cron:our-pr-ci-monitor:20260915-190256 |
… rename When a rename moves the directory, then fails to reopen it and cannot move it back, the table stays attached under its old name with rocksdb_dir naming the destination that holds the rows, while the metadata still names the old path. Reads already refuse in that state. TRUNCATE did not: it removed rocksdb_dir, created an empty database there and cleared handle_unusable, so the table looked healthy while it wrote into a directory that a reload never opens. Measured with the integration test's double-failure setup: after the TRUNCATE, 3 inserted rows were visible, and 0 after DETACH + ATTACH, with the rows left behind in the destination directory. TRUNCATE now refuses with the same ROCKSDB_ERROR as reads. DROP, DETACH + ATTACH and repeating the RENAME stay available; repeating the rename commits the metadata where the data is, and all 6 rows are back after a reload. Found by the automated review in ClickHouse#112224 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment-only change; the comment-stripped sources are identical. Each kept comment now states only the local invariant; the reasoning they used to carry is in the history of this branch: - the rollback tracks the move in a flag because the old path can exist again after the data was moved, so path existence cannot tell whether it moved; - only an empty directory at the old location is removed before retrying the move back, because it cannot hold data; - the ATTACH ... FROM lock is taken before createTable() publishes the table and released before startup(), which is not part of the rename contract. Dropped the comments that repeated the header (initDBForRename(), the handle_unusable write) or stated what the next line does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - cb97df8Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Fix presence, measured: this job installed All 176 check runs completed (157 pass, 15 not selected, 4 red) and Session id: cron:our-pr-ci-monitor:20260926-143040 |
…-rocksdb-rename-moves-data # Conflicts: # src/Common/FailPoint.cpp # src/Interpreters/InterpreterCreateQuery.cpp
… rename After a failed rename whose rollback also fails, the table has no RocksDB handle and reads and TRUNCATE refuse with ROCKSDB_ERROR, but optimize() treated the null handle as "nothing to compact" and reported success. It now refuses the same way. The refusal was written out at five sites; it is now one helper, throwIfHandleUnusable(), used by all six. Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov
left a comment
There was a problem hiding this comment.
Somewhat excessive, but ok.
Closes: #111958
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes silent data loss when an
EmbeddedRocksDBtable is renamed.RENAME TABLEnow moves the table's RocksDB directory to the table's new location, so the rows are still there after a server restart. Previously the directory was left behind, and after a restart the table opened a freshly created empty RocksDB while the real rows stayed orphaned under the old path.Description
StorageEmbeddedRocksDBdeclaresstoresDataOnDisk()astrueand publishes its directory throughgetDataPaths(), but it never overridesIStorage::rename, so it inherited the default implementation, which only updates theStorageIDand discards the new path.DatabaseOnDisk::renameTablepasses that path with the comment "It will move data to new path (if it stores data on disk)", so the engine silently opted out of a contract it declares.The bug survives until the next restart because nothing re-derives
rocksdb_diron the live table: the already open handle keeps answering correctly from the old directory. After a restart the constructor recomputesrocksdb_dirfrom the table's currentrelative_data_pathandrocksdb::DB::Openruns withcreate_if_missing = true, so it creates an empty database instead of failing. That flag is what turns a stale path into silent data loss.Scope is wider than the issue's framing. The predicate is "the computed data path changes", not "another database". Measured on a debug build of master, with a restart between the two columns:
Atomic->Ordinary(as reported)Ordinary->Ordinary, different databaseRENAME TABLE a TO binside oneOrdinarydatabaseOrdinary->AtomicAtomic->Atomic, different databaseAtomicdatabaseA plain same-database
RENAME TABLE a TO bin anOrdinarydatabase already loses all data, with no deprecated flag needed once the database exists. The twoAtomicrows are unaffected only incidentally: anAtomicdata path is keyed on the table UUID, which rename preserves, so the recomputed string is byte-identical.The
Ordinary->Atomicdirection is worse than data loss. A fresh UUID is assigned, so the recomputedstore/<new-uuid>/does not exist, andATTACHskips directory creation, so the open fails withCode: 555 ROCKSDB_ERROR ... No such file or directory: While mkdir if missing. While that metadata file exists,SELECT count() FROM system.tablesandSHOW TABLES FROM <db>both fail withCode: 722 ASYNC_LOAD_WAIT_FAILED; unrelated queries still work, so the blast radius is table listing. This direction is also whatconvertOrdinaryDatabaseToAtomicuses, so the server-side database conversion path was affected too.The fix.
StorageEmbeddedRocksDB::renamecloses the handle, creates the parent of the new location, moves the directory withrenameNoReplace, updatesrocksdb_dir, reopens throughinitDB(), and then callsrenameInMemory.renameNoReplaceis used rather than a check plusfs::renamebecause a plainfs::renamesilently clobbers an existing empty destination directory (measured:ec = 0, data moved on top), and a check-then-rename pair is also racy. The same call is already used to move a table data directory inInterpreterCreateQuery.A directory given explicitly in the engine arguments (
ENGINE = EmbeddedRocksDB(0, '<path>')) is not moved. Such a directory does not belong to the table's location, may be shared, and is recomputed from the engine argument on every load, so relocating it would move a user-owned directory out from under the user. The intent is recorded as aconst bool implicit_pathmember set in the constructor rather than re-derived later by comparing strings.On any failure the previous handle is restored before rethrowing, because
DatabaseOnDisk::renameTablere-attaches the table under the old name when the hook throws. Without the restore, the re-attached table would be live with a null handle, which makesSELECTreturn zero rows silently. The rollback tracks whether it moved the directory in a local flag rather than inferring it from path existence: the old path can exist again for a reason other than "the move never happened" (any statement naming it recreates it), and reopening it then would serve an empty table for rows that are on disk at the new location.Restoring the handle can itself fail: moving the directory back can be impossible, and
initDB()merges options from the config and opens the database, both of which can throw. The only way the move back can fail while the old location exists is that something occupies it, and the only occupant reachable through SQL is an empty directory, becauserenameNoReplacerefuses even an empty destination. An empty directory holds no data, so the rollback removes it and retries the move once; the data and the metadata then both end up at the old location and the table recovers completely, including after a reload. Anything else is kept: a non-empty occupant was not created by this table, so the data stays where it is and the move back keeps failing.When the move back does fail, the object stays attached under the old name with a null handle while the data is still on disk,
rocksdb_diris left naming the directory that actually holds the rows, and the four read entry points (full scan,multiGetand therefore every key lookup,totalRows,totalBytes) throwROCKSDB_ERRORnaming that directory instead of answering zero rows. Reporting an empty table for data that exists is the failure mode this PR is about, so the new code must not be able to reintroduce it. To be plain about the limit of that state: it lives in the storage object only, whileDatabaseOnDisk::renameTablere-attaches the metadata under the old name, so a later reload of that table constructs a fresh object at the old path and needs manual intervention to find its rows. That is the pre-existing partial-rename classDatabaseOnDisk.cppalready documents (see below), not a state this PR can resolve without a new on-disk artefact. The write paths already refused on a null handle before this change and are untouched.TRUNCATErefuses as well, because it would recreate the database in that directory, which a reload does not open.OPTIMIZErefuses too, instead of reporting a compaction that did not run. ADROPin that state removes the metadata path and leaves the directory that holds the rows, which keeps them recoverable by attaching an explicit-path table onto it; deleting it instead would turn a recoverable orphan into data loss, andDROP DATABASErefuses withDATABASE_NOT_EMPTYnaming the leftover. The pre-existing null-handle state produced by a failedTRUNCATEreopen keeps its current behaviour deliberately (it is pinned by04330_rocksdb_truncate_drop_null_ptr.sh): there the data really was wiped, so an empty answer is correct.Second hunk: a
catch (...)inDatabaseOnDisk::renameTable. That function detaches the table and then calls the unrestricted virtualtable->rename(...), but it only handlesDB::ExceptionandPoco::Exception.std::filesystem::filesystem_errorderives fromstd::system_error, not fromPoco::Exception, so it escapes both handlers, and the only caller'scatch (...)restores dependencies without re-attaching the table. The net effect of any non-Poco throw from the hook is a table that stays detached until a restart. This hole is pre-existing and shared withStorageFile::rename(barefs::create_directoriesplusfs::rename) and withDiskLocal::moveDirectory/DiskLocal::createDirectories, used byStorageLog,StorageStripeLogandMergeTreeData. It belongs in this PR because the new RocksDB override is what makes this hook throw raw filesystem errors on this path, and shipping the override without it would knowingly add a new way to detach a table. Measured with a hand-injectedfs::filesystem_errorin the override: with thecatch (...)the table stays attached and readable, without it the following query reportsUNKNOWN_TABLE. Happy to split it out if preferred.Third hunk: the
ATTACH TABLE ... FROMcall site now holds the exclusive table lock.IStorage::renameis documented as being called under that lock, andDatabaseOnDisk::renameTablehonours it, butInterpreterCreateQuery::doCreateTablepublished the table withcreateTableand then relocated it with no table lock at all. The published table is already resolvable, and the RocksDB override is the first implementation on that path that closes a live handle, so a concurrent reader could hold an iterator into a database that is about to be deleted. I take the lock before publication (taking it after would only narrow the window) and release it beforestartup(), which is not part of the rename contract. The eight otherrenameimplementations reachable at that call site (MergeTreeData,StorageReplicatedMergeTree,StorageLog,StorageStripeLog,StorageSetOrJoinBase,StorageDistributed,StorageFile, andStorageProxy) do not take a table lock insiderename, so nothing there can deadlock.Sibling coverage: RocksDB was the only offender.
git grep -n "storesDataOnDisk() const override { return true"plusgit grep -n "void rename(const String" src/Storages/shows that every other storage which stores data on disk already relocates it:StorageLog::rename,StorageStripeLog::rename,StorageSetOrJoinBase::rename,MergeTreeData::rename(andStorageReplicatedMergeTree::rename),StorageDistributed::renameOnDisk,StorageFile::rename, andStorageTableProxythroughStorageProxy::rename.StorageKeeperMapkeeps its data in Keeper and deliberately only renames in memory. So no sibling fix is owed.Behaviour changes to be aware of.
ATTACH TABLE ... FROM '<path>'for anEmbeddedRocksDBtable now actually moves the data into the table's own directory. Previously the inherited no-op left the data at the source. This is the documented intent of that call site ("Move table data to the proper place").DROP TABLEafter aRENAMEnow removes the data, because the relative path the database deletes is where the data actually is.Not fixed here (pre-existing). With the fix,
ATTACH TABLE ... FROMleaves thedata/<db>/<table>symlink of anAtomicdatabase dangling, becausetryCreateSymlinkruns beforeres->rename(...)inInterpreterCreateQuery. This is an ordering defect in the interpreter, not something this change introduces: it was measured on unmodified master withMergeTree, which already relocates its data (ATTACH TABLE default.mtatt FROM 'mtsrc/mt' ... ENGINE = MergeTreegives adata/default/mtattsymlink that does not resolve). Nothing functional reads that symlink,DROP TABLEremoves it and startup atFORCE_RESTORErecreates all of them, so it is cosmetic; it is tracked separately and the new test deliberately does not assert on it.Also pre-existing and unchanged: if the server dies between the directory move and the metadata commit, the data is at the new path while the metadata still names the old one.
DatabaseOnDisk.cppalready documents this ("we may fail after data directory move, but before metadata file creation ... require manual intervention anyway") and it is identical forStorageLogandMergeTree.Verification. New stateless test
04648_rocksdb_rename_moves_data.sh, 12 cases, plustests/integration/test_rocksdb_rename_data_lossfor three more: the four renaming directions of the table above that go throughIStorage::rename, plus the cross-databaseAtomic->Atomicrename as a non-regression control (DatabaseAtomic::renameTablehandles bothAtomicrows withrenameInMemoryonly, so they never reach the hook), a table with TTL, an explicit-path table, aread_onlyexplicit-path table,ATTACH TABLE ... FROM(asserting the reload and that the source directory is gone, because a live handle cannot see a stale path), the destination-exists case, a rawfilesystem_errorinjected through a failpoint, the double-failure case where restoring the handle also fails, which is what pins the refuse-instead-of-answer-zero behaviour, a concurrency case for the third hunk (a pauseable failpoint stopsATTACH ... FROMbetween publication and relocation, and a concurrent reader must not get rows through the handle that is about to be closed), and the two cases where the directory was moved, the reopen failed, and the old location exists again by the time the rollback runs: with an empty directory there the rollback removes it, moves the data back, and the table is readable and reloadable with all its rows; with a non-empty one the occupant is kept, the data stays at the destination, and the table refuses reads andTRUNCATEwhile naming the directory that holds its rows. In the failure cases the rename must fail and the table must either stay fully readable or refuse; it must never report zero rows. The restart is emulated withDETACH TABLE ... SYNCplusATTACH TABLE, which recreates the storage object from metadata and recomputes the data path exactly as a restart does.The test pins
optimize_trivial_approximate_count_query = 0. That is its product default, but the stateless runner randomizes it to1in half of all runs, and with1aSELECT count()is answered from RocksDB's estimated key count throughtotalRowsinstead of reading the table, so the count assertions would stop proving that the moved directory is the one being read. The destination-exists case and the two rollback cases need a directory planted under the path reported bysystem.tables.data_paths, because neither state is reachable through SQL at the required moment:renameNoReplacerefuses any existing destination, and every SQL route to occupy the old path blocks on the DDL guard the paused rename holds. Stateless tests may not write into the server data directory, so those three are integration tests. Neither fabricates part content.The test fails on a master-HEAD debug binary built from the same tree and passes with the fix; it is green over 50 randomized runs. The 22 pre-existing RocksDB stateless tests of the branch base and
test_rocksdb_options/test_rocksdb_read_onlyproduce identical results on both binaries.Workflow [PR]
Sync PR [sync-upstream/pr/112224]
Version info
26.10.1.2181-master(included in26.10and later)