Skip to content

fix(sandbox): avoid snapshot overhead for fast checkpoints - #196727

Merged
steipete merged 4 commits into
mainfrom
steipete/fix-checkpoint-capture-cost-2372
Nov 10, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/fix-checkpoint-capture-cost-2372

Conversation

@steipete

@steipete steipete commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Related: #196662

Maintainer decision: land on the counterbalanced pilot evidence. Final measurement acceptance remains pending because shared-host contention and unstable A/A controls prevented a qualified full campaign.

What Problem This Solves

Taking and recursively removing a full btrfs snapshot on every changed command reduced container pauses but added 28% command latency and CPU in the original 62,000-file benchmark. Small workspaces should not pay that snapshot cost.

User Impact

Small, fast checkpoints keep direct paused capture. Expensive checkpoints retain atomic capture and resume before scanning. Commands still wait for canonical acceptance; after runtime resume, the workspace lease renames the disposable capture to a unique retired path and hands cleanup to the existing run-end lifetime. The next command can execute during deletion; the next snapshot waits for pending cleanup and retries interrupted removals before creating another artifact.

Cleanup keeps the existing native recursive remover and needs no new utility, privilege or mount option. Snapshot creation can still wait for dirty writeback, and nested subvolumes retain the complete paused fallback.

Why This Change Was Made

The manifest worker already knows the accepted entry count. It now carries that fact on an early-aborting probe, so a large tree is recognized even when the changed pathname sorts first. A 20,000-entry inventory or a probe lasting 500 ms selects snapshots. No additional scan, persistent cache, schema, or configuration is introduced. Recovery and initial layout capture without probe facts remain on the direct path.

Canonical writes retain session authority. The lease transfers only an immutable, disposable artifact to independent cleanup. Unique retired names prevent delayed deletion from touching a later capture. Pending promises track active work, not cached scan results; persistent removal failures prevent another snapshot from growing the backlog. A rolling snapshot cannot be refreshed by the current immutable-copy primitive, and an early probe is not a complete changed-path set for safe selective reflinks.

The snapshot manifest scan also avoids one asynchronous filesystem dispatch per metadata read inside the existing capture worker. A shared 32-read yield services cancellation; the main thread and non-snapshot scans retain asynchronous reads. File hashing, identity and containment checks are unchanged.

Evidence

Two regressions fail on the parent: small btrfs checkpoints unnecessarily invoke snapshots, and completed commands remain blocked behind capture deletion. On the candidate all 9 checkpoint scenarios pass, including interrupted acceptance, nested fallback, later guest writes, canonical read-after-command, bounded cleanup custody and caller disposal. Native filesystem owner tests: 10/10. The broader projection owner run passed 83 tests with 2 platform skips; its one obsolete always-snapshot recovery expectation was corrected and replayed green.

The next-command overlap regressions additionally fail on preliminary head a04f5a3 with OPENCLAW_STATE_LEASE_HELD, then pass on the retired-path handoff. Final staged candidate Codex autoreview is scoped-clean through P2. Production delta: +125 LOC: 103 for adaptive capture and bounded lifetime transfer/recovery, plus 22 for worker metadata reads. Tests: +205 LOC, including real-worker scan equivalence and cooperative cancellation; the two scanner/worker test files pass all 45 tests. The checkpoint test registrations move to their existing fixture module to stay within the file limit without dropping coverage.

pnpm check:changed --base 4ec97ef5e73e0780cb0d9a70d096a1bba5600027 completed on the final candidate: all categories pass except the inherited unused-export scans. Both reproduce on the exact parent with identical 28/8 symbol sets and attributed introducing commits. These are existing main regressions. The runtime build also passes. The nine checkpoint cases take 57.24 s including cold compilation (54.17 s Vitest duration, 63% transform and 35% tests); they exercise the actual SQLite lease and lifecycle boundary. The maintainer explicitly accepted the pilot for landing; the incomplete final native campaign remains a measurement limitation, not completed proof.

The exact 205 regression lines have a justified allocation record, and the test-line guard passes against the branch parent. Final-head CI run 42859153410 passes every job except baseline-ratchets and its dependent CI gate. The exact CI main parent ecbad2efa1d7e89d041965612b2237760a024c50 independently reproduces 18 lines of debt: 6,632,310 test lines against a 6,632,292 ceiling. #196680 (3686da563c54738b11fac5c9a103ee8b3943b5e6) introduced 21 lines of debt; #196636 and #196742 paid down three. This PR adds 205 test lines and 205 credit, leaving the inherited debt unchanged. This remains a named main regression.

Final-head CodeQL and OpenGrep initially completed analysis but failed while uploading SARIF because of GitHub installation API rate limits. Only those failed jobs were rerun after diagnosis; both workflows succeeded on attempt 2. No security exception or alert dismissal was used. ClawSweeper reviewed the final source head and reports zero findings.

Native measurement acceptance, recorded before the campaign

Final performance results are pending. The first complete adaptive/cleanup campaign passed small-workspace latency and large pause goals, but did not establish a CPU improvement over the snapshot-every-command implementation, so it was held. A counterbalanced 20-command metadata pilot reduced command median from 2623 to 2088 ms and cgroup CPU from 4694 to 3346 ms/command; snapshot scan time fell from 1517 to 999 ms. All read checks passed. These are pilot results, not the final acceptance campaign.

The first final-head small campaign was affected by another benchmark becoming active in the shared Docker VM. All consistency checks passed, but the whole attempt is retained as contended evidence, not performance acceptance. Subsequent quiet 10/10 controls still differed by 24.7% in command median, despite only 4.6% CPU variation. Recorded phases place most variation in command/engine control and staging waits; manifest scan stayed at 23 ms. Those controls are retained. One explicitly recorded small-workspace protocol revision uses the unchanged driver with 10 warmup and 50 measured commands per arm (--requests 5), improving sample resolution without assuming a warmup cause. The large protocol stays 10/10; outcome targets are unchanged. The revised first control passed correctness but failed its independent resource gate: another workload consumed 34.43 CPU-seconds and 563.85 MB reads during 60.22 seconds. No second control or paired campaign followed. All native timing is now idle pending a reserved quiet interval; no favorable subset or repeated-until-green controls will be selected.

The selected runtime and extended worker-allocation driver are pinned to 12227a56a740261516bb036efcad77fa8078837f. Fresh full-candidate Codex autoreview is scoped-clean through P2; runtime build, targeted checks and the 205-line test allocation pass. The maintainer accepted the pilot for landing at this exact head under the review/security gates and the documented inherited-CI exception. Pilot command median 2.09 s is below the earlier pre-#196662 baseline of 2.37 s, but that comparison is across campaigns, not a qualified final paired comparison. Pilot pause p95 is 223 ms, cgroup CPU improves 28.7%, and all consistency checks pass. Shared-host noise leaves final two-regime acceptance, worker allocation and writeback diagnostics pending. The committed driver is scripts/perf/local-workspace-checkpoint-measure.ts; writeback diagnostics use scripts/perf/local-workspace-snapshot-writeback.py.

Use real Podman+btrfs, 62,000 files/1.1 GB and 100 files/400 KiB, with the same approximately 35 GiB synthetic agent database and 10,000 sessions. Compare pre-#196662 source 3f17d92, shipped 10d6744, and this pinned candidate. Each large formal arm has 10 warm-up and 10 measured mutating commands; the revised small arms have 10 warm-up and 50 measured commands, with canonical and next-guest read checks throughout. Run A/A controls and five counterbalanced baseline/candidate pairs per regime; retain slow and failed arms.

Small-workspace command median must match or improve the pre-change baseline within measured A/A spread, with zero snapshots. Large-workspace pause p95 must be at most 300 ms, with command latency and total CPU materially below the snapshot-every-command implementation. Report remaining differences from the pre-change baseline explicitly. No 20% latency/CPU regression is accepted implicitly.

Include the final cleanup tail outside per-command latency but inside burst CPU/wall accounting. Wait for btrfs kernel deletion work and report whole-VM CPU as well as cgroup CPU, since kernel cleaner work can escape container accounting. Measure allocation separately and keep instrumented profiles out of plain latency results. Dirty-writeback tests compare source churn at 1.7 GB/hour, explicit pre-syncfs, and separately labeled 1.1 GB bursts; they cannot retrospectively attribute an untraced historical pause.

ClawSweeper gate: address every open item by number and obtain zero open items on the final head before merge.

@clawsweeper

clawsweeper Bot commented Nov 10, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts docker Docker and sandbox tooling size: M labels Nov 10, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 10, 2026
Transfer accepted captures to unique retired paths under the projection lease, then use the existing independent run-end lifetime for deletion. Join pending deletion before another capture, retaining bounded failure recovery while allowing the next command to run.

Preserve canonical read-after-command ordering. Remove the privileged deletion shortcut and qualify native proof with unprivileged filesystem work and separate kernel settlement accounting.
@steipete
steipete marked this pull request as ready for review November 10, 2026 15:44
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-10T16:55:50.467443Z 12227a5 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 10, 2026
@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR selects direct capture for fast checkpoints, defers disposable snapshot cleanup, and reduces snapshot-worker metadata overhead.

Example: A command edits a file in a 100-file btrfs workspace and its probe finishes below 500 ms.

  • Before: Checkpointing creates and removes a full snapshot before command completion.
  • After: Checkpointing uses direct paused capture and still waits for canonical acceptance.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The implementation is coherent and the prior finding is resolved, but the declared final performance acceptance remains unproven.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Changed sandbox commands incur snapshot and cleanup overhead even when their workspaces are small.
Reason: The preceding native comparison establishes a concrete cost, and the maintainer-authored direction preserves the existing consistency contract without adding configuration.

Regression provenance

Regression provenance — verified: source commit 10d67445fbec by Peter Steinberger; canonical PR #196662 (blame-to-merge-commit).

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses measured checkpoint overhead, and source review found no actionable introduced defect.

Priority: P2
Reviewed head: 12227a56a740261516bb036efcad77fa8078837f

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The final pinned Podman+btrfs comparison remains outstanding for both workspace sizes, including canonical and next-guest reads, cleanup settlement, whole-VM CPU, and separate allocation accounting.
Agent review details

How this fits together

Sandbox command finalization sends workspace changes through the projection owner, which captures files, reconciles them into the canonical checkout, and resumes the runtime.

flowchart TD
  A[Sandbox command] --> B[Checkpoint owner]
  B --> C[Existing manifest probe]
  C --> D[Direct or snapshot capture]
  D --> E[Canonical acceptance]
  E --> F[Command completion]
  E --> G[Retired capture cleanup]
Loading

Technical review

Best possible solution:

Keep adaptive capture and retired cleanup in the existing checkpoint owner while preserving canonical acceptance, cancellation, and bounded artifact cleanup.

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

Current main selects snapshot capture for changed btrfs checkpoints and awaits deletion; the preceding merged PR records the resulting latency and CPU cost, but this review ran no target code.

Is this the best way to solve the issue?

