Skip to content

Stream .backup metadata with SAX instead of building a DOM tree - #109107

Merged
jkartseva merged 16 commits into
masterfrom
backup-metadata-sax-streaming
Jul 18, 2026
Merged

jkartseva merged 16 commits into
masterfrom
backup-metadata-sax-streaming

Conversation

@jkartseva

@jkartseva jkartseva commented Jul 2, 2026 •

Copy link
Copy Markdown
Member

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

Description

BackupImpl::readBackupMetadata parsed the entire .backup manifest into an in-memory Poco::XML DOM tree before walking it. For large incremental backups the manifest can list millions of files, so the DOM tree alone consumes multiple gigabytes of RAM and is a large part of the front-loaded cost of opening a base backup.

This replaces the DOM parse with a streaming Poco::XML::SAXParser driven by a small BackupMetadataHandler: the header elements are applied when <contents> opens, and each <file> is folded into the existing maps as its closing tag is seen, instead of the whole document being retained in a tree. The on-disk format is unchanged — only the way the manifest is read changes. Callback exceptions are captured and rethrown after parsing, because they must not propagate through the underlying expat callbacks.

Validated end-to-end against a server built from this branch: a new SQL round-trip test (full + incremental + archive backup, restored and compared) and a gtest for BackupMetadataHandler covering the base-backup dedup fields, header-before-files ordering, callback-exception capture, and malformed input.

Changelog category (leave one):

  • Improvement

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

Reduced memory usage when opening a backup (for RESTORE, or as the base of an incremental BACKUP). The .backup metadata is now parsed as a stream instead of being loaded into an in-memory XML document tree, which for large (especially incremental) backups avoids allocating a multi-gigabyte DOM tree.

Version info

  • Merged into: 26.7.1.1145 (included in 26.7 and later)
  • Backported to: 26.6.2.152

jkartseva and others added 4 commits July 1, 2026 23:19
`BackupImpl::readBackupMetadata` parsed the whole `.backup` manifest into an
in-memory `Poco::XML` DOM tree. For large incremental backups the manifest
lists millions of files, so the DOM tree alone costs multiple gigabytes.

Replace it with a streaming `SAXParser`: header elements are applied when
`<contents>` opens, and each `<file>` is folded into the existing maps as its
closing tag is seen, instead of being retained in a tree. The on-disk format
is unchanged. Callback exceptions are captured and rethrown after parsing,
since they must not propagate through the underlying expat callbacks.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Backs up a table (full, incremental on top of the full one, and into an
archive), restores each into a separate table, and checks the restored data
matches. This exercises `readBackupMetadata` across the disk and archive read
paths and the base-backup dedup fields, so a mis-parse of the `.backup`
manifest would fail the RESTORE or restore wrong data.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Move the streaming SAX `ContentHandler` out of the anonymous namespace of
`BackupImpl.cpp` into `Backups/BackupMetadataHandler.{h,cpp}`. The handler was
already fully decoupled from `BackupImpl` (it communicates only through the
`on_header`/`on_file` callbacks), so this is a pure code move that makes it a
named, directly unit-testable unit. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Covers the cases the SQL round-trip test cannot easily construct: header and
per-file field extraction, header-applied-before-any-file ordering, empty
`<contents>`, per-file map reset, capture-and-short-circuit of callback
exceptions (which must not propagate through the expat parser), and a
malformed manifest reported by the parser itself.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6cc11c8]

Summary: ❌

job_name test_name status info comment
Stress test (amd_msan) FAIL
Received signal 8 (signal sent by pid -406800818 from user 21999) (STID: 4141-584d) FAIL cidb IGNORED

AI Review

Summary

I reviewed the current PR diff, the full prior discussion, and the latest code in BackupImpl and BackupMetadataHandler. In the final state, I do not see a remaining blocker or major issue in the SAX-based .backup metadata reader: the earlier fail-open cases around missing or duplicate top-level <contents>, strict scalar parsing, namespace-prefixed elements, callback exception precedence, and mixed-content scalar fields are all addressed in the current code, and the added gtest / stateless coverage matches those fixes.

Final Verdict

✅ No new blocking or major findings in the current revision. No new inline review comments were posted.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 2, 2026
The Fast test build is compiled without the `minizip` library, so backing up
to / restoring from a `.zip` archive fails with `minizip library is disabled`
(`SUPPORT_IS_DISABLED`). The archive step differs from the disk path only in
where the `ReadBuffer` for `.backup` comes from - the metadata parsing is
identical - and archive round-trips are already covered by other tests, so drop
it here and keep the full + incremental disk round-trip, which runs everywhere.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109107&sha=0f61bc54919a89fa269b20d968906d5c9fc561d7&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Backups/BackupMetadataHandler.cpp 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

