Skip to content

improve(backup): compress backup archives on several CPU cores - #199367

Merged
vincentkoc merged 2 commits into
mainfrom
perf/backup-parallel-gzip
Nov 15, 2026
Merged

vincentkoc merged 2 commits into
mainfrom
perf/backup-parallel-gzip

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

Related: #183094

What Problem This Solves

openclaw backup create compresses the whole archive on one CPU core, so large installs spend most of the command waiting on gzip while the other cores are idle. On one 16-core host a scheduled backup create --verify of about 18 GB ran past 60 minutes, more than 40 of them in archive writing at about 6 MB/s of compressed output.

User Impact

User impact: backup archives are written about three times faster on hosts with four or more cores (synthetic measurement below), with the same .tar.gz format. Archives are under 0.1% larger. Existing archives, backup verify, backup restore, and stock tar/gunzip are unaffected.

Why This Change Was Made

The tar stream is cut into 4 MiB blocks. Up to four blocks compress at once on the libuv thread pool, and they are written in order as consecutive gzip members. A gzip file is defined as a series of members (RFC 1952), so every reader sees one ordinary stream. The compression level is unchanged.

Limits and tradeoffs:

  • The width is capped at four because zlib work runs on the libuv pool, which has four threads by default and is shared with file reads. While an archive is being written, other pool work in that process (file stats, DNS) waits behind compression; every caller today is a CLI or worker process, not the Gateway. More cores need worker threads; that is a follow-up.
  • With a stalled disk the writer reads at most about five blocks ahead (21 MiB measured), then waits.
  • The capture phase and verify are untouched. A new format such as zstd is out of scope ([Feature]: Opt-in zstd compression for openclaw backup archives #182699).

Evidence

Synthetic payload, 336 MiB raw: 120 MiB random, 120 MiB JSON-like text, 80 MiB repetitive logs, 4,000 small files. Each variant pipes the same node-tar (7.5.22) stream through the compressor into a file. Three interleaved rounds, Node 26.7.0, darwin/arm64, 18 cores, on a host that was running other work.

variant wall s (3 runs) CPU s (3 runs) archive MiB
before: createGzip() 7.77 / 7.84 / 9.71 8.68 / 8.43 / 10.07 186.6
after: this PR 2.71 / 2.39 / 2.82 8.81 / 8.48 / 9.51 186.7
this PR at width 1 7.50 / 8.21 / 7.28 7.78 / 8.46 / 7.69 186.7
alternative: createGzip({ level: 1 }) 6.44 / 6.92 / 6.08 7.18 / 7.47 / 7.04 190.6

Median wall time falls from 7.84 s to 2.71 s (2.9x) for the same CPU time. Level 1 alone saves about 18% and grows the archive 2%, so the level stays as it is.

Compatibility of the new 85-member archive, checked in the same run:

  • Node createGunzip output is byte-identical to the single-stream archive (354,068,992 bytes).
  • node-tar tar.t with gzip: true, strict: true, and maxDecompressionRatio: 1100 (the options verify uses) lists the same 4,179 entries, also with 4,099-byte reads so member boundaries fall inside and between chunks.
  • node-tar tar.x and system tar -xzf both extract a tree identical to the source (diff -r); gzip -t passes.

A second run on the final head, with the host busier, gave 11.05 / 14.66 / 12.90 s before and 3.89 / 5.47 / 2.39 s after.

Tests in this PR:

  • src/commands/backup-restore.test.ts round trip: real createBackupArchive over a state directory holding 9 MiB of random bytes, then real backup restore (verify plus extraction). It asserts the archive holds more than one gzip member and the restored file is byte-identical.
  • src/infra/backup-gzip.test.ts: member order with uneven chunks, empty input, read-ahead bounded by the width under a slow consumer, and a failed block surfacing in order while the source is closed.

An independent read-only review of the diff found nothing blocking. Its two real findings are fixed here: the stalled-disk bound (about 130 MiB with the first version, now about 21 MiB) and an option that measured no benefit.

Not verified:

  • Tests did not run locally: the worktree had no installed dependencies, so PR CI is the first run. The helper and stream stage were exercised with plain Node against the same source files.
  • No end-to-end openclaw backup create --verify was timed, and nothing was measured on the 16-core host. The gain there depends on how much of its archive time is gzip.
Benchmark script
// node bench.mjs <src/infra/backup-gzip.ts> <node_modules/tar/dist/esm/index.js> <work dir>
import { compose, Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { createGzip } from "node:zlib";
// ...build the payload under <work dir>/state, then for each variant:
const variants = {
  before: () => createGzip(),
  after: () => (source) => gzipInParallel(source),
  "width 1": () => (source) => gzipInParallel(source, 1),
  "level 1": () => createGzip({ level: 1 }),
};
const cpu = process.cpuUsage();
const start = process.hrtime.bigint();
await pipeline(
  compose(Readable.from(tar.c({ cwd: workDir, portable: true }, ["state"])), makeGzip()),
  fs.createWriteStream(out),
);

Backup archives were compressed by one gzip stream, so archive writing used one core regardless of host size. Split the tar stream into 4 MiB blocks and compress up to four at a time on the libuv pool, writing them as consecutive gzip members. The output is still a standard .tar.gz that existing verify, restore, and stock tar read unchanged.

Refs #183094
@vincentkoc vincentkoc self-assigned this Nov 15, 2026
@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 15, 2026
@clawsweeper

clawsweeper Bot commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR compresses backup tar data in ordered 4 MiB gzip members using up to four concurrent compression jobs.

Example: The contributor's 336 MiB synthetic backup workload on an 18-core Mac.

  • Before: Single-stream gzip took a median 7.84 seconds and produced a 186.6 MiB archive.
  • After: Parallel compression reportedly took a median 2.71 seconds and produced a 186.7 MiB archive.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The implementation is focused and appears correct by inspection, with useful compression measurements but limited integration validation.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Partial
User problem: Large backup commands spend substantial time compressing on one CPU core while other cores remain idle.
Reason: The maintainer-authored direction addresses measured user cost with bounded implementation scope; Related wording appropriately leaves the broader performance issue open.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored draft addresses a measured bottleneck still present on main, and inspection found no concrete introduced defect.

Priority: P2
Reviewed head: 11930b3a9f8c6d996a47d2852798c7afdeaf70d4

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Provide redacted terminal output or logs comparing the real backup CLI before and after on a multi-block workload, including successful create --verify and byte-correct restore.
Agent review details

How this fits together

The backup writer receives tar payload bytes and a finalized manifest, compresses them, and publishes a .tar.gz archive consumed by verification and restore.

flowchart LR
  A[Backup CLI] --> B[Capture source state]
  B --> C[Tar payload and manifest]
  C --> D[Ordered parallel gzip]
  D --> E[Published archive]
  E --> F[Verify and restore]
Loading

Technical review

Best possible solution:

Keep compression within the existing backup pipeline, preserving ordered bytes, bounded concurrency, archive compatibility, and existing cleanup ownership.

Do we have a high-confidence way to reproduce the issue?

Current source confirms serial gzip compression, and the linked discussion supplies phase measurements consistent with that bottleneck; no target code was executed during this read-only review.

Is this the best way to solve the issue?

Ordered gzip members are a focused approach that preserves the existing compression level and readers; simplification review found no unnecessary parallel owner or scaffolding.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against b8cd8c10e501.

Provenance checked

  • Manifest composition and compression changes intended behavior with a stated reason (ed0df5b: The earlier change sealed manifest facts after payload traversal to preserve and report symbolic links; it did not establish single-threaded compression as a product requirement.)
  • Cancellation and progress lifecycle keeps the original intent (2a26e67: Interrupted archive production must settle before owned partial-file cleanup; the new compressor joins pending jobs and retains the existing archive lifecycle owner.)
  • Avoiding whole-stream copies changes intended behavior with a stated reason (6a19556: The manifest stage stopped copying every incoming chunk; this PR retains that optimization and introduces bounded block copies specifically for concurrent compression.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Precisely scoped introduced change: The pinned introduction replaces createGzip in appendBackupManifest and adds the bounded compressor and its tests; base-only changes are outside this PR. (src/infra/backup-create-stream.ts:35, 11930b3a9f8c)
  • Current main retains the bottleneck: appendBackupManifest still ends with one createGzip stream on fetched main. (src/infra/backup-create-stream.ts:34, b8cd8c10e501)
  • Reported production bottleneck and broader work: etzelm measured archive writing at roughly 70% of a large backup command; vincentkoc supplied another CPU-bound report. steipete documented the earlier verification optimization in fix: avoid repeated decompression when verifying backups #188518 while leaving capture and compression work open.
  • Useful but limited supplied proof: The full PR body reports interleaved real-zlib benchmarks and successful Node, node-tar, system tar, and gzip compatibility checks, but explicitly says the actual backup CLI and existing suites were not run. (11930b3a9f8c)
  • Behavioral CI has not run: The successful checks are dispatch, label, resolve, macOS scope detection, and actionlint; the remaining checks, including the CI gate, are skipped. (11930b3a9f8c)

Likely related people:

  • Peter Steinberger: Raw commit 6a19556 adds src/infra/backup-create-stream.ts:20 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6a1955683bc9; files: src/infra/backup-create-stream.ts)
  • Vincent Koc: Raw commit a53e1e8 adds src/infra/backup-create-stream.ts:170 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: a53e1e85a71b; files: src/infra/backup-create-stream.ts)
  • Abdel Gomez-Perez: Raw commit ed0df5b adds src/infra/backup-create-stream.ts:12 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ed0df5bf09b7; files: src/infra/backup-create-stream.ts)

