Skip to content

Fix EmbeddedRocksDB data loss when RENAME changes the table data path - #112224

Merged
alexey-milovidov merged 17 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111958-rocksdb-rename-moves-data
Oct 12, 2026
Merged

alexey-milovidov merged 17 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111958-rocksdb-rename-moves-data

Conversation

@groeneai

@groeneai groeneai commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111958

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

Fixes silent data loss when an EmbeddedRocksDB table is renamed. RENAME TABLE now 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

StorageEmbeddedRocksDB declares storesDataOnDisk() as true and publishes its directory through getDataPaths(), but it never overrides IStorage::rename, so it inherited the default implementation, which only updates the StorageID and discards the new path. DatabaseOnDisk::renameTable passes 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_dir on the live table: the already open handle keeps answering correctly from the old directory. After a restart the constructor recomputes rocksdb_dir from the table's current relative_data_path and rocksdb::DB::Open runs with create_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:

case rows before restart rows after restart
Atomic -> Ordinary (as reported) 60 0
Ordinary -> Ordinary, different database 11 0
RENAME TABLE a TO b inside one Ordinary database 10 0
Ordinary -> Atomic 13 table cannot be attached
Atomic -> Atomic, different database 12 12
rename inside one Atomic database 14 14

A plain same-database RENAME TABLE a TO b in an Ordinary database already loses all data, with no deprecated flag needed once the database exists. The two Atomic rows are unaffected only incidentally: an Atomic data path is keyed on the table UUID, which rename preserves, so the recomputed string is byte-identical.

The Ordinary -> Atomic direction is worse than data loss. A fresh UUID is assigned, so the recomputed store/<new-uuid>/ does not exist, and ATTACH skips directory creation, so the open fails with Code: 555 ROCKSDB_ERROR ... No such file or directory: While mkdir if missing. While that metadata file exists, SELECT count() FROM system.tables and SHOW TABLES FROM <db> both fail with Code: 722 ASYNC_LOAD_WAIT_FAILED; unrelated queries still work, so the blast radius is table listing. This direction is also what convertOrdinaryDatabaseToAtomic uses, so the server-side database conversion path was affected too.

The fix. StorageEmbeddedRocksDB::rename closes the handle, creates the parent of the new location, moves the directory with renameNoReplace, updates rocksdb_dir, reopens through initDB(), and then calls renameInMemory. renameNoReplace is used rather than a check plus fs::rename because a plain fs::rename silently 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 in InterpreterCreateQuery.

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 a const bool implicit_path member set in the constructor rather than re-derived later by comparing strings.

On any failure the previous handle is restored before rethrowing, because DatabaseOnDisk::renameTable re-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 makes SELECT return 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, because renameNoReplace refuses 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_dir is left naming the directory that actually holds the rows, and the four read entry points (full scan, multiGet and therefore every key lookup, totalRows, totalBytes) throw ROCKSDB_ERROR naming 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, while DatabaseOnDisk::renameTable re-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 class DatabaseOnDisk.cpp already 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. TRUNCATE refuses as well, because it would recreate the database in that directory, which a reload does not open. OPTIMIZE refuses too, instead of reporting a compaction that did not run. A DROP in 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, and DROP DATABASE refuses with DATABASE_NOT_EMPTY naming the leftover. The pre-existing null-handle state produced by a failed TRUNCATE reopen keeps its current behaviour deliberately (it is pinned by 04330_rocksdb_truncate_drop_null_ptr.sh): there the data really was wiped, so an empty answer is correct.

Second hunk: a catch (...) in DatabaseOnDisk::renameTable. That function detaches the table and then calls the unrestricted virtual table->rename(...), but it only handles DB::Exception and Poco::Exception. std::filesystem::filesystem_error derives from std::system_error, not from Poco::Exception, so it escapes both handlers, and the only caller's catch (...) 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 with StorageFile::rename (bare fs::create_directories plus fs::rename) and with DiskLocal::moveDirectory / DiskLocal::createDirectories, used by StorageLog, StorageStripeLog and MergeTreeData. 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-injected fs::filesystem_error in the override: with the catch (...) the table stays attached and readable, without it the following query reports UNKNOWN_TABLE. Happy to split it out if preferred.

