Skip to content

fix(worktrees): avoid slow APFS worktree cloning - #146401

Merged
steipete merged 2 commits into
mainfrom
codex/apfs-clone-performance
Sep 12, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/apfs-clone-performance

Conversation

@steipete

@steipete steipete commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Related: #146288. Follow-up to #146338. During validation, the TLS integration blocker was repaired independently by #146412; duplicate #146411 was closed. The final merged commit contains only the eight APFS-related files.

What Problem This Solves

Fixes managed APFS worktree creation taking longer than normal Git checkout, particularly in repositories with many small files.

User Impact

Warm worktrees retain copy-on-write storage savings and become faster to prepare. On a 41,655-path OpenClaw checkout, the first host comparison improved from 40.7 seconds to 3.52 seconds; normal Git controls took 8.13–13.69 seconds in the candidate run. A final three-run repeat took 3.90–5.49 seconds (median 4.16 s), with native controls of 9.64 s and 34.79 s on the variable shared host. Subsequent git status took 0.21–0.23 seconds, so validation was not deferred to the next command. Cold creation still pays for the initial Git template checkout.

Apple discourages general directory cloning through clonefile. This change uses that documented atomic API for managed source-only templates. Cancellation waits for an admitted native clone to settle before recovery touches its destination. Unsupported filesystems and clone failures retain Git fallback; unsupported index representations retain full Git validation. No configuration or dependency changes are required.

Why This Change Was Made

Replace the per-file JavaScript loop with one asynchronous native directory clone. Then translate only the copied Git index's file identity metadata where APFS proves the data stream is unchanged and the source's cached metadata still matches. Keep blob IDs, paths, modes, modification times and sizes; leave racy, unsupported or changed entries for Git's normal refresh. Preserve normal edit detection, including same-size edits with restored modification times on Git builds that compare timestamps at whole-second resolution.

The existing worktree service owns allocation, template validation, setup, registration and recovery. Git remains responsible for final index validation and branch state.

Evidence

  • Native directory-operation comparison on the same public source: whole-directory clonefile 0.675 s; existing JavaScript traversal without lease checks 6.77 s; recursive native copyfile 13.99 s. Rust would call the same native operation and is not needed.
  • Matched parent-process high-water RSS (process.resourceUsage().maxRSS) across the native/cold/warm/native sequence was 422 MiB before and 424 MiB after. This includes Node startup, fixture preparation and all creates in that process; it excludes Git child processes and is not a per-checkout or aggregate process-tree peak.
  • On the refreshed main integration, cached creates took 4.14 and 6.68 s versus native controls of 16.58 and 22.54 s; the next status took 0.25 and 0.73 s. The first accelerated call rebuilt the template after the effective Git command configuration changed during the rebase and took 26.39 s; that is a cold rebuild, not a warm sample.
  • Git TRACE2: warm update-index --refresh fell from 24.94 s to 0.082 s. Only 26 symlinks and one empty file required content verification.
  • Full native directory proof: 41,629 regular files, 26 symlinks and 1,978 directories; matching contents/modes, distinct inodes, shared data-stream IDs for all 41,628 nonempty regular files, and independent writes.
  • Focused native/portable tests: 24 passed after rebase (23 on the original base), with 3 Linux-only cases skipped on macOS. Coverage includes lifecycle, independent indexes, cancellation, SHA-1/SHA-256, exact restored modification times, racy entries and unsupported/damaged index fallback. Independent P0–P2 review found no actionable defect.
  • Full managed-service APFS/HFS+ proof passed: 124,884 clone-ID comparisons, matching file contents/modes/symlinks, independent Git indexes and writes, actual HFS+ fallback and cross-volume EXDEV. Warm clones allocated about 16–17 MiB versus about 654 MiB for native checkout on the isolated proof volume.
  • Final changed-file checks, pnpm build, and three supported pnpm openclaw worktrees create CLI runs passed, including index-v4 fallback.
  • Initial CI run 34716939627 is blocked by an unrelated main integration regression at server-startup-finish.ts:416: the TLS sidecar is passed as an array to a newly variadic registration API. The separate repair is fix(gateway): stop TLS renewal through its lifetime owner #146411. This branch has been rebased onto that prerequisite and newer main; fresh independent P0–P2 review, 24 focused tests, full build, and supported CLI proof of the integrated APFS delta all pass. CI is rerunning on the updated head.

These are measurements on one shared host, not universal speed guarantees. The first host comparison uses native APFS storage without disk images; disposable-volume proof measures physical sharing separately.

Kernel-source inspection used Apple-published XNU f6217f891ac0bb64f3d375211650a4c1ff8ca1ea:

  • clonefile_internal enforces absent destination, same mount and filesystem permissions, then calls VNOP_CLONEFILE once.
  • VNOP_CLONEFILE supplies the directory authorization callback, which operates on prefilled attributes without per-child vnodes.
  • getattrlist_internal obtains the requested file metadata and clone identity through one filesystem attribute operation. The documented clone ID uniquely identifies a data stream.