PR surface

Source +66, Tests +34. Total +100 across 3 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 2 68 2 +66
Tests 1 34 0 +34
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 102 2 +100

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P2: Large backups have a reported CPU bottleneck and can exceed scheduling budgets, but this is a scoped performance improvement without an established urgent regression.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Large backups have a reported CPU bottleneck and can exceed scheduling budgets, but this is a scoped performance improvement without an established urgent regression.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Supply the real backup CLI comparison and round-trip evidence described above.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 14, 2026, 8:48 PM ET / November 15, 2026, 01:48 UTC.

Feed the archive file from a byte-mode stream so a slow disk holds a few blocks instead of a queue of members. Cover a multi-member archive through real create and restore, plus read-ahead and failed-block behavior.

Refs #183094
@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations size: M and removed size: S labels Nov 15, 2026
@vincentkoc
vincentkoc marked this pull request as ready for review November 15, 2026 02:53
@vincentkoc
vincentkoc merged commit 6f04753 into main Nov 15, 2026
208 of 209 checks passed
@vincentkoc
vincentkoc deleted the perf/backup-parallel-gzip branch November 15, 2026 03:32
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 15, 2026
…law#199367)

* improve(backup): compress archives on several threads

Backup archives were compressed by one gzip stream, so archive writing used one core regardless of host size. Split the tar stream into 4 MiB blocks and compress up to four at a time on the libuv pool, writing them as consecutive gzip members. The output is still a standard .tar.gz that existing verify, restore, and stock tar read unchanged.

Refs openclaw#183094

* improve(backup): bound parallel gzip read-ahead and prove the round trip

Feed the archive file from a byte-mode stream so a slow disk holds a few blocks instead of a queue of members. Cover a multi-member archive through real create and restore, plus read-ahead and failed-block behavior.

Refs openclaw#183094
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant