Skip to content

perf(worktrees): speed up snapshot restore and repeated creation - #146765

Merged
steipete merged 2 commits into
mainfrom
codex/worktree-restore-perf
Sep 13, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/worktree-restore-perf

Conversation

@steipete

@steipete steipete commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Restoring a saved managed worktree rebuilt the entire source template, making even a small edit pay for another full checkout. Repeated creation also recomputed unchanged Git object sizes and index paths.

User Impact

Managed worktrees restore faster while retaining the original branch history, unstaged edits, untracked files, and provisioned files. Disk admission, missing-object checks, cancellation, and template cleanup remain enforced. No configuration or migration is required.

Why This Change Was Made

Restore reuses the original commit's source template when available and lets Git apply the snapshot differences. Otherwise Git materializes the snapshot directly, avoiding an obsolete parent checkout. If the snapshot changes .gitattributes, Git rematerializes the full snapshot so unchanged blobs receive the correct transformations; admission includes that allocation. Oversized diff inventories use the same conservative full-snapshot fallback without raising the Git output limit.

The existing Git worker retains up to 32 successful commit-size estimates, checks object availability on every request, and bypasses cached totals when replacement refs are present. Worker shutdown discards the cache. Checkout also reuses its resolved source index path and avoids repeated APFS path normalization and timestamp conversions.

Related: #146722, #146723.

Evidence

  • Live APFS comparison using the full repository: 41,887 files, 569 MB. Restore fell from 16.824 s to 4.739 s; the old path spent 11.973 s deleting/rebuilding its template, while the new Git overlay took 542 ms. Both runs passed 167,444 file-hash checks, plus symlink/mode, branch, dirty/untracked restore, and cleanup checks. Restore RSS was 607.6 / 617.3 MiB. Warm creation measured 5.093 / 2.354 s. These are matched observations under variable host load, not universal latency guarantees.
  • 32,768-file size-estimation controls: packed objects 96.27 → 62.65 ms; loose objects 2,209.78 → 153.16 ms. Packed-run median RSS 166.3 → 167.3 MB. Live missing-object and replacement-ref checks remained enabled.
  • Focused owner suites passed, including the existing 180,000-entry Git-index restore regression; one Linux-only raw-filename case was skipped on macOS. Coverage includes native APFS edit detection, low-space restore/fallback, partial clones, replacement refs, file/directory transitions, provisioning, shallow history, hooks, cancellation, and retryable recovery. The template-reuse regression failed on the original code. The ordinary-Git full-repository restore also passed 167,444 hash checks. A deleted-file/filter regression proved that fallback restore no longer materializes obsolete source files.
  • Seven ordinary-Git fixture failures were reproduced on unchanged main: APFS template creation consumed their injected checkout failures. Those fixtures now explicitly select ordinary Git; the acceleration suite continues to exercise the accelerated lifecycle.
  • Initial CI found a real scale regression: 180,000 deleted paths exceeded the bounded diff output. The estimator now reserves the full target on that condition, and restore avoids constructing a cold parent template; the existing large-index regression passes locally.
  • Independent review through P2 completed with no remaining actionable findings. Changed-file formatting, typechecks, lint, and repository guards were run locally; exact-head CI is linked by GitHub.

@steipete steipete self-assigned this Sep 13, 2026
@clawsweeper

clawsweeper Bot commented Sep 13, 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 agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Sep 13, 2026
@steipete
steipete marked this pull request as ready for review September 13, 2026 05:19
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 13, 2026
@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 13, 2026, 1:56 AM ET / 05:56 UTC (Revision 2).

ClawSweeper review

What this changes

Speeds up managed worktree creation and snapshot restoration by reusing clean source templates, applying saved differences through Git, and caching bounded size estimates.

Merge readiness

✅ Ready for maintainer review

The prior checkout-failure finding is addressed, and no remaining actionable defect was found. This useful optimization remains distinct from current main and the two related merged PRs.

Priority: P2
Reviewed head: 4fb7d12208588def79109ab449906cf05ddb400f

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, well-supported optimization whose prior actionable finding is resolved, with no remaining blocking correctness concern found.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied evidence exercises managed-service restore and creation on real APFS and ordinary Git, reports improved restore latency, and verifies saved contents, branch history, modes, symlinks, and cleanup; focused regression tests supplement those observations.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied evidence exercises managed-service restore and creation on real APFS and ordinary Git, reports improved restore latency, and verifies saved contents, branch history, modes, symlinks, and cleanup; focused regression tests supplement those observations.
Evidence reviewed 7 items Prior finding addressed: The follow-up commit adds deferGitCheckout, so initial registration uses --no-checkout and unavailable source-file filters cannot fail during initial materialization. Snapshot materialization now happens inside restore's existing cleanup scope. This resolves the specific failure mechanism in the previous review without requiring its suggested branch-delay implementation.
Restore and recovery coverage: Reviewed tests exercise template retention with successful and failed clones, changed checkout attributes, an unavailable filter on a deleted source file, and cancellation followed by successful retry. Existing service coverage checks preserved provisioned bytes, unstaged/untracked contents, shallow history, and rejection without overwriting a recreated foreign branch.
Conservative allocation and bounded cache: Object hydration remains ahead of cached size lookup; replacement refs disable reuse. The cache holds at most 32 totals. Attribute changes and oversized diff output select full-target admission and rematerialization instead of trusting a partial inventory.
Findings None None.
Security None None.

How this fits together

Managed worktrees give agent tasks isolated Git checkouts and preserve their contents before removal. The restore service combines saved Git snapshots and provisioned-file records to recover the original branch and working files.

flowchart TD
  A[Restore request] --> B[Saved snapshot and file records]
  B --> C[Object and disk admission]
  C --> D{Reusable clean template?}
  D -->|Yes| E[Clone source and apply differences]
  D -->|No| F[Materialize saved snapshot]
  E --> G[Restore provisioned files]
  F --> G
  G --> H[Original branch with saved working edits]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +241, Tests +224, Docs +2. Total +467 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 8 308 67 +241
Tests 5 250 26 +224
Docs 1 3 1 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 561 94 +467

Review metrics

Metric Value Why it matters
Production versus test growth production +241 net lines; tests +224 net lines Production growth implements bounded transition estimation and restore fallback handling within the existing owners.
Observed APFS restore 16.824 s → 4.739 s The supplied paired full-repository observations show a substantial improvement with content validation, while explicitly acknowledging variable host load.

Technical review

Best possible solution:

Keep Git as the restore owner while reusing clean templates, preserving snapshot contents and branch history, and retaining conservative full-checkout fallbacks.

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

Not applicable as a remaining correctness bug; this is a performance optimization supported by supplied paired real-service measurements and current-source inspection.

Is this the best way to solve the issue?

Yes. The patch extends the existing checkout and Git-worker owners, preserves stored formats and settings, and handles attribute changes and oversized inventories conservatively.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a measured performance improvement to managed worktree creation and recovery with a bounded product surface.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The supplied evidence exercises managed-service restore and creation on real APFS and ordinary Git, reports improved restore latency, and verifies saved contents, branch history, modes, symlinks, and cleanup; focused regression tests supplement those observations.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied evidence exercises managed-service restore and creation on real APFS and ordinary Git, reports improved restore latency, and verifies saved contents, branch history, modes, symlinks, and cleanup; focused regression tests supplement those observations.

Evidence

What I checked:

  • Prior finding addressed: The follow-up commit adds deferGitCheckout, so initial registration uses --no-checkout and unavailable source-file filters cannot fail during initial materialization. Snapshot materialization now happens inside restore's existing cleanup scope. This resolves the specific failure mechanism in the previous review without requiring its suggested branch-delay implementation. (src/agents/worktrees/checkout.ts:337, 4fb7d1220858)
  • Restore and recovery coverage: Reviewed tests exercise template retention with successful and failed clones, changed checkout attributes, an unavailable filter on a deleted source file, and cancellation followed by successful retry. Existing service coverage checks preserved provisioned bytes, unstaged/untracked contents, shallow history, and rejection without overwriting a recreated foreign branch. (src/agents/worktrees/service.acceleration.test.ts:483, 4fb7d1220858)
  • Conservative allocation and bounded cache: Object hydration remains ahead of cached size lookup; replacement refs disable reuse. The cache holds at most 32 totals. Attribute changes and oversized diff output select full-target admission and rematerialization instead of trusting a partial inventory. (src/agents/worktrees/capacity.runtime.ts:151, 4fb7d1220858)
  • Real performance and preservation evidence: The supplied complete PR body, captured under sourceRevision af598a7bd9d970b388d9866be0eb4aa313578f4c473be0ae4ad6e34eebc5a755, reports a real full-repository APFS restore comparison of 16.824 to 4.739 seconds, 167,444 file-hash checks per variant, branch/mode/symlink/content checks, and RSS measurements. It also reports an ordinary-Git full-repository restore with matching hash checks. These are contributor-recorded observations, not executions performed by this review.
  • Still necessary on current main: Fetched main still passes the snapshot ref into checkout creation and computes commit sizes without this cache. The merged related work at perf(worktrees): avoid redundant checkout waits and Git queries #146722 and improve(worktrees): reduce removal time and warm clone disk requirements #146723 improves timestamp waits, Git queries, removal, and clone admission; neither supplies this restore overlay. (src/agents/worktrees/service.ts, a2e647d5136f)
  • Merged area history: Current-main history contains repeated worktree changes by Peter Steinberger. GitHub identifies steipete on the merged checkout-latency commit and shows its exact deadline change against parent 28ac613, matching the locally inspected raw parent record. (src/agents/worktrees/checkout-apfs.ts:139, 7e179352d9a2)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-13T05:28:20.978Z sha 38323f2 :: blocked before merge. :: [P2] Create the restore branch only after checkout succeeds

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 13, 2026
@steipete
steipete merged commit 3ffc015 into main Sep 13, 2026
319 of 322 checks passed
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

@steipete
steipete deleted the codex/worktree-restore-perf branch September 13, 2026 06:11
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
…nclaw#146765)

* perf(worktrees): speed up snapshot restore and repeated creation

* fix(worktrees): bound restore inventories and defer obsolete checkouts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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