This PR reduces memory usage when opening backups by replacing .backup metadata parsing in BackupImpl::readBackupMetadata from a Poco::XML DOM parse to a streaming Poco::XML::SAXParser with a dedicated BackupMetadataHandler, avoiding multi-gigabyte DOM allocations for large manifests.

Changes:

  • Added BackupMetadataHandler (SAX DefaultHandler) to collect header fields and stream <file> entries one at a time.
  • Switched BackupImpl::readBackupMetadata to SAX-based parsing and deferred rethrow of callback exceptions after parsing.
  • Added coverage via a new stateless round-trip backup/restore query test and a new gtest suite for handler behavior.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/Backups/BackupImpl.cpp Replaces DOM-based .backup parsing with SAX handler callbacks while building the same in-memory maps.
src/Backups/BackupMetadataHandler.h Declares streaming SAX handler interface, callback hooks, and captured-exception contract.
src/Backups/BackupMetadataHandler.cpp Implements SAX event handling for header and per-file leaf extraction with exception capture.
src/Backups/tests/gtest_backup_metadata_handler.cpp Adds unit tests for handler ordering, field reset, exception capture, and malformed XML behavior.
tests/queries/0_stateless/04494_backup_metadata_round_trip.sh Adds end-to-end backup/restore round-trip validation (full + incremental).
tests/queries/0_stateless/04494_backup_metadata_round_trip.reference Expected output for the new round-trip test.

Comment thread src/Backups/BackupImpl.cpp Resolved
Comment thread src/Backups/BackupImpl.cpp Resolved
jkartseva and others added 2 commits July 1, 2026 20:57
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
@pamarcos pamarcos self-assigned this Jul 2, 2026
@pamarcos
pamarcos self-requested a review July 2, 2026 11:59

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

Validated end-to-end against a server built from this branch

Do you have some before/after numbers so that we can compare the amount of memory used in one case and the other? Feel free to assume a very bad scenario where this improvement would shine.

Comment thread src/Backups/BackupImpl.cpp Resolved
Comment thread src/Backups/BackupMetadataHandler.cpp Resolved
Comment thread src/Backups/BackupImpl.cpp Outdated
version = parse<int>(req("version"));
if ((version < INITIAL_BACKUP_VERSION) || (version > CURRENT_BACKUP_VERSION))
throw Exception(
ErrorCodes::BACKUP_VERSION_NOT_SUPPORTED, "Backup {}: Version {} is not supported", backup_name_for_logging, version);

@pamarcos pamarcos Jul 2, 2026 •

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.

Feedback from Claude Fable 5:

[src/Backups/BackupImpl.cpp:606, 636-642, 648, 655] Value parsing became lenient where it used to fail closed on damaged manifests. Old XMLUtils::getBool → Poco::AbstractConfiguration::parseBool threw SyntaxException on unrecognized text (and accepted yes/on/case-insensitive True); the new get_bool (636-642) and the inline check for BASE_BACKUP_COPY_S3_CREDENTIALS_FROM_BACKUP (606) silently map anything other than exactly "true"/"1" to false. Old getUInt64/getInt → Poco::NumberParser threw on trailing garbage; DB::parse (648, 655) parses the digit prefix and silently ignores the rest (12x34 → 12; 1garbage → 1). ClickHouse itself only writes canonical values, so round-trips are unaffected — but for a corrupted manifest a silently misread encrypted_by_disk=false means restoring ciphertext as plaintext data instead of raising BACKUP_DAMAGED. Fix: use strict full-consumption parsing (e.g. parseFromString-style with EOF assertion) and throw BACKUP_DAMAGED on unrecognized bool text.

Comment on lines +16 to +17
full_backup="Disk('backups', '$full_id')"
incr_backup="Disk('backups', '$incr_id')"

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.

Here we're testing full and incremental, but what about archive backup?

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 fails in the fast test build: 1aef8f9

