Repository navigation
Fix empty tables in a second Backup database from the same backup - #113378
PedroTadim merged 1 commit into
Conversation
… name Creating two ENGINE = Backup databases from the same backup left the second one's tables silently empty, and dropping such a database and recreating it under a different name did the same, so a database could not be restored from a backup under a new name without restarting the server. buildStoragePolicyName keyed the policy on the in-backup database name and the backup destination only. The local database name was absent from the key, yet the value cached under it depends on the local name: the policy's DiskBackup is built with path_prefix_replacement.from = data_path, that is data/<local name>/. Context::getOrCreateStoragePolicy is get-or-create, so on a key hit the creator lambda never runs and the second database adopts the first one's disk. DiskBackup::replacePathPrefix returns the path unchanged when the prefix does not match, so the second database's part lookups resolve to paths that are not in the backup, and its tables load with zero parts without any error. Add the local database name to the name, and derive the whole name as a sipHash128 over the length-prefixed triple (local name, in-backup name, destination). Hashing rather than joining with a delimiter matters here: escapeForFileName does not escape '_', which is ubiquitous in database names, so a '_'-joined key collides for ordinary name pairs such as local "x" plus in-backup "y_z" against local "x_y" plus in-backup "z", and a collision in this key reproduces exactly the silent wrong-results bug being fixed. Length prefixing keeps field boundaries unambiguous. DiskFromAST names generated disks the same way and for the same reason, since the name has to come out identical on every open of the same database. Nothing persists the name: DatabaseBackup never writes a table .sql, it reads them out of the backup and rewrites the AST in memory, and getCreateDatabaseQueryImpl regenerates CREATE DATABASE from the config without mentioning a policy. So the changed spelling needs no upgrade or downgrade path, no SettingsChangesHistory entry, and no versioning. A database created by an older server picks up the fix when it is opened. As a side effect the policy name no longer embeds the backup destination verbatim. BackupInfo::toString formats with secrets shown, so with an S3 destination the previous name carried the credentials into each table's storage_policy setting and into system.storage_policies. The integration test test_multiple_databases_from_same_backup was written by @orloffv in the test-only pull request ClickHouse#83220. Closes: ClickHouse#83219
Internal second-model reviewA separate reviewer read the change cold, without the implementation notes, and an independent
The second model returned no findings. Independently verified during review, not taken from the implementation notes:
Session id: cron:clickhouse-review-slot-8:20260804-180400 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-47:20260804-171931 |
|
cc @alesapin @jkartseva, could you review this? The storage policy that backs an |
|
Workflow [PR], commit [1498d6f] Summary: ✅
AI ReviewSummaryThis PR fixes the direct cache-key collision between two Findings❌ Blockers
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 19/20 (95.00%) · Uncovered code |
| String buildStoragePolicyName(const String & local_database_name, const DatabaseBackup::Configuration & config) | ||
| { | ||
| return fmt::format("__database_backup_config_{}_{})", config.database_name, config.backup_info.toString()); | ||
| const auto backup_info_string = config.backup_info.toString(); |
There was a problem hiding this comment.
config.backup_info.toString() is still not the full identity of the cached DiskBackup. If the destination comes from a named collection, ALTER NAMED COLLECTION can change the resolved URL/credentials without changing this string. Because Context::getOrCreateStoragePolicy caches these __... policies by name and StoragePolicySelector::updateFromConfig keeps temporary policies alive, dropping and recreating ENGINE = Backup(..., S3(my_collection)) under the same local database name can silently keep reading the old backup.
Can we key this off the resolved destination identity instead, for example via BackupFactory::getDestinationIdentity on a frozen named-collection snapshot, and keep that identity stable between beforeLoadingMetadata and loadTablesMetadata? A focused repro would be: create bk from S3(coll), drop it, ALTER NAMED COLLECTION coll SET url = ..., recreate bk, and observe that it still reads the first backup.
There was a problem hiding this comment.
The premise is correct and I reproduced it, but it is a pre-existing defect in a different
key component, so I am not folding it into this PR.
getDestinationIdentity does exist (BackupFactory.h:65, added in 7db7330524f), so the
suggestion is not hypothetical. It currently has zero production callers.
Confirmed that toString() renders only the collection name: SHOW CREATE DATABASE bk
gives ENGINE = Backup('src', 'S3(coll)'), with no resolved URL.
Ran your repro against MinIO with two backups of the same database holding different row
counts (bkt/one = 2 rows, bkt/two = 3):
CREATE NAMED COLLECTION coll AS url='.../bkt/one', access_key_id=..., secret_access_key=...;
CREATE DATABASE bk ENGINE = Backup('src', S3(coll)); -- 2, correct
DROP DATABASE bk;
ALTER NAMED COLLECTION coll SET url='.../bkt/two';
CREATE DATABASE bk ENGINE = Backup('src', S3(coll)); -- 2, expected 3| binary | build id | first open | after ALTER | expected |
|---|---|---|---|---|
| this PR | 50a7c56a8adf4197 |
2 | 2 | 3 |
| pristine master | 86a06a744ba91a07 |
2 | 2 | 3 |
Identical on both arms, so this PR neither introduces nor worsens it. Three further facts I
measured: a server restart does clear it (the same database then reads 3), SYSTEM RELOAD CONFIG does not (__-prefixed policies are skipped at StoragePolicy.cpp:528,546), and a
per-query override is unaffected because kv_args are rendered into toString(), so
S3(coll, url='.../two') correctly reads 3. Only the bare-collection form is affected.
Reasons to keep it separate rather than fold it in. This PR fixes the missing local database
name, and that half is complete and verified. Adopting the destination identity is not a
one-liner: getDestinationIdentity requires a frozen collection and a context, while the
sibling call site updateCreateQueryWithDatabaseBackupStoragePolicy receives no context, and
both sites have to derive a byte-identical name or table load throws UNKNOWN_POLICY. It also
changes behaviour for engines whose identity callback throws by design (Memory and Null,
which have no persistent identity), which deserves its own decision.
I have filed it as follow-up work with the repro above.
There was a problem hiding this comment.
Filed as #113455, with the repro, the two-binary measurement showing it is pre-existing, and the four constraints any fix has to satisfy (getDestinationIdentity needs a frozen collection and a context, the sibling call site has no context, both sites must derive a byte-identical name, and the Memory/Null identity callbacks throw by design). Leaving this PR as is.
CI finish ledger - 1498d6fCI is complete for this head. No failing checks. The
Session id: cron:our-pr-ci-monitor:20260805-033000 |
| @@ -0,0 +1,60 @@ | |||
| #!/usr/bin/env bash | |||
| # Tags: no-encrypted-storage | |||
There was a problem hiding this comment.
Because ENGINE = Backup cannot read a backup whose parts came off an encrypted disk at all, so the test cannot pass in that mode for a reason unrelated to what it checks. I measured it rather than assuming, and all four sibling ENGINE = Backup tests (03276-03279) carry the same tag for the same reason.
Servers with configs installed by the real tests/config/install.sh --s3-storage [--encrypted-storage] --no-azure, MinIO on 11111, each server's buildId() asserted against the binary before every arm:
| test | encrypted storage | binary | result |
|---|---|---|---|
| 04750 (this PR) | no | this PR | matches reference |
| 04750 (this PR) | yes | this PR | every read 0 |
| 03277 (existing) | no | this PR | matches reference |
| 03277 (existing) | yes | this PR | every read 0 |
| 03277 (existing) | yes | pristine master | every read 0 |
The last row is the one that matters: an existing test fails identically on master without this PR, so the tag is not something this PR chose.
Mechanism. Under --encrypted-storage the default MergeTree policy becomes s3_encrypted, whose disk is type=encrypted. BACKUP copies part files off that disk verbatim as ciphertext: in the backup on disk, columns.txt and count.txt both start with the bytes ENC (kHeaderSignature, src/IO/FileEncryptionCommon.cpp), where the unencrypted arm starts columns format version: 1. The table metadata is written by the backup engine itself and stays plaintext, so the table attaches and shows up in system.tables, but BackupImpl tracks encrypted_by_disk per file and refuses to serve one to a non-encrypted destination (CANNOT_RESTORE_TO_NONENCRYPTED_DISK, src/Backups/BackupImpl.cpp). DiskBackup::getDataSourceDescription never sets is_encrypted, so that check can never pass. Every part is detached as broken:
<Error> t: Part data/.../all_1_1_0/ is broken and needs manual correction. Reason: Code: 697.
DB::Exception: File data/.../all_1_1_0/columns.txt is encrypted in the backup, it can be
restored only to an encrypted disk. (CANNOT_RESTORE_TO_NONENCRYPTED_DISK)
Note this also hits the first database, so it is not the shape this PR fixes.
The tag arrived with the encrypted-storage mode itself, in b199cb5 (#59898), which added --encrypted-storage and tagged 03276-03279 in the same commit. It only skips the encrypted variant of the object-storage runs; the test still runs in every other stateless configuration, and the integration test covers the object-storage destination.
Restoring an encrypted backup through ENGINE = Backup is an unimplemented feature with an explicit error rather than a silent wrong result, so I did not fold anything into this PR for it. Happy to file it separately if you want it tracked.
|
@orloffv can you give a final review? |
|
|
Backporting to merge #122669 |
Cherry pick #113378 to 26.3: Fix empty tables in a second Backup database from the same backup
One conflict, in `tests/integration/test_database_backup/test.py`, and it is not a divergence in what this change touches: #113378 inserts `test_multiple_databases_from_same_backup` right after `test_database_backup_table`, and the function that follows at that point differs between the branches. Master has `test_database_backup_unavailable_but_server_starts`, which this branch does not carry; this branch has `test_database_backup_metadata_with_quoted_locator_loads_on_restart`, which rebinds `instance` to `instance_local_metadata`. Resolved to this branch's file plus the inserted test, so the merge against the backport base is `DatabaseBackup.cpp` (+28/-6), the new test function, and the two `04750_database_backup_multiple_databases_same_backup` files and nothing else. The inserted test uses the module-level `instance`, which this branch defines; `current_database_name` is in `loadTablesMetadata`, the `SipHash &` overload of `getSipHash128AsHexString` is present, and `04750` is free. Co-Authored-By: Claude Opus 5 <[email protected]>
…e from the same backup
Backport #113378 to 26.3: Fix empty tables in a second Backup database from the same backup
Backport #113378 to 26.7: Fix empty tables in a second Backup database from the same backup
…up database from the same backup
Closes: #83219
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed silently empty tables when more than one
ENGINE = Backupdatabase is created from the same backup, or when such a database is recreated under a different name. The storage policy that backs aBackupdatabase is now identified by a name that also covers the local database name, so each database gets the disk built for its own data path.Description
Creating two
Backupdatabases from one backup left the second one's tables empty, with no error:Dropping a
Backupdatabase and recreating it under a different name hit the same thing, so a database could not be restored from a backup under a new name without a server restart.Root cause:
buildStoragePolicyNamekeyed the policy on the in-backup database name and the backup destination only, leaving out the local database name. The policy'sDiskBackupis built for one specific local data path (path_prefix_replacement.from = data_path, i.e.data/<local name>/), andgetOrCreateStoragePolicyskips its creator on a name hit, so the second database adopted the first one's disk.DiskBackup::replacePathPrefixreturns a path unchanged when the prefix does not match, so the second database's part lookups resolved to paths absent from the backup and its tables loaded with zero parts.The fix adds the local database name, deriving the whole name as a
sipHash128of the length-prefixed triple (local name, in-backup name, destination) so field boundaries stay unambiguous.DiskFromASTnames generated disks the same way and for the same reason: the name has to be identical on every open of the same database. Nothing persists the name, so no compatibility handling is needed.Validated on a debug build: both new tests fail on unpatched master and pass with the change; the
test_database_backupintegration suite (13 cases) and the four existingdatabase_backupstateless tests stay green; the new stateless test passes 50/50 under randomized settings. Recreating a database under the same name and opening two databases from different backups behave as before.The integration test
test_multiple_databases_from_same_backupis @orloffv's, from his test-only #83220.Version info
26.8.1.828-master(included in26.8and later)26.7.17.7,26.3.36.6