Selecting capture from existing probe facts removes unnecessary snapshots, while the existing lifecycle owner can delete uniquely retired artifacts without delaying canonical acceptance; the worker change preserves metadata and cancellation contracts.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Snapshot selection and synchronous cleanup changes intended behavior with a stated reason (10d6744: Resume btrfs guests before manifest scanning while preserving immutable capture and canonical acceptance.)
  • Unchanged checkpoint probing keeps the original intent (df73fef: Avoid pausing commands whose accepted workspace contents are unchanged; this PR carries an existing inventory fact through that probe.)
  • Manifest metadata scheduling changes intended behavior with a stated reason (ac8c661: Overlap sibling metadata operations within bounded discovery batches; snapshot-worker synchronous reads now target measured dispatch overhead while retaining bounded cancellation yields.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +125, Tests +205, Docs +70, Other +308. Total +708 across 16 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 6 139 14 +125
Tests 4 238 33 +205
Docs 2 77 7 +70
Config 0 0 0 0
Generated 0 0 0 0
Other 4 327 19 +308
Total 16 781 73 +708

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.

Review metrics

Metric Value Why it matters
Production versus regression growth Production +125 net LOC; tests/support +205 net LOC Growth implements adaptive capture, bounded cleanup handoff, and worker metadata scheduling, with distinct ordering, failure-recovery, equivalence, and cancellation regressions.

Labels

Label changes:

  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit. Replaced prior rating: 🧂 unranked krab.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦪 silver shellfish, so this older rating label is no longer current.

Label justifications:

  • P2: The measured overhead affects sandbox checkpoint latency and CPU without evidence of lost files or broken command completion.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit. Replaced prior rating: 🧂 unranked krab.
  • 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.

  • Complete the pinned native comparison against the recorded acceptance criteria, including final cleanup and whole-VM CPU accounting.

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.

History

Review history (2 earlier review cycles)
  • reviewed 2026-11-10T16:00:31.269Z sha 4e94243 :: needs changes before merge. :: [P2] Allocate the added regression-test lines
  • reviewed 2026-11-10T16:22:13.156Z sha 90738a9 :: needs maintainer review before merge. :: none

Reviewed November 10, 2026, 11:59 AM ET / 16:59 UTC (Revision 3).

Allocate the exact 137 new regression lines for adaptive capture, next-command overlap, caller disposal and bounded cleanup recovery. Keep the shared baseline unchanged and do not allocate inherited main debt. The exact test-line guard passes against the branch parent; independent Codex review is clean.
@steipete

Copy link
Copy Markdown
Contributor Author

Addressed the latest review's one open item on head 90738a9e76c0906191ee8e64a7b89cd67d3acc5f:

  1. Allocate the added regression-test lines (P2): checkpoint-adaptive-retirement.txt, lines 1–4 grants exactly the 137 new test lines and explains the distinct adaptive-capture, next-command overlap, caller-disposal and recovery contracts. The shared scalar and all regression cases remain intact. pnpm check:test-lines-ratchet --base 4ec97ef5e73e0780cb0d9a70d096a1bba5600027 --no-merge-base passes: 6,629,089 lines against 6,629,098, preserving the parent's nine-line headroom. Independent Codex review of this correction is scoped-clean through P2.

The earlier CI main parent ac7e941722ab32fcf019ef257fc52819fa71da07 independently reproduces 21 lines of inherited debt. #196680 (3686da563c54738b11fac5c9a103ee8b3943b5e6) added 28 UI test lines without allocation, crossing seven lines of headroom. This is recorded as a separate main regression; this PR does not grant extra credit for it.

The formal native performance campaign is still running. The budget-only commit changes no runtime or benchmark bytes, so the pinned 4e94243a1126e0ae0c944783ed8023ac6fd8ff40 measurements apply to this head. Merge remains held for the declared performance proof and security/CI disposition.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 10, 2026
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 10, 2026
Read snapshot metadata directly in the capture worker with a shared bounded yield for cancellation. Preserve asynchronous metadata reads on the main thread and non-snapshot scans. Extend native allocation proof to account for workers and cover scan equivalence and cancellation.
@steipete

Copy link
Copy Markdown
Contributor Author

The final source candidate is 12227a56a740261516bb036efcad77fa8078837f. It adds bounded worker-local metadata reads after the first full native campaign showed that asynchronous cleanup alone did not establish a CPU improvement. The counterbalanced pilot reduced command median by 20% and cgroup CPU by 29%; the final campaign remains a merge gate.

  1. The earlier test-allocation finding remains fixed: the allocation record now covers exactly 205 added regression lines, including worker equivalence and cooperative cancellation. The branch-parent test-line guard passes with nine lines of slack.

All 45 scanner/worker tests, focused type/lint checks, the runtime build and fresh full-candidate Codex autoreview pass. The PR body records the unchanged acceptance criteria and pending final native proof. Please review the new worker path and allocation instrumentation at this head.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 10, 2026
@steipete
steipete merged commit d7f90ec into main Nov 10, 2026
190 of 200 checks passed
@steipete
steipete deleted the steipete/fix-checkpoint-capture-cost-2372 branch November 10, 2026 18:17
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 11, 2026
…196727)

* fix(sandbox): avoid snapshot overhead for fast checkpoints

* fix(sandbox): retire checkpoint captures outside the command lease

Transfer accepted captures to unique retired paths under the projection lease, then use the existing independent run-end lifetime for deletion. Join pending deletion before another capture, retaining bounded failure recovery while allowing the next command to run.

Preserve canonical read-after-command ordering. Remove the privileged deletion shortcut and qualify native proof with unprivileged filesystem work and separate kernel settlement accounting.

* test(sandbox): budget checkpoint retirement regressions

Allocate the exact 137 new regression lines for adaptive capture, next-command overlap, caller disposal and bounded cleanup recovery. Keep the shared baseline unchanged and do not allocate inherited main debt. The exact test-line guard passes against the branch parent; independent Codex review is clean.

* perf(sandbox): reduce snapshot worker metadata overhead

Read snapshot metadata directly in the capture worker with a shared bounded yield for cancellation. Preserve asynchronous metadata reads on the main thread and non-snapshot scans. Extend native allocation proof to account for workers and cover scan equivalence and cancellation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. docker Docker and sandbox tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: L 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