Skip to content

Fix empty tables in a second Backup database from the same backup - #113378

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-83219-backup-db-storage-policy-key
Aug 5, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-83219-backup-db-storage-policy-key

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #83219

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

Fixed silently empty tables when more than one ENGINE = Backup database is created from the same backup, or when such a database is recreated under a different name. The storage policy that backs a Backup database 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 Backup databases from one backup left the second one's tables empty, with no error:

CREATE DATABASE bk1 ENGINE = Backup('src', File('b1'));
CREATE DATABASE bk2 ENGINE = Backup('src', File('b1'));
SELECT count() FROM bk1.t;  -- 2
SELECT count() FROM bk2.t;  -- 0

Dropping a Backup database 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: buildStoragePolicyName keyed the policy on the in-backup database name and the backup destination only, leaving out the local database name. The policy's DiskBackup is built for one specific local data path (path_prefix_replacement.from = data_path, i.e. data/<local name>/), and getOrCreateStoragePolicy skips its creator on a name hit, so the second database adopted the first one's disk. DiskBackup::replacePathPrefix returns 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 sipHash128 of the length-prefixed triple (local name, in-backup name, destination) so field boundaries stay unambiguous. DiskFromAST names 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_backup integration suite (13 cases) and the four existing database_backup stateless 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_backup is @orloffv's, from his test-only #83220.

Version info

  • Merged into: 26.8.1.828-master (included in 26.8 and later)
  • Backported to: 26.7.17.7, 26.3.36.6

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

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

A separate reviewer read the change cold, without the implementation notes, and an independent
second model then re-reviewed the whole diff. Findings and verdicts:

# Finding Verdict
💡 PR title was 77 characters, over the 70 the style guidance asks for AGREE, shortened before publishing
💡 The one added comment block is 4 lines against a 3-line guideline DISAGREE. 16 added code lines against 4 comment lines, and each of the three claims is a local invariant that is easy to break by accident: the name is the cache key, length prefixing is what prevents the collision, and the name must be a pure function or a restart re-collides. None of them is motivation or history, so none belongs only in the commit message
💡 The revived integration test covers one backup destination where its siblings cover four DISAGREE. It is @orloffv's original test and the object-storage arm is the strictest of the four; the local disk path is covered by the new stateless test, and the other destinations add no distinct path through buildStoragePolicyName

The second model returned no findings.

Independently verified during review, not taken from the implementation notes:

  • Both buildStoragePolicyName call sites derive the identical string. There are exactly two,
    and a byte mismatch would throw UNKNOWN_POLICY at table load rather than fail silently.
  • beforeLoadingMetadata installs the policy before loadTablesMetadata resolves it, on both
    the CREATE DATABASE path and on startup.
  • Nothing persists the policy name, so the changed spelling needs no versioning. Checked against
    the on-disk metadata of a live server as well as structurally: every write path on
    DatabaseBackup throws, and getCreateDatabaseQueryImpl regenerates the DDL from the config.
  • RENAME DATABASE cannot desynchronize the key from the data path, because it is unreachable
    for this engine. SYSTEM RELOAD CONFIG still skips the name, which keeps its __ prefix.
  • escapeForFileName is injective, so hashing the raw name while the value side hashes the
    escaped path keeps key and value in agreement.
  • Both new tests fail on unpatched master on exactly the arms that should fail, and the
    same-name-recreate arm passes in both directions, so it guards against an over-broad fix.

Session id: cron:clickhouse-review-slot-8:20260804-180400

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on demand, no server or S3 needed. clickhouse local with a File('b1') backup: create bk1 then bk2 from it, SELECT count() gives 2 and 0. Also reproduces as a stateless test (04750, fails on unpatched master) and as the integration test (AssertionError: assert '' == '1\tfrom_backup\n').
b Root cause explained? buildStoragePolicyName keyed the policy on the in-backup database name plus the backup destination, omitting the local database name, while the cached value depends on it: the policy's DiskBackup sets path_prefix_replacement.from = data_path, i.e. data/<local name>/. getOrCreateStoragePolicy is get-or-create, so on a key hit the creator 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 absent from the backup and its tables load with zero parts, silently.
c Fix matches root cause? Yes. The key now covers every input the value depends on, which is the violated invariant itself. No guard at the symptom site: replacePathPrefix is untouched, since with the key fixed its prefix always matches.
d Test intent preserved / new tests added? New stateless test 04750_database_backup_multiple_databases_same_backup.sh (two live databases, recreate under the same name, recreate under a different name, RENAME DATABASE still rejected) and integration test_multiple_databases_from_same_backup (S3-plain destination plus a restart re-read), revived from @orloffv's test-only #83220. No existing test was weakened.
e Both directions demonstrated? Yes, on Build-ID verified binaries. Pristine master (86a06a74...): stateless test FAILS (1000 499500 becomes 0 0 on the two affected arms), integration test FAILS. Fixed binary (50a7c56a...): stateless 50/50 under randomized settings, integration passes, all 13 integration cases and the 4 existing database_backup stateless tests green.
f Fix is general across code paths? Yes. Both buildStoragePolicyName callers are fixed and now derive the identical string: the installer (beforeLoadingMetadata) and the resolver that writes each table's storage_policy setting. A byte mismatch would throw UNKNOWN_POLICY at table load, and the row-count arms prove the tables actually read. Enumerated: 2 callers total, 1 DiskBackup construction site, 1 getOrCreateStoragePolicy caller, and __database_backup_config appears nowhere else in the tree.
g Fix generalizes across inputs? Yes, measured. Local names that are dotted, non-ASCII, space-and-percent bearing, and single character all read correctly from one backup with 4 distinct policy names. The ambiguous-split pair that a delimiter-joined key would have collided on, local x reading in-backup y_z versus local x_y reading in-backup z from the same backup, gets distinct names and returns each database's own rows; the name is hashed over length-prefixed fields for exactly this reason. Two different backups, and recreate under the same name, still behave as before.
h Backward compatible? Yes, nothing persists the policy name. DatabaseBackup never writes a table .sql; it reads them out of the backup, rewrites the AST in memory, and getCreateDatabaseQueryImpl regenerates CREATE DATABASE from the config with no policy mention. Confirmed empirically: the only on-disk metadata is ATTACH DATABASE ... ENGINE = Backup('src', File('b1')), and a reopen re-derives the name and reads correctly. A database created by an older server picks up the fix on open; one created by a patched server, read back on an older binary, simply reverts to the old behaviour. No SettingsChangesHistory.cpp entry and no format versioning apply.
i Invariants and contracts preserved? The invariant restored is that the storage-policy cache key must cover every input the cached value depends on. getDatabaseName takes the database mutex and beforeLoadingMetadata does not hold it, matching the same call already made in that function's own error path; the other call site reuses the current_database_name the surrounding lambda already captured. The name keeps its __ prefix, so SYSTEM RELOAD CONFIG continues to skip it. The FORCE_ATTACH early return still leaves before the policy is touched, so no table can be given an uninstalled policy name; covered by the existing test_database_backup_unavailable_but_server_starts. RENAME DATABASE remains rejected, so the key cannot desynchronize from the data path.

Session id: cron:clickhouse-impl-slot-47:20260804-171931

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @jkartseva, could you review this? The storage policy that backs an ENGINE = Backup database was keyed on the in-backup database name plus the destination, leaving out the local database name, while the cached DiskBackup translates paths for one specific local data path, so a second database from the same backup silently adopted the first one's disk and read zero parts.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1498d6f]

Summary: ✅


AI Review

Summary

This PR fixes the direct cache-key collision between two Backup databases that differ only by local database name, and the added tests cover the reproduced bug. I found one remaining correctness gap in the same invariant: destinations reached through named collections can still alias to a stale DiskBackup, so I do not think the change is ready to merge yet.

Findings

❌ Blockers

  • [src/Databases/DatabaseBackup.cpp:92] buildStoragePolicyName still hashes config.backup_info.toString(), which is only the query text, not the resolved backup destination. For ENGINE = Backup(..., S3(my_collection)), ALTER NAMED COLLECTION can change the target backup without changing this string. Because Context::getOrCreateStoragePolicy reuses temporary policies by name and those __... policies survive config reloads, dropping and recreating the database under the same local name can silently keep reading the old backup. Key the policy off a resolved destination identity such as BackupFactory::getDestinationIdentity, and keep that identity stable between beforeLoadingMetadata and loadTablesMetadata.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 19/20 (95.00%) · Uncovered code

Full report · Diff report

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

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.

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.

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

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.

@groeneai create an issue for this and fix it later

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.

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.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1498d6f

CI is complete for this head. No failing checks. The Bugfix validation (integration tests, *) jobs both concluded success: their per-test FAIL rows are the expected pre-fix failures that validate the regression test, not failures to own.

Check / test Reason Owner / fixing PR
- no failures -

Session id: cron:our-pr-ci-monitor:20260805-033000

@PedroTadim PedroTadim assigned PedroTadim and unassigned PedroTadim Aug 5, 2026
@@ -0,0 +1,60 @@
#!/usr/bin/env bash
# Tags: no-encrypted-storage

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.

@groeneai why no encrypted storage?

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.

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.

@PedroTadim

Copy link
Copy Markdown
Member

@orloffv can you give a final review?

@orloffv

orloffv commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

@orloffv can you give a final review?
I like it!

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 5, 2026
Merged via the queue into ClickHouse:master with commit 9d0b1a2 Aug 5, 2026
180 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 5, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@PedroTadim

Copy link
Copy Markdown
Member

Backporting to merge #122669

jkartseva added a commit that referenced this pull request Sep 28, 2026
Cherry pick #113378 to 26.3: Fix empty tables in a second Backup database from the same backup
jkartseva added a commit that referenced this pull request Sep 28, 2026
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]>
robot-clickhouse added a commit that referenced this pull request Sep 28, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 28, 2026
PedroTadim added a commit that referenced this pull request Sep 29, 2026
Backport #113378 to 26.3: Fix empty tables in a second Backup database from the same backup
PedroTadim added a commit that referenced this pull request Sep 29, 2026
Backport #113378 to 26.7: Fix empty tables in a second Backup database from the same backup
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.2-must-backport v26.3-must-backport v26.4-must-backport v26.5-must-backport v26.6-must-backport v26.7-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Creating multiple databases from the same backup produces empty tables due to shared backup ID in storage policies

7 participants