Third hunk: the ATTACH TABLE ... FROM call site now holds the exclusive table lock. IStorage::rename is documented as being called under that lock, and DatabaseOnDisk::renameTable honours it, but InterpreterCreateQuery::doCreateTable published the table with createTable and 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 before startup(), which is not part of the rename contract. The eight other rename implementations reachable at that call site (MergeTreeData, StorageReplicatedMergeTree, StorageLog, StorageStripeLog, StorageSetOrJoinBase, StorageDistributed, StorageFile, and StorageProxy) do not take a table lock inside rename, so nothing there can deadlock.

Sibling coverage: RocksDB was the only offender. git grep -n "storesDataOnDisk() const override { return true" plus git 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 (and StorageReplicatedMergeTree::rename), StorageDistributed::renameOnDisk, StorageFile::rename, and StorageTableProxy through StorageProxy::rename. StorageKeeperMap keeps 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 an EmbeddedRocksDB table 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 TABLE after a RENAME now removes the data, because the relative path the database deletes is where the data actually is.
  • A user who relied on the orphaned-data behaviour (rename a table, then recreate one under the old name and find the old rows) sees a change. That is the bug being fixed.
  • No on-disk or metadata format change, so a downgrade is safe: an older binary reads the table at its new path exactly as if the table had been created there.

Not fixed here (pre-existing). With the fix, ATTACH TABLE ... FROM leaves the data/<db>/<table> symlink of an Atomic database dangling, because tryCreateSymlink runs before res->rename(...) in InterpreterCreateQuery. This is an ordering defect in the interpreter, not something this change introduces: it was measured on unmodified master with MergeTree, which already relocates its data (ATTACH TABLE default.mtatt FROM 'mtsrc/mt' ... ENGINE = MergeTree gives a data/default/mtatt symlink that does not resolve). Nothing functional reads that symlink, DROP TABLE removes it and startup at FORCE_RESTORE recreates 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.cpp already documents this ("we may fail after data directory move, but before metadata file creation ... require manual intervention anyway") and it is identical for StorageLog and MergeTree.

Verification. New stateless test 04648_rocksdb_rename_moves_data.sh, 12 cases, plus tests/integration/test_rocksdb_rename_data_loss for three more: the four renaming directions of the table above that go through IStorage::rename, plus the cross-database Atomic -> Atomic rename as a non-regression control (DatabaseAtomic::renameTable handles both Atomic rows with renameInMemory only, so they never reach the hook), a table with TTL, an explicit-path table, a read_only explicit-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 raw filesystem_error injected 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 stops ATTACH ... FROM between 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 and TRUNCATE while 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 with DETACH TABLE ... SYNC plus ATTACH 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 to 1 in half of all runs, and with 1 a SELECT count() is answered from RocksDB's estimated key count through totalRows instead 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 by system.tables.data_paths, because neither state is reachable through SQL at the required moment: renameNoReplace refuses 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_only produce identical results on both binaries.


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

Version info

  • Merged into: 26.10.1.2181-master (included in 26.10 and later)

groeneai and others added 7 commits July 27, 2026 13:35
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal review before opening this PR: 6 rounds, 32 findings, 19 AGREE / 12 DISAGREE adjudicated

Before opening this PR I put the change through an independent cold code review plus a
second-model gate, in six rounds, and adjudicated every finding against the code. Five
rounds produced a fix; the sixth was clean. Across the six rounds: 15 findings from the
cold review, 13 from the gate, plus 4 from an earlier approach-level gate on the plan.
19 AGREE, 12 DISAGREE, 3 dropped as verified-clean on re-derivation.

Every AGREE below is fixed in the diff and pinned by a test case. Every DISAGREE is
backed by a code citation or a measurement.

The five findings that changed the design

Each of these came from a review pass over the previous round's fix, which is why they
compound: closing one hole created behaviour that nothing pinned.

# Finding Verdict and what changed
❌ The override closes the handle before moving the directory, so if the rollback's reopen also fails the caller re-attaches the table with a null handle, and the read paths then answer EMPTY: initializePipeline substitutes NullSource, multiGet returns {}. SELECT count() reports 0 on a table whose rows are intact on disk, which is the exact symptom this PR removes, reachable through the PR's own new code. AGREE - an unrecoverable reopen is now recorded, and the four read entry points (full scan, multiGet and therefore every key lookup, totalRows, totalBytes) refuse with ROCKSDB_ERROR naming the directory that holds the rows.
❌ That refuse-instead-of-answer state had no committed test. The failpoint added for the previous round throws before the move, so the rollback reopens an untouched directory and succeeds; reverting all four guards left the test green. AGREE - a re-arming failpoint applied to both reopen attempts reaches the state deterministically. Reverting the guards now fails the test, per guard: reverting only the full-scan guard moves only the full-scan line.
❌ ATTACH TABLE ... FROM publishes the table with createTable and only then relocates its directory, with no table lock at all. The published table is already resolvable, and this 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 closed. AGREE - the exclusive table lock is now held across publication and relocation, and released before startup(), which is not part of the rename contract. A pauseable failpoint stops the attach inside that window and asserts a concurrent reader gets no rows; deleting just the lockExclusively statement moves exactly that one assertion.
❌ The rollback inferred "did I move the directory?" 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 serves an empty table for rows that are on disk at the new location. AGREE - the rollback now tracks the relocation in a local flag instead of inferring it from paths.
❌ The resulting fail-closed state lives only in memory, while the caller re-attaches metadata naming the OLD path, so a reload constructs a fresh object there with create_if_missing = true and can again answer zero rows over data that exists. AGREE on the defect, DISAGREE on the proposed remedy. The only SQL-reachable way the move back can fail while the old path exists is an EMPTY directory occupying it, because renameNoReplace refuses even an empty destination. An empty directory holds no data, so the rollback now removes it and retries the move once: data and metadata end up together at the old path and the table recovers, including after a reload. A non-empty occupant is kept and the fail-closed state stands, with its reload limit disclosed plainly in the description rather than promised away. I did not make the unusable state durable, which is what the finding asked for: that needs a new on-disk artefact for a split state DatabaseOnDisk.cpp already documents as requiring manual intervention, and which every sibling storage on the same hook reaches with no rollback at all.

Coverage and hygiene findings

# Finding Verdict
⚠️ The new catch (...) in DatabaseOnDisk::renameTable was not exercised: case 10's pre-existing-destination path raises a ClickHouse Exception, which the pre-existing first handler already catches, so reverting the new handler left the test green. AGREE - a failpoint now raises a raw std::filesystem::filesystem_error from the rename, and a case proves the table stays attached and readable.
⚠️ The test did not pin optimize_trivial_approximate_count_query, which the stateless runner randomizes at 50%. With it on, SELECT count() is answered from RocksDB's estimated key count instead of reading the table, so in about half of all runs the count assertions stopped demonstrating which directory is read, which is this PR's whole subject. AGREE - pinned to 0 with a comment recording why the pin is load-bearing even though it matches the product default. Measured: with 0 the plan reads ReadFromEmbeddedRocksDB / FullScan and read_rows = 37; with 1 it is ReadFromPreparedSource (Optimized trivial count) and read_rows = 1, on a 37-row table.
⚠️ Case 9 (ATTACH ... FROM) did not prove the data had actually moved: a live handle keeps answering from wherever it was opened. AGREE - the case now asserts the reload and that the source directory is gone.
💡 Two DROP TABLE statements in the test are load-bearing (the next statement reopens the same directory), and CI's ignore_drop_queries_probability turns a DROP of an on-disk table into a no-op with p=0.2. AGREE - those statements now pin ignore_drop_queries_probability = 0.
💡 The unusable-handle flag was cleared only on the rename success path, so it survived an unrelated successful TRUNCATE recovery and could later attribute a null handle to a failed rename. AGREE - cleared on any successful open, which makes the flag mean what its comment says.
💡 The test left tables behind in its own database, and the directories it fabricates were not removed. AGREE - fixed.

Where I disagreed, with the evidence