APFS's internal tree transaction and locking implementation is not public. The published XNU source predates the tested Darwin 27 kernel; full native proof validates behavior on the actual host.

The final combined-head CI is green: run34717840913, head 30f1f01dfc2ef29b040a7e752a7040767fcf05bf. The included TLS prerequisite also passed an isolated supported-CLI HTTPS startup/shutdown proof: verified health200, both actual renewal watchers stopped on SIGTERM, clean54ms Gateway shutdown, exit0, reusable port, and complete synthetic-state cleanup.

Merged as 9b59fe4ef7da6444059d4fe4651b14097f13ab59. Verified on current main. The final merge excludes the already-landed TLS repair (b405e7f644106306d2d3965ecf22335fdbe15716, #146412).

@clawsweeper

clawsweeper Bot commented Sep 12, 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.

@steipete
steipete marked this pull request as ready for review September 12, 2026 20:23
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Sep 12, 2026
@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 12, 2026, 5:14 PM ET / 21:14 UTC (Revision 3).

ClawSweeper review

What this changes

Accelerates macOS managed worktree creation with native APFS directory cloning and verified Git-index metadata updates, and includes the TLS cleanup registration prerequisite.

Merge readiness

✅ Ready for maintainer review

The performance fix remains useful, and no actionable correctness blocker was found. The added, explicitly scoped RSS comparison satisfies the previous review’s outstanding request.

Priority: P2
Reviewed head: 30f1f01dfc2ef29b040a7e752a7040767fcf05bf

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Strong native performance and correctness evidence supports a focused implementation with conservative fallback and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured macOS/APFS managed-service and supported CLI observations exercise the changed clone and index paths, showing faster warm creation, prompt subsequent Git status, independent writes/indexes, and real fallback behavior; the added RSS comparison completes the prior request.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured macOS/APFS managed-service and supported CLI observations exercise the changed clone and index paths, showing faster warm creation, prompt subsequent Git status, independent writes/indexes, and real fallback behavior; the added RSS comparison completes the prior request.
Evidence reviewed 9 items Previous proof request resolved: The supplied complete PR body and #146401 (comment) report matched parent-process high-water RSS of 422 MiB before and 424 MiB after. The measurement includes startup, fixture preparation, and the native/cold/warm/native sequence, and explicitly excludes Git children. This answers the retained rank-up request at the unchanged reviewed head. Captured context sourceRevision: bcf19f563b4dcac46d951b3b0a3268196a44a45e5b7e295dc5e501c17d2dae2e.
Real production-path evidence: The captured body reports actual managed-service and supported CLI creation on macOS/APFS: warm creation improved from 40.7 s to 3.52 s in the initial comparison; refreshed integration measured 4.14 and 6.68 s, with subsequent status at 0.25 and 0.73 s. It also records independent contents/indexes, 124,884 clone-ID comparisons, HFS+ fallback, EXDEV, and index-v4 fallback. These are reported real-host observations, not reviewer-executed tests or universal performance guarantees.
Conservative index translation: The parser validates checksums and supported representations; translation requires matching source metadata and shared APFS data-stream identity. Racy or unverified entries retain ordinary Git validation. The caller still runs update-index --refresh and retains checkout fallback.
Findings None None.
Security None None.

How this fits together

Managed worktrees turn repository revisions into isolated agent checkouts. The filesystem backend materializes source files, while the existing worktree service and Git retain allocation, registration, validation, and recovery ownership.

flowchart TD
  A[Repository revision] --> B[Managed worktree service]
  B --> C[Validated source template]
  C --> D[Native APFS directory clone]
  D --> E[Verify shared file identities]
  E --> F[Git index validation]
  B --> G[Normal Git fallback]
  G --> H[Independent agent checkout]
  F --> H
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +248, Tests +184, Docs +2. Total +434 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 5 297 49 +248
Tests 2 196 12 +184
Docs 2 5 3 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 498 64 +434

Review metrics

Metric Value Why it matters
Comparative memory 422 → 424 MiB parent-process peak RSS The scoped comparison resolves the prior memory-evidence request without claiming aggregate process-tree memory.
Production versus test growth Production +248 lines; tests +184 lines net Production growth implements conservative index parsing and native metadata verification, justified by measured reductions in clone and refresh time.

Technical review

Best possible solution:

Keep acceleration within the existing worktree lifecycle, using clone-proven metadata while preserving Git validation, independent checkouts, and normal fallback.

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

Yes: repeated managed-worktree creation on a large APFS repository exercises main’s per-file clone and index-refresh costs, corroborated by the supplied before/after measurements. This read-only review did not execute the runtime.

Is this the best way to solve the issue?

Yes: the patch removes the measured overhead within the existing backend, conservatively translates proven file identities, and retains Git fallback without adding configuration or another lifecycle owner.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster. Replaced prior rating: 🐚 platinum hermit.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P2: This is a bounded performance improvement for macOS managed worktree creation with demonstrated real-host benefit.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster. Replaced prior rating: 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured macOS/APFS managed-service and supported CLI observations exercise the changed clone and index paths, showing faster warm creation, prompt subsequent Git status, independent writes/indexes, and real fallback behavior; the added RSS comparison completes the prior request.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured macOS/APFS managed-service and supported CLI observations exercise the changed clone and index paths, showing faster warm creation, prompt subsequent Git status, independent writes/indexes, and real fallback behavior; the added RSS comparison completes the prior request.

Evidence

What I checked:

  • Previous proof request resolved: The supplied complete PR body and fix(worktrees): avoid slow APFS worktree cloning #146401 (comment) report matched parent-process high-water RSS of 422 MiB before and 424 MiB after. The measurement includes startup, fixture preparation, and the native/cold/warm/native sequence, and explicitly excludes Git children. This answers the retained rank-up request at the unchanged reviewed head. Captured context sourceRevision: bcf19f563b4dcac46d951b3b0a3268196a44a45e5b7e295dc5e501c17d2dae2e. (30f1f01dfc2e)
  • Real production-path evidence: The captured body reports actual managed-service and supported CLI creation on macOS/APFS: warm creation improved from 40.7 s to 3.52 s in the initial comparison; refreshed integration measured 4.14 and 6.68 s, with subsequent status at 0.25 and 0.73 s. It also records independent contents/indexes, 124,884 clone-ID comparisons, HFS+ fallback, EXDEV, and index-v4 fallback. These are reported real-host observations, not reviewer-executed tests or universal performance guarantees. (src/agents/worktrees/checkout.ts:279, 30f1f01dfc2e)
  • Conservative index translation: The parser validates checksums and supported representations; translation requires matching source metadata and shared APFS data-stream identity. Racy or unverified entries retain ordinary Git validation. The caller still runs update-index --refresh and retains checkout fallback. (src/agents/worktrees/checkout-apfs.ts:140, 30f1f01dfc2e)
  • Allocation and cancellation ownership: The backend checks live allocation authority after source inspection, awaits the admitted native operation, then checks authority again. The service supplies its renewable allocation-lease guard; checkout recovery refuses mutation after authority loss. Native tests cover rejection before dispatch and joining an admitted clone before reporting cancellation. (src/agents/worktrees/filesystem-backend.ts:98, 30f1f01dfc2e)
  • Native dependency contract: The patch directly invokes Darwin clonefile, establishing the dependency signal. Apple's pinned implementation accepts directories, rejects existing destinations and cross-mount cloning, checks filesystem authorization, and invokes VNOP_CLONEFILE. This source does not expose APFS's internal implementation or replace the supplied real-host evidence. (bsd/vfs/vfs_syscalls.c:9037, f6217f891ac0)
  • Current main still needs the optimization: The fetched main retains recursive per-file APFS cloning and the unmodified index-copy path. The merged baseline feat(worktrees): share source storage with APFS clones #146338 provides storage sharing but explicitly documented slower creation; it does not supersede this performance work. (src/agents/worktrees/filesystem-backend.ts:79, d093d651f71d)

Likely related people:

  • Peter Steinberger: Raw commit ca88f96 adds src/agents/worktrees/filesystem-apfs.native.ts:17 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ca88f96389bc; files: src/agents/worktrees/filesystem-apfs.native.ts)

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 (2 earlier review cycles)
  • reviewed 2026-09-12T20:30:20.175Z sha 394adf4caff739eada826f406798b36594f64c6e :: blocked before merge. :: none
  • reviewed 2026-09-12T20:48:42.906Z sha 30f1f01 :: blocked before merge. :: none

