Skip to content

Fix EmbeddedRocksDB backup to include table data - #109327

Merged
qoega merged 24 commits into
ClickHouse:masterfrom
groeneai:fix-embedded-rocksdb-backup-109213
Sep 14, 2026
Merged

qoega merged 24 commits into
ClickHouse:masterfrom
groeneai:fix-embedded-rocksdb-backup-109213

Conversation

@groeneai

@groeneai groeneai commented Jul 3, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #109213

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

Fix BACKUP of EmbeddedRocksDB tables. Previously only the table metadata was stored in the backup and the actual data was silently dropped, so RESTORE produced an empty table. The backup now includes all key-value pairs and restores them correctly.

Description

StorageEmbeddedRocksDB did not override backupData() / restoreDataFromBackup(), so it fell through to the no-op IStorage defaults: BACKUP captured only metadata/<db>/<table>.sql and no data files, and RESTORE reported success while producing an empty table (silent data loss).

Reproduction before the fix
CREATE TABLE rdb (k UInt64, v String) ENGINE = EmbeddedRocksDB PRIMARY KEY k;
INSERT INTO rdb SELECT number, 'val_' || toString(number) FROM numbers(1000);
BACKUP TABLE rdb TO File('rdb_backup');   -- backup contains only metadata/default/rdb.sql
DROP TABLE rdb SYNC;
RESTORE TABLE rdb FROM File('rdb_backup');
SELECT count() FROM rdb;                  -- 0 (data lost)

Fix

Implement both entrypoints as a logical dump, following the existing StorageKeeperMap / StorageMemory pattern:

  • backupData() iterates every key-value pair over an implicit RocksDB snapshot and writes them as length-prefixed binary records into one compressed data.bin entry, produced lazily via IBackupEntriesLazyBatch.
  • restoreDataFromBackup() reads data.bin back and re-inserts the pairs with a rocksdb::WriteBatch. Restoring into a non-empty table is rejected unless allow_non_empty_tables is set, matching the other engines.
  • Tables sharing one rocksdb_dir (one writable plus read_only siblings) elect a single owner, so the shared database is dumped and replayed once, and finalizeRestoreFromBackup() reopens the siblings' handles so they see the restored rows. That step holds only a shared table lock, so a full scan may be iterating a handle as it is replaced: rocksdb_ptr is now a shared_ptr the reading source keeps alive for its iterator's lifetime, and the reopen releases its reference instead of closing, since closing a database under a live iterator aborts inside RocksDB. A running scan keeps the snapshot it started on.

Keys and values are already raw serialized strings, so bytes are copied verbatim and every key layout and value type round-trips without type-specific handling.

Restoring into a shared directory that no longer exists is unsupported: a read_only handle can only open an existing RocksDB directory, which is a property of the engine.

Coverage: 04401_rocksdb_backup_restore for the round-trip, the non-empty guard, composite keys and complex value types; tests/integration/test_rocksdb_backup_restore for the on-disk rocksdb_dir cases, including the shared-dir dedup, the read_only, ttl and schema rejections, and a RESTORE racing a full scan of a sibling.


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

StorageEmbeddedRocksDB did not override backupData()/restoreDataFromBackup(),
so BACKUP only captured table metadata and RESTORE silently produced an empty
table (data loss). Implement a logical dump: back up all key/value pairs into a
single compressed data.bin entry and re-insert them on restore. RocksDB stores
keys/values as raw serialized strings, so the bytes are copied verbatim and every
primary key layout and value type round-trips without type-specific handling.

Closes: ClickHouse#109213

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE rdb (k UInt64, v String) ENGINE = EmbeddedRocksDB PRIMARY KEY k; INSERT ... 1000 rows; BACKUP TABLE rdb TO File('rdb_backup'); DROP TABLE rdb; RESTORE TABLE rdb FROM File('rdb_backup'); SELECT count() deterministically returns 0 on the unmodified binary (build id 25a7feb0), and the backup contains only metadata/default/rdb.sql.
b Root cause explained? Yes. StorageEmbeddedRocksDB does not override IStorage::backupData()/restoreDataFromBackup(). IStorage's defaults are no-ops (backup writes nothing; restore only asserts the folder is empty). So BACKUP captures only the .sql metadata and RESTORE re-creates an empty RocksDB, silently discarding all rows.
c Fix matches root cause? Yes. Overriding the two entrypoints is exactly the missing piece. backupData() dumps every key/value pair into a compressed data.bin entry; restoreDataFromBackup() reads them back and re-inserts with a WriteBatch. Mirrors the established StorageKeeperMap/StorageMemory logical-dump pattern.
d Test intent preserved / new tests added? New regression test 04401_rocksdb_backup_restore added: full round-trip (1000 rows, verified via count + sum + cityHash), non-empty-table guard (CANNOT_RESTORE_TABLE), composite primary key, complex value types (Nullable/Array/Map), and empty table. It fails (0 rows) on the pre-fix binary and passes with the fix. No existing test weakened.
e Both directions demonstrated? Yes. Pre-fix binary: RESTORE yields 0 rows / backup has no data file. Post-fix binary (build id ae1c8e55): backup contains data/default/rdb/data.bin, RESTORE yields all 1000 rows; 100k-row round-trip also matches exactly (count+sum+hash).
f Fix is general across code paths? Yes. RocksDB has a single storage; there are no sibling read/write paths to patch. Both directions (backup and restore) are implemented symmetrically. Not a defensive symptom-guard — it implements the genuinely missing feature.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. RocksDB stores keys/values as raw serialized byte strings, so the dump copies the bytes verbatim — independent of column type. Verified round-trip with single and composite primary keys and with Nullable, Array, Map values, plus empty and 100k-row tables. TTL/read_only opening is unchanged.
h Backward compatible? Yes. Pure additive fix. No setting default changed (no SettingsChangesHistory.cpp entry needed). The backup on-disk layout only gains a data.bin under data/<db>/<table>/; old (data-less) backups still restore — restore is a no-op when data.bin is absent, preserving today's empty-restore behavior for pre-existing backups.
i Invariants and contracts preserved? Yes. The scan holds a shared lock on rocksdb_ptr_mx for the whole iteration (keeps the handle alive, excludes drop/truncate, does not block concurrent inserts) and reads from an implicit RocksDB snapshot for a consistent view; TSA_GUARDED_BY(rocksdb_ptr_mx) is respected. Restore uses addDataRestoreTask and the non-empty-table guard exactly like StorageKeeperMap/StorageMemory.

Session id: cron:clickhouse-worker-slot-2:20260703-155000

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @kssenii @vitlibar — could you review this? StorageEmbeddedRocksDB never overrode backupData()/restoreDataFromBackup(), so BACKUP stored only metadata and RESTORE silently produced an empty table (#109213). This adds a logical key-value dump (data.bin) using the same IBackupEntriesLazyBatch pattern as KeeperMap/Memory, plus a regression test.

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

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [418b437]

Summary: ✅


AI Review

Summary

This PR implements EmbeddedRocksDB data backup/restore, including shared rocksdb_dir coordination and the read_only restore edge cases. The current branch still produces a self-inconsistent backup for a supported shared-directory configuration with mixed ttl, so I cannot approve it yet.

Findings

❌ Blockers

  • [src/Storages/RocksDB/StorageEmbeddedRocksDB.cpp:646-662] The shared-dir dedup path only replaces data.bin with the writable owner's payload, but each table still writes its own ttl.txt and schema.txt first. tests/integration/test_rocksdb_read_only/test.py:37-63 still allows a writable EmbeddedRocksDB(0, dir) to coexist with a read_only EmbeddedRocksDB(10, dir, 1) on the same directory, so BACKUP DATABASE of that pair records ttl.txt = 10 for the read-only table while its data.bin points at the writable ttl = 0 dump. The documented RESTORE ... AS <writable_table> SETTINGS allow_different_table_def = 1 path then passes the ttl / schema checks and replays bytes without TTL timestamps into a ttl > 0 target. Suggested fix: only deduplicate when ttl and backupSchemaFingerprint() also match, or make the sibling reference the owner's companion files together with data.bin. A focused integration case that restores the mixed-ttl read-only table on its own would keep this mode covered.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: make the shared-dir backup entry self-consistent for mixed-ttl siblings, or reject that mode explicitly, and add a regression for restoring that mixed-ttl read-only table on its own.

LLVM Coverage Report

Measured on commit 418b437.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 291/304 (95.72%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 3, 2026
Address review feedback on EmbeddedRocksDB backup/restore:

- TTL tables: back up and restore raw values through GetRootDB() instead of
  the DBWithTTL wrapper. The wrapper's iterator strips the trailing 4-byte
  creation timestamp and its Write() appends a fresh one, so the previous code
  reset every row's expiration on restore (rows about to expire were
  resurrected for another full TTL interval). GetRootDB() copies the timestamp
  suffix verbatim in both directions, preserving the original expiration. For
  non-ttl tables GetRootDB() is the DB itself, so the bytes are unchanged.

- Restore no longer accumulates the whole table into a single WriteBatch before
  writing. It flushes once the batch reaches 64 MiB, so restoring a large
  on-disk table does not require a second full copy of the data in RAM.

Regression test covers TTL expiration preservation and a large-table restore
that crosses the flush threshold.

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up commit 6bb0a1a addresses the two review comments (TTL expiration preservation + incremental restore flush).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. TTL: CREATE TABLE t (k UInt64, v String) ENGINE = EmbeddedRocksDB(1) PRIMARY KEY k; INSERT (1,'a'),(2,'b'); BACKUP; SELECT sleep(3); DROP; RESTORE; OPTIMIZE; SELECT count(). Pre-fix returns 2 (expired rows resurrected), post-fix returns 0. OOM: 200k-row / ~100 MB table backup+restore.
b Root cause explained? For ttl > 0, rocksdb_ptr is a DBWithTTL. Its TtlIterator::value() strips the trailing 4-byte creation timestamp and DBWithTTL::Write() appends a fresh one, so the previous logical-byte dump lost the original timestamp and restore re-stamped every row to restore-time, resetting expiration. Separately, restore built one WriteBatch for the whole table and wrote it only after reading the entire backup, doubling peak RAM for an on-disk engine.
c Fix matches root cause? Yes. Backup iterator and restore write both use rocksdb_ptr->GetRootDB(), which unwraps DBWithTTL, so the timestamp suffix is read and written verbatim in both directions. Restore flushes the WriteBatch at a 64 MiB threshold and clears it.
d Test intent preserved / new tests added? Existing round-trip cases unchanged. Added a TTL case asserting expired rows are dropped after OPTIMIZE (would be resurrected under the old behavior) and a large-table case crossing the flush threshold.
e Both directions demonstrated? Yes. TTL: reverting the two GetRootDB() calls and rebuilding gives 2 rows after OPTIMIZE (resurrection); with the fix, 0. Both confirmed on Build-ID-verified binaries. Regression test passes 10/10 via clickhouse-test.
f Fix is general across code paths? Yes. Both the backup read path and the restore write path are corrected; these are the only two RocksDB access points in the backup/restore code. Not a symptom guard: it targets exactly the wrapper stripping/re-stamping the timestamp.
g Fix generalizes across inputs? Yes. Raw key/value bytes are copied verbatim, so all PK layouts and value types round-trip unchanged (verified single/composite PK, Nullable, Array, empty table). TTL handling is orthogonal to column types; non-ttl tables are byte-for-byte unchanged because GetRootDB() is the DB itself.
h Backward compatible? The backup format for a ttl > 0 table now includes the 4-byte suffix (previously the data was silently empty on restore, so no usable prior backups exist to regress). Non-ttl backup bytes are unchanged. No settings or on-disk engine format changes.
i Invariants and contracts preserved? Yes. GetRootDB() returns the underlying rocksdb::DB (identity for a plain DB); writing raw values to it is what the TTL wrapper itself does internally after AppendTS. The scan still holds a shared lock over an implicit snapshot; each incremental flush re-acquires the shared lock and checks the handle, matching the normal insert path.

Session id: cron:clickhouse-worker-slot-7:20260703-171000

A read_only table opens its RocksDB handle with OpenForReadOnly() (ttl = 0) or
DBWithTTL::Open(..., read_only) (ttl > 0), both of which reject writes. The
restore path issues an unconditional Write(), so restoring a backup whose table
definition has read_only = true failed with an opaque RocksDB write error
("Not supported in compacted db mode"). Reject it up front in
restoreDataFromBackup() with a clear CANNOT_RESTORE_TABLE error instead.

Backup of a read_only table still works (it only reads); only the data restore
is rejected, so users get an actionable message pointing at a writable table.

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

groeneai commented Jul 3, 2026 •

Copy link
Copy Markdown
Collaborator Author

Follow-up: handle read_only EmbeddedRocksDB tables on RESTORE (commit cfcd962).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Create a read_only EmbeddedRocksDB table over an externally-populated dir, BACKUP, DROP, RESTORE. Without the guard this fails on every run with Code 555 ROCKSDB_ERROR: Not supported in compacted db mode.
b Root cause explained? initDB() opens a read_only table via OpenForReadOnly() (ttl=0) or DBWithTTL::Open(..., read_only) (ttl>0). Both reject writes. restoreDataImpl() issues an unconditional rocksdb::Write(), so restoring a backup whose table definition is read_only always fails, and with an opaque RocksDB error.
c Fix matches root cause? Yes. restoreDataFromBackup() now rejects read_only up front with a clear CANNOT_RESTORE_TABLE instead of letting the write fail later. Restore-before-reopen was rejected: a read_only table is a read-only view over an externally-managed RocksDB dir, so writing into it would violate that contract.
d Test intent preserved / new tests added? New regression test 04402_rocksdb_backup_restore_readonly.sh asserts RESTORE of a read_only table is refused with CANNOT_RESTORE_TABLE. Existing 04401 cases unchanged.
e Both directions demonstrated? Yes (debug build, Build ID verified). Without guard: Code 555 ROCKSDB_ERROR. With guard: Code 608 CANNOT_RESTORE_TABLE.
f Fix is general across code paths? Both read_only open modes (ttl=0 OpenForReadOnly, ttl>0 DBWithTTL::Open(..., read_only)) reach the same restoreDataFromBackup() entrypoint, so the single guard covers both. BACKUP is unaffected (read-only).
g Fix generalizes across inputs? The guard keys on the read_only flag, independent of ttl value, PK layout, or value type. Verified writable-table restore (incl. TTL, multi-column PK, large tables) still round-trips.
h Backward compatible? Yes. No format, setting, or default change. Previously-broken behavior (opaque failure) becomes a clear rejection; writable-table backup/restore is unchanged.
i Invariants and contracts preserved? Yes. Upholds the read_only contract (never write to an externally-managed read_only store). Guard runs before addDataRestoreTask, under no new locks; the existing non-empty check and restore write path are untouched for writable tables.

Session id: cron:clickhouse-worker-slot-3:20260703-182200

…_only restore

restoreDataFromBackup() now distinguishes three cases instead of treating a
missing data.bin as an empty table.

backupData() always writes data.bin (zero records for an empty table), so an
absent data.bin no longer means "empty". It means the backup predates the data
fix (metadata only) or is corrupted. Restoring it as an empty table would
silently reintroduce the issue ClickHouse#109213 data loss, so restore now fails closed
with CANNOT_RESTORE_TABLE. A structure_only restore still skips data and is
unaffected.

The read_only rejection is narrowed: a read_only table over an external RocksDB
directory cannot take the restore Write(), but an empty backup needs no Write(),
so an empty read_only table is restored as pure metadata. A read_only backup
that carries rows is still rejected up front.

Tests: 04401 covers the data-less fail-closed case (plus structure_only restore
still allowed); 04402 covers the empty read_only metadata restore alongside the
existing non-empty read_only rejection.

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up to the two inline change requests (data-less backup + empty read_only restore). Updated pre-PR validation gate for commit eba2b8c.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Case 1: BACKUP ... SETTINGS structure_only=true then a normal RESTORE -> old code silently restored an empty table (count 0, no error). Case 2: empty read_only table backup -> old code rejected RESTORE with CANNOT_RESTORE_TABLE. Both reproduced on demand.
b Root cause explained? backupData() now always writes data.bin (zero records for an empty table). So (1) an absent data.bin no longer means "empty table"; it means an old metadata-only backup or corruption, yet the old if (!hasFiles) return; silently restored empty (reintroducing #109213). (2) The unconditional if (read_only) throw was too broad: an empty backup needs no Write(), so an empty read_only table can be restored as pure metadata.
c Fix matches root cause? Yes. Three explicit cases keyed on the presence and emptiness of data.bin: absent -> fail closed (CANNOT_RESTORE_TABLE); present+zero rows+read_only -> allow metadata restore; present+rows+read_only -> reject.
d Test intent preserved / new tests added? Yes. 04401 gains the data-less fail-closed case (and asserts structure_only RESTORE is still allowed); 04402 gains the empty read_only metadata-restore case beside the existing non-empty read_only rejection. No prior assertion weakened.
e Both directions demonstrated? Yes, Build-ID-verified. Old binary (562cb634): Case 1 restore -> count 0 no error; empty read_only -> Code 608. Fix binary (ea78f745): Case 1 -> CANNOT_RESTORE_TABLE; empty read_only -> restored, count 0; non-empty read_only -> still Code 608.
f Fix is general across code paths? Yes. All three outcomes live in the single restoreDataFromBackup() entrypoint for this engine; no sibling restore path exists. structure_only restores are gated earlier in RestorerFromBackup::insertDataToTable() so the fail-closed guard never fires on them.
g Fix generalizes across inputs? Yes. data.bin presence/emptiness is independent of key/value types; verified with plain, empty, multi-column PK, Nullable, Array, TTL, and 200k-row tables. read_only + ttl>0 opens via DBWithTTL::Open(..., read_only) which is the same write-rejecting handle, so the row-carrying rejection covers it.
h Backward compatible? Yes, and it improves compatibility: an OLD (pre-fix) metadata-only backup that used to silently restore empty now fails loudly instead of losing data. New backups always contain data.bin. No setting default, wire, or on-disk format change.
i Invariants and contracts preserved? Yes. backupHasRows() opens a fresh CompressedReadBufferFromFile and only peeks EOF; the actual restore reopens the file. The read_only contract (never write to an externally-managed read_only RocksDB dir) is upheld: the only allowed read_only restore performs no Write().

Session id: cron:clickhouse-worker-slot-6:20260703-192400

An empty backup restored into a read_only table whose external RocksDB
directory already holds rows was silently accepted, leaving the stale rows
in place. The zero-row read_only branch returned early and skipped the
allow_non_empty_tables non-empty-table guard.

Compute whether the backup carries rows once, reject a read_only restore only
when the backup is non-empty, run the non-empty-table guard for read_only
tables too, and skip the actual Write() only when the backup has no rows. An
empty backup over a pre-populated read_only directory now fails with
CANNOT_RESTORE_TABLE unless allow_non_empty_tables is set.

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for 7736cb1 (empty read_only restore non-empty guard):

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Back up an empty read_only table over a dir, populate that dir with 100 rows, RESTORE the empty backup. Pre-fix: reports success, 100 stale rows remain. Deterministic on a debug build.
b Root cause explained? The zero-row read_only branch returned early, skipping the allow_non_empty_tables non-empty-table guard below it. backupData() now always emits data.bin, so the empty-backup path reaches that early return and bypasses the guard, leaving a pre-populated external read_only directory untouched while reporting a successful restore.
c Fix matches root cause? Yes. Compute backup_has_rows once; reject read_only only when the backup has rows; run the non-empty guard for read_only too; skip the Write() (early return) only when backup_has_rows is false. The guard now covers the exact skipped path.
d Test intent preserved / new tests added? Yes. All existing 04401/04402 cases unchanged and green. New 04402 case: empty backup + pre-populated read_only target -> CANNOT_RESTORE_TABLE; with allow_non_empty_tables=1 -> allowed, no write, 100 rows preserved.
e Both directions demonstrated? Yes. Pre-fix binary (ea78f745): silent success, count()=100 stale. Fixed binary (5b5d6167): CANNOT_RESTORE_TABLE; with allow_non_empty_tables=1 restore succeeds and rows are preserved.
f Fix is general across code paths? Yes. restoreDataFromBackup() is the single restore entry point for EmbeddedRocksDB; the guard now applies uniformly to read_only and writable tables. No sibling path duplicates this logic.
g Fix generalizes across inputs? Yes. The non-empty check iterates the actual target RocksDB store, independent of key/value types, PK layout, or TTL. backup_has_rows peeks the first record regardless of payload. Empty vs non-empty backup and empty vs pre-populated target are all covered.
h Backward compatible? Yes. No setting default, on-disk, or wire-format change. A restore that previously silently left stale rows now fails closed unless allow_non_empty_tables is set (the documented opt-in), consistent with the writable-table path. No SettingsChangesHistory change needed.
i Invariants and contracts preserved? Yes. read_only handle is never written to (rejection happens before any Write()); the allow_non_empty_tables contract (reject non-empty targets unless opted in) now holds on the read_only path too; the metadata-only restore of a genuinely empty read_only table still succeeds.

Session id: cron:clickhouse-worker-slot-7:20260703-202600

@jkartseva jkartseva self-assigned this Jul 4, 2026
@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 7736cb1

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.

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) / 04056_npy_large_shape_validation infra (macOS runner: ModuleNotFoundError: numpy; 9 PRs / 0 master, 30d) a fix task is created (investigating at full effort — fixing PR link to follow here)
Fast test (arm_darwin) / 03321_forwarded_for infra (macOS runner: ModuleNotFoundError: pandas; 8 PRs / 0 master, 30d) a fix task is created (investigating at full effort — fixing PR link to follow here)
Upgrade check (amd_release) / Error message in clickhouse-server.log (DatabasePostgreSQL::getTablesIterator 192.0.2.1:5432 timeout) infra (background PostgreSQL pool connection error in log; 148 PRs / 0 master, 30d) #109350 (ours, open)
Mergeable Check / PR aggregators reflect the Fast-test + Upgrade-check lines above; no separate failure
CH Inc sync — CH Inc sync (private, not actionable by us)

None of these are PR-caused: this PR changes only StorageEmbeddedRocksDB backup/restore C++ and two RocksDB backup regression tests, which cannot affect a macOS numpy/pandas Fast-test env or a background PostgreSQL-pool connection error in the upgrade-check log. All non-exempt lines are non-PR-caused infra with an owner.

Session id: cron:our-pr-ci-monitor:20260704-010000

@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the two Fast test (arm_darwin) ledger lines (numpy / pandas ModuleNotFoundError): #108859 (merged 2026-07-03).

It adds numpy, pandas, and scipy to the macOS runner bootstrap pip install (praktika runner-init.py, version 71 -> 72) and un-skips 03321_forwarded_for. The provisioning runs on the self-hosted macOS runner host (S3-sourced, version-gated), not from a PR branch, so it applies to all PRs' arm_darwin lane as the runner hosts re-provision; no rebase of this PR is needed.

Post-merge CIDB confirms it is taking effect: both tests now run and pass on re-provisioned hosts (32 OK vs 8 FAIL per test since the merge), with the remaining failures confined to a single not-yet-re-provisioned straggler host. These lines were never PR-caused (0 master failures over 30 days; a RocksDB backup C++ change cannot affect the macOS Python env).

Address review feedback on the two CANNOT_RESTORE_TABLE messages in
restoreDataFromBackup(), text only, no logic change.

- data.bin-absent branch: a structure_only = true backup is a legitimate
  supported mode that intentionally omits data.bin, so the message no longer
  implies old/corrupt. It now tells the user to restore such a backup with
  SETTINGS structure_only = true, and only calls the backup pre-fix or
  corrupted otherwise.
- read_only-reject branch: spell out the concrete writable-restore workaround
  (pre-create a writable EmbeddedRocksDB table with the same schema and ttl,
  then RESTORE ... AS <writable_table> SETTINGS allow_different_table_def = 1).

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

groeneai commented Jul 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

Pushed 1b1e1a9 (rebased onto current PR head 8e64a1e, which merged master): reworded the two CANNOT_RESTORE_TABLE exception messages per review, text only, no logic change. Verified compiled into the binary and that the structure_only data-restore rejection fires with the new wording; existing 04401/04402 cases assert only the error-code name (CANNOT_RESTORE_TABLE), so no .reference change needed.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Data restore of a structure_only backup deterministically throws CANNOT_RESTORE_TABLE; the read_only+rows restore deterministically throws the read_only message. Both are exercised by 04401/04402.
b Root cause explained? The two exception message texts were misleading: (1) the data.bin-absent branch is also hit by a legitimate structure_only=true backup but implied old/corrupt; (2) the read_only-reject message named no concrete restore workaround.
c Fix matches root cause? Yes. Message text only: (1) names structure_only=true as legitimate and tells the user to restore with SETTINGS structure_only=true; (2) spells out RESTORE ... AS <writable_table> SETTINGS allow_different_table_def=1. No control flow changed.
d Test intent preserved / new tests added? Preserved. 04401/04402 assert the CANNOT_RESTORE_TABLE error code, which is unchanged; message rewording keeps every case green. No new test needed for a message-only change.
e Both directions demonstrated? Reworded strings confirmed present in the rebuilt binary (Build ID changed); structure_only data-restore rejection verified to emit the new text at runtime.
f Fix is general across code paths? N/A (message-text-only change, no code bug).
g Fix generalizes across inputs? N/A (message-text-only change).
h Backward compatible? Yes. No behavior, format, or setting change; only exception message strings.
i Invariants and contracts preserved? Yes. restoreDataFromBackup() logic (fail-closed on absent data.bin, read_only reject when backup has rows, non-empty guard, skip Write on empty backup) is byte-for-byte unchanged; only the throw message strings differ.

Session id: cron:clickhouse-worker-slot-3:20260716-084100

Several EmbeddedRocksDB tables (one writable plus any number of read_only)
may share a single rocksdb_dir. The previous backup path dumped the shared
RocksDB once per table from independent snapshots on different handles, and
restore replayed each dump. That broke the supported shared-dir case: a
BACKUP DATABASE of {rw, ro} was unrestorable (the read_only sibling got its
own non-empty data.bin and tripped the read_only restore rejection), and
racing writes between the per-table dumps could restore divergent copies.

Elect a single owner per rocksdb_dir, mirroring StorageKeeperMap. The owner
(the writable table when present, whose handle also sees the freshest data)
backs up the shared RocksDB once; sibling tables reference that data entry
instead of dumping again. On restore only the owner replays the data; the
read_only rejection now applies only when a read_only table is itself the
owner (no writable sibling exists). Coordination keys are host-qualified in
the on-cluster case because rocksdb_dir is a host-local filesystem path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@jkartseva jkartseva added can be tested Allows running workflows for external contributors and removed can be tested Allows running workflows for external contributors labels Aug 7, 2026
Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 7ec0b35

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.

Check / test Reason Owner / fixing PR
Fast test / 02458_relax_too_many_parts flaky, not caused by this diff: INSERT rejected with TOO_MANY_PARTS while counting the part it wrote itself, onset 2026-08-01 across 31 unrelated pull requests plus 3 master runs #113045 (external, open)
Finish Workflow / Post Hooks cascade of the above: the four per-arch Bugfix validation jobs were DROPPED when Fast test failed, so none of them measured anything #113045 (external, open)

The Fast test red is not this pull request's diff. This branch touches src/Backups/*, src/Storages/RocksDB/* and its own two new tests; it contains no part-count, sink or INSERT code. 02458_relax_too_many_parts began failing on 2026-08-01, immediately after #109000 raised the default max_insert_threads for plain INSERTs, and it has since failed on 31 distinct pull requests and 3 master runs. #113045 names this exact test in its own body and shows the mechanism from a server log: 26 sinks are created for the query, its part is renamed into place, and onStart on a late-scheduled sink counts that part and rejects the query six milliseconds later.

Post Hooks reports passed: none for the per-arch Bugfix validation jobs with all four in state DROPPED. Nothing measured the regression test, so the row carries no independent signal and resolves with the same owner.

Session id: cron:our-pr-ci-monitor:20260807-010000

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-foreign-db Connectivity to external databases (ODBC/JDBC, MySQL, PostgreSQL, etc.). label Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

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

@jkartseva jkartseva self-assigned this Sep 8, 2026
@jkartseva

Copy link
Copy Markdown
Member

@groeneai merge master into this PR

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master in: 3e9b3f8da7a265eac29c9705ff4cbd399ece186b. No conflicts, and it sits on top of your 2026-08-06 merge, so nothing already on the branch was rewritten. The change itself is unchanged by the merge (19 files, +1081, no deletions against master).

Verified locally before pushing, since the branch was 18358 commits behind:

  • debug build (clang-22) rc=0, 16916/16916 targets;
  • 04401_rocksdb_backup_restore and 04402_rocksdb_backup_restore_readonly, 50 runs each with randomized settings: 100/100 pass.

On the CI that is starting: the Fast test red on the previous head was 02458_relax_too_many_parts, owned by #113045, which is still open, so it can show up here again.

One item from my pre-push review, from reading the code rather than from a run, so please treat it as a question and not as a report: RestorerFromBackup::finalizeTables calls finalizeRestoreFromBackup holding only lockForShare, and the read_only branch of my override closes and reopens the RocksDB handle there, while the all-scan read path takes rocksdb_ptr_mx only to create the iterator and then releases it for the iteration. A full scan of a read_only sibling running concurrently with that finalize step would iterate a closed handle. truncate has the same close-and-reopen shape but runs under an exclusive table lock, so it is not exposed that way. I have no reproducer for it. I can tighten the handle lifetime in this PR if you want it here rather than separately.

@jkartseva

Copy link
Copy Markdown
Member

@groeneai

The feedback from the failing style checker:

fetches a server-side filesystem path from a system table
Modifying the server's data on disk is not allowed in stateless tests ... Write an integration test instead.

Replace the stateless test with an integration test.

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

Doing that.

All seven cases in 04402_rocksdb_backup_restore_readonly.sh need an explicit on-disk rocksdb_dir created and cleaned up (the read_only restore guard, an empty vs an already-populated read_only directory, the shared-dir {rw, ro} single-owner dedup, an all-read_only group, and the ttl and schema mismatch rejections), so the whole file moves to a new tests/integration/test_rocksdb_backup_restore/ rather than only the flagged line changing.

04401_rocksdb_backup_restore.sql stays in 0_stateless: it only runs BACKUP/RESTORE ... Memory(...), never reads a path out of a system table and never touches the server's disk, so the checker does not flag it. Tell me if you want that one moved as well.

I will post the commit here once the integration test passes locally.

…ration test

04402_rocksdb_backup_restore_readonly.sh created and removed RocksDB directories
under the server's user_files path, which a stateless test may not do
(check_no_server_data_manipulation, added in e1fc810): the suite runs
against object storage, shared MergeTree and encrypted disks, where a server-side
path is not the test's to touch.

All seven cases move to tests/integration/test_rocksdb_backup_restore, which owns
its server: the read_only restore rejection, an empty read_only backup, an empty
backup over an already-populated read_only directory, the shared-dir {rw, ro}
single-owner dedup, an all-read_only group keeping independent snapshots, and the
ttl and schema mismatch rejections.

The assertions are rewritten to match the specific rejection message rather than
only the error code, so one guard's failure can no longer be reported as another
guard's success: the shell version printed its success marker whenever grep found
nothing, including when RESTORE failed with an unrelated error. The ttl and schema
cases also gain the reverse direction they described but did not exercise (a ttl 5
backup into a ttl 0 target, and a target whose value columns are in a different
order).

04401_rocksdb_backup_restore.sql stays in 0_stateless: it only uses BACKUP and
RESTORE with Memory() backups and never reads a server path.
@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

Done in 030eee179051962281c818abf5501a8720e4ed81. 04402_rocksdb_backup_restore_readonly.sh is deleted and its seven cases now live in tests/integration/test_rocksdb_backup_restore: the read_only restore rejection, an empty read_only backup, an empty backup over an already-populated read_only directory, the shared-dir {rw, ro} single-owner dedup, an all-read_only group keeping independent snapshots, and the ttl and schema mismatch rejections. PR description updated.

Two things I changed in the move rather than porting as they were:

  • the shell version asserted only the error code, and printed its success marker whenever grep found nothing, so a RESTORE failing with an unrelated error read as a pass. Each rejection now matches its own message, so one guard's failure cannot be reported as another guard's success.
  • the ttl and schema cases gained the reverse arms they described but never exercised (a ttl 5 backup into a ttl 0 target, and a target whose value columns are in a different order), and the shared-dir case now also restores the read_only table on its own into a fresh writable table. That last arm is what pins the backup side down: the in-place restore passes whether or not the sibling's entry references the owner's dump, because its restore task is skipped either way.

Verified with the integration runner: 7/7, and 21/21 over three repeats in random order. As a control I ran the same test against a master binary without this PR and 6 of the 7 fail; the exception is the empty-read_only case, which is a metadata-only restore that master completes too. server_data_manipulation_in_stateless_tests passes locally now, and 04401_rocksdb_backup_restore.sql is unchanged.

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 418b43705 with master fe1a91eac (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 129e4b59b; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

15 object files changed (+185.60 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/RocksDB/StorageEmbeddedRocksDB.cpp.o 832.07 KiB 967.20 KiB +135.13 KiB (+16.24%)
src/CMakeFiles/dbms.dir/Backups/BackupCoordinationOnCluster.cpp.o 447.24 KiB 470.43 KiB +23.19 KiB (+5.18%)

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

Compile time of recompiled translation units

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

Job report

groeneai and others added 2 commits September 9, 2026 07:41
finalizeRestoreFromBackup() reopens a read_only table's RocksDB handle so that a
read_only sibling sharing a rocksdb_dir observes the rows the writable owner
replayed. RestorerFromBackup::finalizeTables() calls it holding only
lockForShare, so unlike truncate() and drop(), which run under an exclusive
table lock, it does not exclude readers. The full-scan read path takes
rocksdb_ptr_mx only to create a rocksdb::Iterator and then iterates without it,
and rocksdb_ptr was a unique_ptr, so closing the handle there destroyed a
database that an iterator still pointed into. RocksDB traps that in
~ColumnFamilySet(), which asserts the last reference is gone: a debug build
aborts the server, and a build with assertions disabled reads freed memory.

So RESTORE DATABASE of a {writable, read_only} pair on one rocksdb_dir killed
the server whenever a full scan of the read_only table was in flight.

rocksdb_ptr becomes a shared_ptr and the reading source keeps the handle it took
its iterator from, which also means a scan that starts before the reopen
finishes on the snapshot it began with. finalizeRestoreFromBackup() releases its
reference rather than closing the handle, leaving the close to whichever owner
turns out to be last.

Co-Authored-By: Claude Opus 5 <[email protected]>
Each case in 04401_rocksdb_backup_restore drops a table and then restores into
the same name. InterpreterDropQuery silently ignores a DROP of a table that
stores data on disk when ignore_drop_queries_probability is non-zero, which the
stress runner sets to 0.2 for every client, so the table would survive and the
RESTORE that follows would take the already-exists path and produce a different
answer. EmbeddedRocksDB stores data on disk, so the test has to pin the setting.

Co-Authored-By: Claude Opus 5 <[email protected]>
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-unknown PR origin: unclassified (legacy task) 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 backup does not include data files; only metadata is created

6 participants