# Finding Why I disagree
❌ A failed ATTACH ... FROM move leaves a committed table pointing at a destination it never reached, with no rollback in doCreateTable. Real, but pre-existing and not made newly reachable here. That call site already invokes throwing relocation hooks for every other on-disk storage: MergeTreeData::rename throws DIRECTORY_ALREADY_EXISTS outright, StorageLog::rename and StorageStripeLog::rename go through DiskLocal::moveDirectory (a bare fs::rename), StorageSetOrJoinBase::rename uses replaceFile, StorageFile::rename is fs::create_directories plus fs::rename. The source data is not lost either: the attach path keeps the rewritten source path as the storage's construction path, so a failed move is recoverable by re-attaching. Transactional rollback there would change behaviour for five other engines, so it is disclosed in the description and tracked separately.
⚠️ renameNoReplace degrades to an existence check plus fs::rename where atomic no-replace is unavailable (WSL, Docker on macOS), so an empty destination created inside that window could be replaced. Use a strict primitive that fails closed instead. The mechanism is correct and I verified it, including that rename() onto an existing empty directory does clobber it while onto a non-empty one it fails with ENOTEMPTY. I disagree with the remedy on three grounds. There is no strict primitive to call: atomicRename.h exposes only supportsAtomicRename, renameNoReplace and renameExchange, so this means either a new shared primitive with six other in-tree callers, which is a separate change, or refusing the rename outright on those platforms, which is a functional regression where it works today. This PR is already strictly safer than every sibling on the same hook, all of which use weaker primitives unconditionally on every platform. And the window has no in-server writer: the only creators of a table-level data directory are this engine's constructor under mode < ATTACH and its own truncate, while RENAME holds a DDL guard on both the source and destination names plus the exclusive table lock on the source, so a concurrent CREATE or ATTACH of the destination name is serialized behind it.
⚠️ The key-lookup assertion still passes if the query silently falls back to the full-scan guard. Reverting only the full-scan guard leaves the key-lookup line at 1, and reverting all four moves both lines; the two mutants together discriminate the paths, so the assertion is bound to multiGet.
💡 The changelog category should be Critical Bug Fix because the description says silent data loss. I do not select Critical Bug Fix on my own initiative; that is the maintainers' call. The description states the severity in full, including the Ordinary to Atomic direction that leaves a permanently unloadable table, so relabelling is a one-word edit if preferred.

Checked independently and found correct

Recorded here rather than as findings: member initialisation order for the new
implicit_path member, and that it is set before the constructor rewrites the directory
string so it records intent rather than re-deriving it later; all three rollback branches
leaving the recorded directory consistent with where the data actually is; EXCHANGE TABLES and same-Atomic-database renames not reaching the override at all, which is why
the Atomic rows of the table in the description are controls and not coverage; every
write path already refusing on a null handle; totalRows and totalBytes throwing not
being able to break system.tables, which wraps both in a handler; system.rocksdb
correctly still receiving nullptr, since it treats that as "skip this table"; a no-op
OPTIMIZE and absent statistics being the only other null-handle observers, neither of
which reports row data; the eight rename implementations reachable at the ATTACH ... FROM call site all being lock-free inside rename, so the new lock cannot deadlock any
of them; and the sibling sweep over storages that store data on disk, which found RocksDB
to be the only offender.

One coverage boundary is deliberate: the totalRows and totalBytes guards get no
assertion, because both functions return early under
optimize_trivial_approximate_count_query = 0, which the test pins for the reason above.
Asserting them would re-open the estimate path.