Pass the renewal handle directly to the variadic gateway lifetime owner. This completes the integration between TLS renewal (#146267) and the sidecar ownership refactor (#146275), repairing TS2741 and retaining working TLS watcher cleanup.
@steipete
steipete force-pushed the codex/apfs-clone-performance branch from 394adf4 to 30f1f01 Compare September 12, 2026 20:41
@clawsweeper clawsweeper Bot added 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 12, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Added the requested comparative peak RSS evidence to the PR body: 422 MiB before and 424 MiB after for the matched native/cold/warm/native benchmark process, using process.resourceUsage().maxRSS. The measurement scope is explicit: Node startup, fixture preparation and all creates; excludes Git children and is not an aggregate process-tree peak. The existing architecture and conservative validation remain unchanged.

The refreshed main integration also passed 24 focused tests, a full build, and the supported CLI proof. Its cached creates took 4.14 and 6.68 seconds; the one-time template rebuild after the configuration fingerprint changed is reported separately as cold. Native controls and follow-up status times remain in the body to make the shared-host variability visible.

@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@steipete
steipete merged commit 9b59fe4 into main Sep 12, 2026
204 of 205 checks passed
@steipete
steipete deleted the codex/apfs-clone-performance branch September 12, 2026 21:21
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 13, 2026
* fix(gateway): register TLS renewal with its sidecar owner

Pass the renewal handle directly to the variadic gateway lifetime owner. This completes the integration between TLS renewal (openclaw#146267) and the sidecar ownership refactor (openclaw#146275), repairing TS2741 and retaining working TLS watcher cleanup.

* perf(worktrees): accelerate APFS directory cloning
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 gateway Gateway runtime 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