Skip to content

Don't copy all file infos when writing backup metadata - #109861

Merged
jkartseva merged 9 commits into
masterfrom
jkartseva/backup-no-copy-file-infos-on-finalize
Jul 16, 2026
Merged

jkartseva merged 9 commits into
masterfrom
jkartseva/backup-no-copy-file-infos-on-finalize

Conversation

@jkartseva

@jkartseva jkartseva commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

Related: https://github.com/ClickHouse/clickhouse-private/issues/63523

When finalizing a BACKUP, BackupImpl::writeBackupMetadata obtained the file infos of all hosts via IBackupCoordination::getFileInfosForAllHosts, which materializes a copy of every BackupFileInfo into a vector. A backup can contain millions of files (one per part file across all tables), so this transiently allocated several gigabytes right at the end of the operation — on top of the infos already held by the coordination. This was observed as a significant contributor to backup memory usage on a production instance whose backups list ~9 million files.

This adds IBackupCoordination::forEachFileInfoForAllHosts, which iterates the file infos in place (under the coordination lock) instead of copying them, and uses it in:

  • writeBackupMetadata — one pass to count entries and detect base-backup use, then a pass to stream the <contents> of the .backup metadata;
  • tryRemoveAllFiles — the corrupted-backup cleanup path (where memory is already tight).

Notes:

  • The .backup metadata format is unchanged; this only changes how the in-memory file infos are traversed while writing it.
  • This walks back some of the convenient full-materialization introduced in Simplify backup coordination for file infos #48095 ("Simplify backup coordination for file infos"), now that backups of millions of files make the copy costly.

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Reduced peak memory usage when finalizing a BACKUP. Writing the backup metadata no longer copies the file infos of all files into a temporary vector (which, for backups of millions of files, transiently cost several gigabytes); the infos are now iterated in place.

Version info

  • Merged into: 26.7.1.1006 (included in 26.7 and later)
  • Backported to: 26.6.2.153

@clickhouse-gh

clickhouse-gh Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2734aae]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, distributed plan, parallel) FAIL
01730_distributed_group_by_no_merge_order_by_long FAIL cidb IGNORED
03742_nested_loop_join_long FAIL cidb IGNORED
04033_tpc_ds_q91 FAIL cidb IGNORED
04064_unused_interpolate_columns_without_wrapper FAIL cidb IGNORED
04341_broken_mutation_part_log_flush FAIL cidb IGNORED
04057_virtual_row_many_parts FAIL cidb IGNORED
04062_text_index_json_all_values_ghdata FAIL cidb IGNORED
00804_test_custom_compression_codes_log_storages FAIL cidb IGNORED
01415_sticking_mutations FAIL cidb IGNORED
04299_alter_column_null_modifier FAIL cidb IGNORED
248 more test cases not shown
Fast test (arm_darwin) DROPPED IGNORED
Build (amd_darwin) DROPPED IGNORED
Build (arm_darwin) DROPPED IGNORED
Build (arm_v80compat) DROPPED IGNORED
Build (amd_freebsd) DROPPED IGNORED
Build (ppc64le) DROPPED IGNORED
Build (amd_compat) DROPPED IGNORED
Build (amd_musl) DROPPED IGNORED
Build (riscv64) DROPPED IGNORED

AI Review

Summary

This PR replaces the copy-all getFileInfosForAllHosts path with in-place iteration while writing .backup metadata and while collecting files to delete for corrupted backups. The memory reduction on finalization looks correct, but the touched corrupted-backup cleanup path in BackupImpl::tryRemoveAllFiles still has real failure modes that leave a broken backup behind, so I would still request changes.

Findings

⚠️ Majors

  • [src/Backups/BackupImpl.cpp:1277-1288] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/109861#discussion_r3554855943] tryRemoveAllFiles still prepends .backup unconditionally even though that file is only created in finalizeWriting. A BACKUP ... TO Memory(...) that fails before finalization still reaches BackupWriterDefault::removeFiles, BackupInMemory::removeFile(".backup") throws BACKUP_ENTRY_NOT_FOUND, and cleanup aborts before any real data file or the lock file is removed.
    Suggested fix: skip .backup when it does not exist, or otherwise make the cleanup path tolerant of missing entries before calling writer->removeFiles. Add a focused Memory() regression for a failure before finalizeWriting.
  • [src/Backups/BackupImpl.cpp:1278-1287] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/109861#discussion_r3548901396] tryRemoveAllFiles still appends one entry per BackupFileInfo, but with deduplicate_files = 1 multiple infos intentionally share the same data_file_name. BackupWriterDefault::removeFiles deletes sequentially, so Memory() throws on the second delete of the same name and leaves the corrupted backup behind.
    Suggested fix: deduplicate files_to_remove before passing it to writer->removeFiles.
  • [src/Backups/BackupImpl.cpp:1278-1287] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/109861#discussion_r3548780282] BackupCoordinationFileInfos::prepare deliberately clears data_file_name for empty files and whole-file base-backup references, so the current files_to_remove.push_back(file_info.data_file_name) still enqueues "". Memory() then throws on removeFile(""), and other backends still receive a delete request for an invalid/root path.
    Suggested fix: filter out empty data_file_name values while building files_to_remove.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 9, 2026