Happy to split the catch (...) hunk in DatabaseOnDisk::renameTable out into its own PR
if you would rather keep this one to the storage change.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on demand. CREATE DATABASE ord ENGINE = Ordinary + CREATE TABLE default.rocks (...) ENGINE = EmbeddedRocksDB PRIMARY KEY k + INSERT ... numbers(60) + RENAME TABLE default.rocks TO ord.rocks + DETACH TABLE ord.rocks SYNC; ATTACH TABLE ord.rocks; -> SELECT count() returns 0 instead of 60. DETACH SYNC/ATTACH recreates the storage object from metadata, exactly as a restart does.
b Root cause explained? StorageEmbeddedRocksDB declares storesDataOnDisk() as true and publishes getDataPaths() -> {rocksdb_dir} but never overrides IStorage::rename, so it inherited the default whose body is only renameInMemory(...) and which discards new_path_to_table_data. DatabaseOnDisk::renameTable passes that path with the comment "It will move data to new path (if it stores data on disk)". Nothing re-derives rocksdb_dir on the live table, so the open handle keeps answering from the old directory; after a restart the constructor recomputes it from the new relative_data_path and rocksdb::DB::Open runs with create_if_missing = true, creating an empty database. That flag turns a stale path into silent data loss.
c Fix matches root cause? Yes. The engine now implements the hook whose documented job is to move the data: close handle, create parent, renameNoReplace, update rocksdb_dir, initDB(), renameInMemory. No widened bound, no no-random-* tag, no defensive check masking an upstream problem. renameNoReplace rather than check-plus-fs::rename because a bare fs::rename silently clobbers an existing empty destination (measured, ec = 0) and check-then-rename is racy.
d Test intent preserved / new tests added? No existing test weakened. New stateless test 04648_rocksdb_rename_moves_data.sh with 15 cases: all six database-engine directions (including a labelled non-regression Atomic -> Atomic control), a ttl > 0 table, an explicit-path table, a read_only explicit-path table, ATTACH TABLE ... FROM, the destination-exists case (rename must fail and the table must stay attached and fully readable), a failpoint-injected raw std::filesystem::filesystem_error case pinning the caller's re-attach on a non-ClickHouse exception, and a case in which the rollback reopen fails too, pinning that reads then refuse (ROCKSDB_ERROR) on both the full-scan and the key-lookup entry point while a reload still recovers every row. optimize_trivial_approximate_count_query is pinned to 0 so the SELECT count() assertions read the table instead of being answered from RocksDB's estimated key count, which the stateless runner would otherwise randomize into half of all runs. 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. Case 13 pins the ATTACH ... FROM publication-to-relocation window with a PAUSEABLE_ONCE failpoint: a concurrent reader must not read through the handle the relocation is about to close. Cases 14 and 15 pin the rollback itself: a second PAUSEABLE_ONCE failpoint stops a failed rename right before its rollback and the test recreates the old location in that window. In case 14 it is an empty directory, so the rollback removes it, moves the data back, and the table must be readable and reloadable with all its rows while the destination is gone; in case 15 it holds a file, so the occupant must survive, the data must stay at the destination, and reads must refuse while naming that destination rather than reopening an empty directory and answering zero rows.
e Both directions demonstrated? Yes. On a pristine master-HEAD debug binary built from this branch's exact merge-base the test FAILS (1/2/3 reloaded 0, case 4 cannot be attached with Code: 555 ROCKSDB_ERROR ... While mkdir if missing, 6 ttl reloaded 0, 9 attach from moved 0, 10 rename refused 0 and 11 rename failed 0, with the post-state lines of cases 10 and 11 empty). With the fix it PASSES, and 50/50 randomized runs are green (50 passed, 0 failed). The refusal behaviour is pinned in both directions too: deleting all four read guards, or only the flag write, turns 12 full scan refuses and 12 key lookup refuses from 1 to 0, and deleting only the full-scan guard moves the first line while leaving the second at 1. Removing only the lockExclusively call moves exactly 13 concurrent read excluded from 1 to 0; an implementation that reassigns rocksdb_dir while keeping the source handle open leaves the old case-9 lines at 7/1 and moves only the two new ones to 0. Restoring the rollback's old path-existence test (while keeping everything else) moves case 14's three lines to 0/0/0 and case 15's full scan refuses, error names destination and key lookup refuses from 1 to 0, so both cases measure the flag and not something incidental. Dropping the empty-directory removal and retry moves case 14's readable/reloadable/destination-gone lines and leaves case 15 untouched; relaxing the emptiness test to "is a directory" moves 15 occupant kept from 1 to 0 and leaves case 14 untouched, so the fs::is_empty guard is load-bearing rather than decorative.
f Fix is general across code paths? Sibling sweep by capability predicate: git grep -n "storesDataOnDisk() const override { return true" intersected with git grep -n "void rename(const String" src/Storages/. StorageLog, StorageStripeLog, StorageSetOrJoinBase, MergeTreeData (+StorageReplicatedMergeTree), StorageDistributed, StorageFile and StorageTableProxy (via StorageProxy::rename) all already relocate; StorageKeeperMap keeps its data in Keeper. RocksDB was the only offender, so no sibling fix is owed. Both callers of IStorage::rename are covered: DatabaseOnDisk::renameTable and InterpreterCreateQuery (ATTACH ... FROM, test case 9). DatabaseAtomic::renameTable calls renameInMemory directly because its path is UUID-keyed. Both callers now also honour the documented "called under exclusive lock" precondition: DatabaseOnDisk::renameTable already did, and the ATTACH ... FROM call site in InterpreterCreateQuery now takes it too. Every other engine reaching that call site was read and none takes a table lock inside its own rename, so the added window cannot deadlock them.
g Fix generalizes across inputs (params/datatypes/wrappers)? This is a path/lifecycle change, so type wrappers do not apply. The parameter matrix is covered instead: all six Atomic/Ordinary rename directions, ttl > 0 (reopens through rocksdb::DBWithTTL), explicit rocksdb_dir argument, read_only = 1, ATTACH ... FROM, and a pre-existing destination directory (including the empty-directory boundary, which a bare fs::rename would silently clobber).
h Backward compatible? Yes. No setting, no serialization or metadata format change, so no SettingsChangesHistory.cpp entry. Downgrade is safe: an older binary reads the table at its new path exactly as if it had been created there. One intentional behaviour change (a cross-path rename now moves data instead of orphaning it) is the bug being fixed; ATTACH ... FROM becoming functional for this engine is documented intent of that call site. Both are disclosed in the PR description.
i Invariants and contracts preserved? The handle is closed and reopened under rocksdb_ptr_mx, and both callers hold an exclusive table lock across the whole rename (DatabaseOnDisk::renameTable already did; the ATTACH ... FROM call site in InterpreterCreateQuery now takes it before publishing the table and releases it before startup()), so no concurrent reader, writer or bulk sink can observe the intermediate state (EmbeddedRocksDBBulkSink captures getDataPaths()[0] at construction, which that lock excludes). On every failure path the previous handle is restored before rethrowing, so the table the caller re-attaches is usable; a secondary failure during rollback is logged and the original exception is rethrown. The rollback records in a local flag whether it moved the directory instead of inferring it from path existence, so a source directory recreated concurrently cannot make it skip the move-back and reopen an empty database over rows that are at the new location. When the old location is occupied by an empty directory, which is the only occupant reachable through SQL, the rollback removes it and retries once, so the data and the metadata end up together at the old location and the table recovers even after a reload; a non-empty occupant is never removed, and then the object keeps rocksdb_dir naming the directory that holds the data and refuses reads (that state is in-memory only, so a later reload of that table needs manual intervention, which is the pre-existing partial-rename class DatabaseOnDisk.cpp documents and the PR description states plainly). If even the rollback reopen fails the table is marked as having no usable handle, and the four READ paths (initializePipeline full scan, multiGet, totalRows, totalBytes) then throw ROCKSDB_ERROR naming the directory instead of answering zero rows over intact on-disk data; the teardown paths (truncate, drop) keep tolerating a null handle as before. That flag is read and written only under rocksdb_ptr_mx, and the original exception still propagates unchanged. The added catch (...) in DatabaseOnDisk::renameTable upholds that function's own detach/re-attach contract for exceptions that are neither DB::Exception nor Poco::Exception; pinned by test case 11, which injects a raw std::filesystem::filesystem_error through a failpoint (with the handler the table stays attached and readable, without it the next query reports UNKNOWN_TABLE). The unusable-handle state itself is pinned by test case 12 through a second, REGULAR failpoint (rocksdb_rename_fail_reopen) that fails both the forward reopen and the rollback reopen of one rename: the full scan and the key lookup must both raise ROCKSDB_ERROR, and a reload must still recover every row, which is what distinguishes "this object cannot serve the data" from "the data is gone". The failpoint sits in a private initDBForRename() wrapper rather than in initDB() itself, so it is unreachable from the constructor and from truncate() and cannot be tripped by a concurrent test (measured: while it is armed, CREATE TABLE and TRUNCATE both succeed). handle_unusable is now cleared at the end of every successful initDB() instead of only on the rename success path, so its meaning is exactly "the most recent open attempt failed and could not be recovered" and a stale true cannot survive a later successful reopen.