Comment thread src/Backups/BackupMetadataHandler.cpp Outdated
Comment on lines +45 to +48
if (name == "file")
{
if (on_file)
on_file(file_fields);

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.

Feedback from Claude Fable 5:

endElement fires on_file for a at any depth (lines 45-48), and startElement re-fires on_header for any nested (lines 19-23). Concrete trace: n0 — the leaves land at depth 4, so file_fields is fully populated and on_file runs with no header applied and no version check; if <object_key> is present it reaches the LOGICAL_ERROR throw in BackupImpl.cpp instead of BACKUP_DAMAGED. The old DOM code only iterated direct children of /. Note this is not fixed by the "throw if was never seen" check alone — a document that does contain later can still process a misplaced before the header. Since path is already maintained, please gate the callbacks: fire on_header only when opens at depth 1, and on_file only when the path is exactly [root, contents, file].

Comment thread src/Backups/BackupImpl.cpp Outdated
Comment on lines +712 to +716
xml_parser.parseMemoryNP(str.data(), str.size());

/// Callbacks must not throw through expat; a captured exception is rethrown here.
if (handler.saved_exception)
std::rethrow_exception(handler.saved_exception);

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.

Feedback from Claude Fable 5:

If a callback exception was captured and the document is also malformed later on, parseMemoryNP throws the secondary XML error and saved_exception (the root cause, e.g. BACKUP_VERSION_NOT_SUPPORTED) is lost. Consider wrapping the parse in try/catch and preferring saved_exception when rethrowing. Relatedly, after a captured fatal error the parser still scans the remainder of a potentially multi-GB manifest with no way to abort early.

Parses a synthetic manifest with both the old DOM parse and the streaming SAX
handler and reports peak live-allocated bytes (jemalloc stats.allocated). The
file count is BACKUP_METADATA_BENCH_FILES-tunable for a worst-case measurement.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@jkartseva

jkartseva commented Jul 10, 2026 •

Copy link
Copy Markdown
Member Author

@pamarcos

Do you have some before/after numbers so that we can compare the amount of memory used in one case and the other? Feel free to assume a very bad scenario where this improvement would shine.

Good idea — I added a benchmark and measured it. The gtest BackupMetadataHandler.PeakMemoryStreamingVsDom (src/Backups/tests/gtest_backup_metadata_handler.cpp, commit e9496e4) parses one synthetic manifest both ways — the old DOMParser + walk vs. the streaming SAX handler — and reports peak live-allocated bytes (jemalloc stats.allocated, which unlike RSS isn't distorted by the allocator holding on to freed pages). It skips under sanitizer builds (jemalloc off) and takes BACKUP_METADATA_BENCH_FILES to size the manifest:

BACKUP_METADATA_BENCH_FILES=5000000 ./unit_tests_dbms --gtest_filter='*PeakMemoryStreamingVsDom*'

Worst-case scenario (all entries deduplicated against a base backup — the most leaf elements per <file>, i.e. the most DOM nodes), peak parse memory:

files DOM (before) SAX (after)
1 M 1.1 GiB ~0
5 M 5.5 GiB ~0
10 M 11 GiB ~0

DOM is linear at ~1184 B/file (≈13 Poco DOM nodes × 72 B + heap for name/checksum/base_checksum + allocator rounding); SAX is constant because only one <file>'s fields are alive at a time. So opening a 10M-file base backup drops from ~11 GiB of transient DOM to essentially nothing.

Note: commit e9496e4 is just the measurement harness — I'll likely revert it from the branch afterwards (allocating a full DOM tree is too heavy to run on every unit-test invocation), but it stays reachable at that SHA for anyone who wants to reproduce the numbers.

jkartseva and others added 2 commits July 10, 2026 01:52
This reverts commit e9496e4.

The benchmark allocates a full DOM tree, which is too heavy to run on every
unit-test invocation. It was a one-off harness for the before/after memory
numbers; it stays reachable at e9496e4 for anyone who wants to reproduce them.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Reject a manifest without <contents> (BACKUP_DAMAGED), gate the SAX callbacks
by exact path so misplaced <file>/<contents> elements are ignored, parse
numbers and booleans strictly, and prefer a captured callback exception over a
secondary parse error. Also drops the now-unused <Common/XMLUtils.h> include.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@jkartseva
jkartseva force-pushed the backup-metadata-sax-streaming branch from 52252c9 to ff3a578 Compare July 10, 2026 04:32
Comment thread src/Backups/BackupImpl.cpp Resolved
Comment thread src/Backups/BackupMetadataHandler.cpp 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 6 out of 6 changed files in this pull request and generated 2 comments.

Comment thread src/Backups/BackupImpl.cpp Resolved
Comment on lines +45 to +58
const String & name = qname.empty() ? local_name : qname;
/// On a closing tag `path.back() == name`. Gate by exact position (see startElement).
if (name == "file" && path.size() == 3 && path[1] == "contents")
{
if (on_file)
on_file(file_fields);
}
else if (path.size() == 2 && name != "contents") /// header leaf: <root>/<leaf>
header_fields[name] = current_text;
else if (path.size() == 4 && path[1] == "contents" && path[2] == "file") /// file leaf
file_fields[name] = current_text;
current_text.clear();
if (!path.empty())
path.pop_back();

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.

I don't want to go too far down the rabbit hole of XML parser hardening. The manifest is generated by writeBackupMetadata, so it's not auxiliary or externally supplied data – unless the user is doing something unusual.

Comment thread src/Backups/BackupMetadataHandler.cpp Resolved
Comment thread src/Backups/BackupMetadataHandler.cpp Resolved
jkartseva and others added 4 commits July 14, 2026 01:02
Follow-up hardening for the SAX metadata reader:
- Range-check the parsed version as UInt64 before narrowing to int, so a value
  that fits in UInt64 but not int (e.g. 4294967298 -> 2) is rejected instead of
  wrapping past the supported-range check.
- Reject a second top-level <contents> (writeBackupMetadata never emits two).
- Keep the first value for duplicate header/file fields (try_emplace), matching
  the old DOM getNodeByPath behavior instead of last-value-wins.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Cover missing/misplaced <contents>, a <file> outside <contents>, a duplicate
top-level <contents>, and first-value-wins for duplicate header/file fields.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Enable FEATURE_NAMESPACE_PREFIXES on the SAX parser so a prefixed element keeps
its prefix in the name (as the old DOM parser did). Without it a declared
<x:contents> arrives as local name "contents" and is accepted as an ordinary
element; with it the handler sees "x:contents", never matches, and the manifest
is rejected as having no <contents>. Confirmed by running against Poco XML.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Tampers a backup manifest to <version>4294967298</version> (fits in UInt64,
narrows to 2 as int) and asserts RESTORE fails with BACKUP_VERSION_NOT_SUPPORTED
instead of wrapping past the supported-version check.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

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 7 out of 8 changed files in this pull request and generated no new comments.

…-streaming

# Conflicts:
#	src/Backups/BackupImpl.cpp
Comment thread src/Backups/BackupMetadataHandler.cpp Resolved
A scalar field containing a child element (e.g. `<version>4294967298<x/>2</version>` or
`<encrypted_by_disk>true<x/>false</encrypted_by_disk>`) collapsed to the last text run in the
SAX path, turning a damaged value into a valid one. Reject a child element opening inside a
header/file scalar leaf, matching the old DOM `innerText` behavior. Adds gtests for both cases.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.00% 86.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 78.10% 78.10% +0.00%

Changed lines: Changed C/C++ lines covered: 258/286 (90.21%) · Uncovered code

Full report · Diff report

@jkartseva

Copy link
Copy Markdown
Member Author

The Stress test (amd_msan) failure is unrelated to this PR.

It's a SIGFPE (integer divide-by-zero) in EnabledQuota::Interval::getEndOfInterval (src/Access/EnabledQuota.cpp:237) on a zero-duration quota interval, hit during client authentication — nothing to do with backup metadata (this PR only touches src/Backups/). It reproduces on master directly and across ~40 unrelated PRs on the same day with the identical stack (STID: 4141-584d).

Tracked by #110860, with a fix already in review (#110846, "Disable zero-length interval quotas"). Safe to disregard for this PR.

@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR rewrites backup-manifest reading from a DOM parser to a streaming SAX handler (new BackupMetadataHandler) plus stricter numeric/boolean validation; it only touches the backup/restore path and nothing in the query-execution hot path. The two flagged ClickBench improvements (Q4 -19.3%, Q15 -21.1%) are both no_change: CPU time is flat on both queries and the medians sit within master's current variance band, so the wall-clock drops are cache/IO variance rather than a PR effect. The envelope suppression is consistent with the diff and the data. No action needed.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 12fd46c1-31dc-4e50-9f99-af210bc6c00c
  • MIRAI run: 018ce1ba-e64f-410b-a1a2-890f6a4ae460
  • PR check IDs:
    • clickbench_128308_1784327949
    • clickbench_128315_1784327949
    • clickbench_128321_1784327949
    • tpch_adapted_1_official_128330_1784327949
    • tpch_adapted_1_official_128342_1784327949
    • tpch_adapted_1_official_128355_1784327949

@jkartseva
jkartseva added this pull request to the merge queue Jul 18, 2026
Merged via the queue into master with commit 6181f52 Jul 18, 2026
176 of 178 checks passed
@jkartseva
jkartseva deleted the backup-metadata-sax-streaming branch July 18, 2026 04:15
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 18, 2026
@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
jkartseva added a commit that referenced this pull request Aug 1, 2026
Cherry pick #109107 to 26.6: Stream .backup metadata with SAX instead of building a DOM tree
robot-clickhouse added a commit that referenced this pull request Aug 1, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 1, 2026
jkartseva added a commit that referenced this pull request Aug 3, 2026
Backport #109107 to 26.6: Stream .backup metadata with SAX instead of building a DOM tree
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…sax-streaming

Stream .backup metadata with SAX instead of building a DOM tree
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.

6 participants