@jkartseva
jkartseva requested a review from Copilot July 9, 2026 03:49

Copilot AI left a comment

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.

Pull request overview

This PR reduces peak memory usage when finalizing BACKUP by avoiding materializing a full BackupFileInfos copy (potentially millions of entries) just to write .backup metadata or to clean up a corrupted backup.

Changes:

  • Add IBackupCoordination::forEachFileInfoForAllHosts with a copying default implementation.
  • Implement in-place iteration for local and on-cluster coordination by iterating the prepared BackupCoordinationFileInfos structures.
  • Update BackupImpl::writeBackupMetadata and BackupImpl::tryRemoveAllFiles to iterate file infos via the new API instead of copying.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
src/Backups/IBackupCoordination.h Adds the new virtual iteration API for file infos across all hosts.
src/Backups/IBackupCoordination.cpp Provides default implementation that falls back to getFileInfosForAllHosts.
src/Backups/BackupImpl.cpp Switches metadata writing and corrupted-backup cleanup to iterate in place.
src/Backups/BackupCoordinationOnCluster.h Declares override for the new iterator API.
src/Backups/BackupCoordinationOnCluster.cpp Implements iterator API with coordination mutex protection.
src/Backups/BackupCoordinationLocal.h Declares override for the new iterator API.
src/Backups/BackupCoordinationLocal.cpp Implements iterator API with coordination mutex protection.
src/Backups/BackupCoordinationFileInfos.h Adds iteration helper to traverse prepared file infos without copying.
src/Backups/BackupCoordinationFileInfos.cpp Implements iteration over the prepared pointer list.

Comment thread src/Backups/IBackupCoordination.h Resolved
Comment thread src/Backups/BackupCoordinationLocal.cpp Resolved
Comment on lines 1278 to +1282
files_to_remove.push_back(".backup");
for (const auto & file_info : coordination->getFileInfosForAllHosts())
coordination->forEachFileInfoForAllHosts([&](const BackupFileInfo & file_info)
{
files_to_remove.push_back(file_info.data_file_name);
});

@jkartseva jkartseva Jul 9, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This issue pre-existed and is out of scope of this PR.