Session id: cron:clickhouse-impl-slot-5:20260728-043001

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @GrigoryPervakov @tuanpach — could you review this? StorageEmbeddedRocksDB declares storesDataOnDisk() but never overrode IStorage::rename, so the new data path was discarded and after a restart the table opened a freshly created empty RocksDB while the real rows stayed orphaned under the old path; the override now moves the directory with renameNoReplace and restores the handle on any failure. It also adds a catch (...) to DatabaseOnDisk::renameTable (a raw filesystem_error from the hook escaped both existing handlers and left the table detached) and makes the ATTACH TABLE ... FROM call site hold the exclusive table lock across relocation.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2e30b0f]

Summary: ✅


AI Review

Summary

This PR fixes the main EmbeddedRocksDB rename data-loss bug by moving implicit RocksDB directories during RENAME, restoring the old handle on rollback, and failing closed when the handle cannot be restored. The remaining correctness gap is in ATTACH TABLE ... FROM: the destination table is still published before relocation runs, so a relocation failure can return an exception after the destination table has already been attached.

Findings

❌ Blockers

  • [dismissed by author -- https://github.com/Fix EmbeddedRocksDB data loss when RENAME changes the table data path #112224#discussion_r3663728803] [src/Interpreters/InterpreterCreateQuery.cpp:2793] ATTACH TABLE ... FROM still calls database->createTable() before res->rename(...). If relocation then throws, the statement returns an exception but the destination table stays attached, so retries hit TABLE_ALREADY_EXISTS and the failed DDL still leaves visible side effects. I still consider this real because this PR makes that post-publication failure path reachable for EmbeddedRocksDB, not just for other engines.
  • Suggested fix: keep the destination unpublished until relocation succeeds, or add rollback after database->createTable() so a failing res->rename(...) detaches/drops the just-created destination table and removes its metadata before rethrowing.
Final Verdict

❌ Changes required before merge: EmbeddedRocksDB rename/reload behavior itself looks fixed, but ATTACH TABLE ... FROM is still not exception-safe once relocation can fail after publication.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 28, 2026
/// 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);

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.

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.

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.

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::drop is disk->removeRecursive(table_path) (src/Storages/StorageLog.cpp:964-967).
  • MergeTreeData::dropAllData ends in disk->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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 113/131 (86.26%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1ba4edb

CI has fully finished on this head: 174 check-runs, all completed, 0 queued, 0 in progress,
Finish Workflow success at 11:34:53Z. One failing check (155 success, 18 skipped, 1 failure).

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan) / UndefinedBehaviorSanitizer STID 0250-4a9f trunk UBSan signed overflow, not PR-caused #112045 (external, open)
src/Functions/toStartOfInterval.cpp:293:80: runtime error: signed integer overflow:
-9223372036854775807 + -7200000000000 cannot be represented in type 'Int64'

Not PR-caused: this PR changes src/Storages/RocksDB/StorageEmbeddedRocksDB.{cpp,h},
src/Databases/DatabaseOnDisk.cpp, src/Interpreters/InterpreterCreateQuery.cpp,
src/Common/FailPoint.cpp and one new stateless test. It touches nothing under src/Functions/, and
toStartOfInterval has no path to EmbeddedRocksDB RENAME. Breadth over 30 days keyed on the frame
toStartOfInterval.cpp:293: 83 hits across 70 distinct pull requests, including 8 rows on master, so it
is a pre-existing trunk defect rather than anything this branch introduced.

Owner justification: #112045 is titled for exactly this defect and its diff is
src/Functions/toStartOfInterval.cpp plus a regression test, adding an overflow check to the
origin + offset composition that is the addition failing above. It is open and not merged, so there is
nothing to pick up by merging master.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7ca4bba

Every failure below has an owner: a fixing PR (ours 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.

CI is fully finished on this head: 175 checks, 0 incomplete, 156 jobs OK, 18 skipped
(every skip carries a reason), 0 dropped in the praktika report, so the run carries real coverage.

Check / test Reason Owner / fixing PR
Stress test (arm_debug) / Hung check failed, possible deadlock found deadlock, not PR-caused: the stuck query is DROP TABLE prometheus (elapsed 743s, is_cancelled=1), blocked in DatabaseCatalog::waitTableFinallyDropped under InterpreterDropQuery::waitForTableToBeActuallyDroppedOrDetached, with DROP DATABASE ... SYNC and DETACH DATABASE queued behind its DDLGuard. The database is the one created by 04811_promql_topk_bottomk_limitk. This PR touches only EmbeddedRocksDB and its tests, and no TimeSeries code. fixing PR #114326 (external, open)

Build (arm_release) / Post Hooks shows FAIL in the CI database while the GitHub check
concluded success; that is reporting-sink bookkeeping, not a test failure, so it is not a ledger line.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112224&sha=7ca4bbac546a7da2e25c231f530c7f02c8611cda&name_0=PR&name_1=Stress%20test%20%28arm_debug%29

Session id: cron:our-pr-ci-monitor:20260811-180000

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

See the job log for details.

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 30 not_sure 223 271 +21.5% <0.0001 aggregation: This GROUP BY over MergeTree data never touches the RocksDB rename or ATTACH FROM code this PR changes. CPU time is flat (2347 vs 2342 ms), and the +21.5% wall-clock is inside master's normal range.
⚠️ 31 not_sure 262 313 +19.5% <0.0001 aggregation: This GROUP BY over MergeTree data does not execute the changed RocksDB or DDL paths. CPU time is flat (2795 vs 2792 ms), and the +19.5% wall-clock stays within master's normal range.

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
  • StressHouse run: 1e105cfb-782e-41e4-8f97-4de5ebf6e1c6
  • MIRAI run: dd1611a0-1add-4733-9fde-e56a46bc293a
  • PR check IDs:
    • clickbench_928833_1791755494
    • clickbench_928839_1791755494
    • clickbench_928845_1791755494
    • tpch_adapted_1_official_928856_1791755494
    • tpch_adapted_1_official_928867_1791755494
    • tpch_adapted_1_official_928904_1791755494

@clickhouse-gh clickhouse-gh Bot added the comp-foreign-db Connectivity to external databases (ODBC/JDBC, MySQL, PostgreSQL, etc.). label Sep 4, 2026
…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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - bf9fa79

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.

CI is fully finished on this head: 176 checks, 0 incomplete, 158 pass, 15 skipped, 3 failed.
The CI database holds 272,996 OK rows and zero FAIL/ERROR/UNKNOWN rows for this commit,
so no test failed here: the one failing job died before it ran anything.

Check / test Reason Owner / fixing PR
Build profile diff infra, nothing tested: has_pr_data raised RuntimeError: CI logs cluster query failed on the binary_sizes read and aborted the job before any comparison #120121 (mine, open), which turns a transient cluster read failure into a skipped comparison instead of a failed one; #118708 (mine, open) makes that message carry the cluster's own error
CH Inc sync - CH Inc sync (private, not actionable by me)

PR is the praktika aggregator over the two rows above, not a separate failure.

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112224&sha=bf9fa793c458294f798dab3551f5191a025ecaee&name_0=PR&name_1=Build%20profile%20diff

Session id: cron:our-pr-ci-monitor:20260915-190256

groeneai and others added 2 commits September 26, 2026 03:24
… 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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cb97df8

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
Upgrade check (amd_release) / Error message in clickhouse-server.log release-side metadata round-trip, not PR-caused. The pre-upgrade v26.9.2.8 server leaves t_pfl_05079 as AggregateFunction(quantile('0.5'), Float64), and the upgraded server refuses to attach it in AsyncLoader::worker (Code 70 CANNOT_CONVERT_TYPE). 78 PRs carry this signature since 2026-09-21 (21 in the last 24 hours), and no master run does #121590 (external, merged into 26.9, not yet in a published release)
Upgrade check (amd_release) / Cannot check whether the mutation submitted before the upgrade was finished same cause: the system.mutations probe dies with ASYNC_LOAD_WAIT_FAILED behind the same failed t_pfl_05079 load #121590 (external, merged into 26.9)
Mergeable Check, PR rollups, red only because of the two rows above #121590 (external, merged into 26.9)
CH Inc sync - CH Inc sync (private, not actionable by me)

Fix presence, measured: this job installed v26.9.2.8-stable as the previous release, and that is
still the newest published 26.9 release (2026-09-22 14:53Z). #121590 merged into 26.9 at 16:29Z
the same day, so the installed package predates it. Merging master cannot pick it up, because the
fix lives on 26.9. This PR changes how EmbeddedRocksDB handles RENAME and restart. It touches
no aggregate function parameter parsing and no Memory table metadata.

All 176 check runs completed (157 pass, 15 not selected, 4 red) and Finish Workflow is green.

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 alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Somewhat excessive, but ok.

@alexey-milovidov alexey-milovidov self-assigned this Oct 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 12, 2026
Merged via the queue into ClickHouse:master with commit a02f178 Oct 12, 2026
163 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 12, 2026
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-foreign-db Connectivity to external databases (ODBC/JDBC, MySQL, PostgreSQL, etc.). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

EmbeddedRocksDB table loses all data after RENAME to another database and a restart

4 participants