for (const auto & file_info : coordination->getFileInfosForAllHosts())
coordination->forEachFileInfoForAllHosts([&](const BackupFileInfo & file_info)
{
files_to_remove.push_back(file_info.data_file_name);

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.

tryRemoveAllFiles currently appends one entry per BackupFileInfo, but with deduplicate_files = 1 multiple infos intentionally share the same data_file_name. BackupWriterMemory inherits BackupWriterDefault::removeFiles, which deletes sequentially, and BackupInMemory::removeFile throws on the second delete of the same name. That means a failed deduplicated BACKUP ... TO Memory(...) will abort cleanup partway through and leave the corrupted backup behind. This list needs deduplication before it is passed to writer->removeFiles.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This issue pre-existed and is out of scope of this PR

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated 1 comment.

Comment thread src/Backups/IBackupCoordination.h Resolved

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated 4 comments.

Comment on lines +787 to +793
void BackupCoordinationOnCluster::forEachFileInfoForAllHosts(const std::function<void(const BackupFileInfo &)> & callback) const
{
auto component_guard = Coordination::setCurrentComponent("BackupCoordinationOnCluster::forEachFileInfoForAllHosts");
std::lock_guard lock{file_infos_mutex};
prepareFileInfos();
file_infos->forEachFileInfoForAllHosts(callback);
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Both writeBackupMetadata and tryRemoveAllFiles run at finalize and nothing else touches file_infos_mutex then.
A vector of pointers costs memory, which is the opposite of this PR.

Comment on lines +125 to +129
void BackupCoordinationLocal::forEachFileInfoForAllHosts(const std::function<void(const BackupFileInfo &)> & callback) const
{
std::lock_guard lock{file_infos_mutex};
file_infos.forEachFileInfoForAllHosts(callback);
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Both writeBackupMetadata and tryRemoveAllFiles run at finalize and nothing else touches file_infos_mutex then.
A vector of pointers costs memory, which is the opposite of this PR.

Comment thread src/Backups/BackupImpl.cpp Resolved
Comment thread src/Backups/BackupImpl.cpp Resolved
/// bitset is cheaper than a hash set. Skip entries without a data file (empty file or
/// base-backup reference); an empty name could resolve to the backup root.
std::vector<bool> data_file_index_seen;
coordination->forEachFileInfoForAllHosts([&](const BackupFileInfo & file_info)

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.

tryRemoveAllFiles still assumes .backup exists for every non-archive backup, but that file is only created in finalizeWriting. If the backup fails earlier, files_to_remove starts with a missing .backup; for BACKUP ... TO Memory(...), BackupWriterDefault::removeFiles then calls BackupInMemory::removeFile(".backup"), which throws BACKUP_ENTRY_NOT_FOUND and aborts cleanup before any of the real data files or the lock file are removed. Please make this cleanup path tolerate an absent .backup file and add a focused Memory() regression for a pre-finalization failure.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This issue pre-existed and is out of scope of this PR

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Addressed in #109947

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.

I rechecked the current head after the master merge, and the issue is still present. src/Backups/BackupImpl.cpp:1276 still unconditionally prepends .backup before calling writer->removeFiles, and BackupWriterDefault::removeFiles still deletes sequentially. For BACKUP ... TO Memory(...), a failure before finalizeWriting still reaches BackupInMemory::removeFile(".backup"), throws BACKUP_ENTRY_NOT_FOUND, and aborts cleanup before any real data file or the lock file is removed.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It is not merged yet.

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.

Comment thread src/Backups/IBackupCoordination.h Resolved
jkartseva and others added 4 commits July 9, 2026 23:01
BackupImpl::writeBackupMetadata copied every BackupFileInfo of all hosts
(getFileInfosForAllHosts) to write the .backup contents. With millions of
files this transiently cost several GiB at finalize. Add
IBackupCoordination::forEachFileInfoForAllHosts to iterate in place instead,
and use it in writeBackupMetadata and tryRemoveAllFiles.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@jkartseva
jkartseva force-pushed the jkartseva/backup-no-copy-file-infos-on-finalize branch from 7bb2319 to b5bb330 Compare July 9, 2026 23:08
Co-authored-by: Copilot Autofix powered by AI <[email protected]>

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

getFileInfosForAllHosts is kept for other callers.

Why? I don't see any other callers using that method. I think we could remove it entirely.
Apart from that and a minor nitpick, looks good to me. I haven't approved it yet waiting to see if we can remove getFileInfosForAllHosts.

Comment thread src/Backups/BackupImpl.cpp Resolved
Co-authored-by: Pablo Marcos <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Your PR hit the Logical error: 'clock' abort in the stress/AST-fuzzer tests. It is fixed in master. Please update the branch.

@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 79.70% 85.80% +6.10%
Functions 91.70% 92.70% +1.00%
Branches 72.00% 78.00% +6.00%

Changed lines: Changed C/C++ lines covered: 40/42 (95.24%) · Uncovered code

Full report · Diff report

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated no new comments.

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

🚀

@jkartseva
jkartseva added this pull request to the merge queue Jul 15, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jul 15, 2026
@jkartseva
jkartseva added this pull request to the merge queue Jul 16, 2026
Merged via the queue into master with commit 6be2c19 Jul 16, 2026
175 of 177 checks passed
@jkartseva
jkartseva deleted the jkartseva/backup-no-copy-file-infos-on-finalize branch July 16, 2026 02:52
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 16, 2026
alexey-milovidov pushed a commit to groeneai/ClickHouse that referenced this pull request Jul 22, 2026
A BACKUP ... TO Memory(...) that fails before finalization never writes the
`.backup` metadata file. tryRemoveAllFiles still tried to remove it, and
BackupInMemory::removeFile threw BACKUP_ENTRY_NOT_FOUND, aborting cleanup and
leaving the backup registered so the name could not be reused. Make the
in-memory writer's removal best-effort, matching the S3, Disk and File writers,
and log a missing entry instead of ignoring it silently.

Adds a backup_fail_before_writing_metadata failpoint and a regression test.

Related: ClickHouse#109861

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 31, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 31, 2026
jkartseva added a commit that referenced this pull request Aug 3, 2026
Backport #109861 to 26.6: Don't copy all file infos when writing backup metadata
UnamedRus pushed a commit to UnamedRus/ClickHouse that referenced this pull request Aug 12, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-no-copy-file-infos-on-finalize

Don't copy all file infos when writing backup metadata
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
A BACKUP ... TO Memory(...) that fails before finalization never writes the
`.backup` metadata file. tryRemoveAllFiles still tried to remove it, and
BackupInMemory::removeFile threw BACKUP_ENTRY_NOT_FOUND, aborting cleanup and
leaving the backup registered so the name could not be reused. Make the
in-memory writer's removal best-effort, matching the S3, Disk and File writers,
and log a missing entry instead of ignoring it silently.

Adds a backup_fail_before_writing_metadata failpoint and a regression test.

Related: ClickHouse#109861

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-improvement Pull request with some product improvements 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.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants