Skip to content

perf(worktrees): reuse sandbox dependency templates - #164517

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-worktree-deps-provisioning-20260919
Oct 3, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-worktree-deps-provisioning-20260919

Conversation

@steipete

@steipete steipete commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fresh sandboxed managed worktrees repeatedly install the same pnpm dependencies before an agent can run repository code. The sandbox executes a private Git checkout, so warming only the canonical host worktree does not reach it.

User Impact

New Docker/Podman private checkouts on supported copy-on-write filesystems arrive with dependencies after the first checkout prepares their generation. Existing sessions retain their files and do not wait behind a cold template installation. worktreeAcceleration: false also disables dependency preparation; no new configuration is added.

Why This Change Was Made

Prepare the independent Git checkout and frozen pnpm install once in a disposable sandbox, then clone that template into each private session checkout. The generation includes the selected commit, lockfile hash, immutable sandbox image (guest Node/package-manager versions), guest workdir, and installation policy. The existing template registry, allocation lease, and seven-day GC own preparation and retirement; the old inline projection Git preparation and separate source-template lifecycle implementation are replaced by shared owners. Template registry access now runs through the existing SQLite worker broker.

The builder receives no configured environment credentials, custom binds, or setup command, and its Git metadata is mounted read-only. Host ignored-file provisioning and unsandboxed operator.admin setup authority remain unchanged. Only real node_modules directories, independent of Git ignore spelling, are retained as additional template output; all tracked source, including the frozen lockfile and ignore rules, must remain unchanged. Failed installation or source mutation records a warning and caches a clean source-only fallback for the generation. Cleanup must retire the builder before publication or deletion. Sandboxes configured with network: none use offline installation: a real cold probe failed promptly in 0.22 s, while ordinary installation was still retrying after 30 s.

Installation and consumption use the same guest /workspace path. pnpm absolute shims therefore need no relocation. Native-protocol stamps also remained valid in the whole-tree experiment, but production deliberately removes those generated outputs outside node_modules; native work regenerates them normally. A plain read-only host-store trial did not satisfy this workload's offline metadata/store contract.

Production LOC grows because preserving the source-only host boundary requires a separate credential-free guest installer with durable cancellation/cleanup custody, a precise dependency-output invariant, and worker-backed registry access. Unsupported external pnpm virtual stores fall back instead of publishing broken links, and missing cache directories rebuild through the same owner. The change does not add a second setup owner or a writable shared package cache. Production delta under the requested exclusions: +1009/-213, net +796 lines.

Evidence

Linux Btrfs/Podman rig, Node 24.21.0, pnpm 12.5.1, OpenClaw's common sandbox image (irrelevant Brew/Bun installation omitted), isolated synthetic state. Rootful Podman used guest 0:0 for root-owned rig fixtures; no host credentials or package store were mounted. Real flow: ManagedWorktreeService.create → persisted sandbox-required session → resolveSandboxContext → sandbox exec → node --import ./scripts/tsx.mjs -e "import('./src/agents/worktrees/checkout-policy.ts')".

Time to working repository import Before After
First worktree per generation 90.885 s 86.056 s
Second worktree per generation 77.961 s 38.749 s
Isolated snapshot/container/dependency boundary 21.93 s 1.50 s / 1.47 s

The full-flow numbers include source-worker startup and private checkout preparation, not model or full RPC latency. The second before case briefly overlapped another check process; the narrower boundary measurements were uncontended. The first generation still pays the installation cost. A subsequent frozen install reused all dependencies without relinking in 3.74 s. Cold install peak RSS was about 1 GiB; prepared imports used about 217 MiB.

Ten Btrfs snapshots added zero data bytes and 327,680 physical metadata bytes. btrfs filesystem du --raw reported zero exclusive bytes for every checkout; ordinary du reported approximately 6.53 GB per checkout because it counts shared extents repeatedly.

Live proof passed: lockfile commit creates a new template and retires its predecessor; consumer edits do not alter siblings; forced install failure preserves clean source and excludes partial modules/host credentials; a second failed-generation checkout reuses that fallback; an existing projection resumes while the global allocation lease remains held. No production host was modified.

Testbox provider: blacksmith-testbox, initial validation lease tbx_01m41fyp8ctey5d3z3fej78rd8; final validation lease tbx_01m41nn12z0g49mnqycyr54dqm. Queued leases that disappeared were replaced; active leases were stopped before base changes. Installed frozen dependencies once in the independently synchronized checkout.

  • New dependency-template owner tests: 8 passed; about 1.6 s test execution, 19.78 s Vitest wall / 21.30 s command wall including cold worker preparation.
  • Review regressions: the three cases for ignored children, missing template directories, and external virtual stores all failed on the pre-fix implementation and passed on the current implementation (17.50/17.52 s Vitest wall, 43.82 s total Testbox command).
  • New sandbox installer tests: 6 passed; 0.074 s test execution, 1.24 s Vitest wall / 2.00 s command wall.
  • Existing filesystem acceleration tests: 21 passed, 22.52 s wall.
  • Existing projection reconciliation tests: 21 passed; optional live container test skipped on Testbox (real Podman flow independently proven on rig).
  • Existing registry tests: 2 passed.
  • Sandbox custody regression: 1 passed, 9.15 s Vitest wall.
  • PR wrapper inventory: 1 passed, 3.07 s Vitest wall (remaining cases intentionally filtered).
  • pnpm build: passed on the final Testbox lease in 8m32s (full remote command including focused tests: 9m45s). The build reported an unrelated Control UI startup gzip budget warning, 373,687 B versus 373,454 B; build exit was 0.
  • Authorized Linux rig fallback, node scripts/check-changed.mjs --staged at base c3f61d8f591f: 24 checks passed; core lint failed only on the two callback-shadowing errors subsequently corrected in 9705e3d53531. The corrected files passed focused Testbox lint, and the current-head CI core-lint job passed. Full original summary below; the historical aggregate exit remains 1.
  • Independent Codex review: corrected ignored-child trimming, external virtual-store fallback, and missing-directory recovery with regression coverage. Final pass scoped-clean at P0–P2. Static analysis subsequently removed one unused internal export.

Initial fixture failures (wrong broker test pool and parameterized test context) were fixed. The type gate caught and corrected an optional AbortSignal where Git preparation requires cancellation custody. No test sleeps, timer-driven polling, or per-test Gateway boots were added.

The initial published commit is a patch-identical rebase from validated base c3f61d8f591f onto 28a6f71449aa; git range-diff reports an unchanged patch. Earlier live rig measurements used base 52b32becc08d; the final focused regressions and build used c3f61d8f591f. The first current-head CI run (37151390481) found two lane-owned no-shadow lint errors, fixed in 9705e3d53531 by renaming callback-local variables without changing behavior. The correction passed independent Codex review and focused lint on blacksmith-testbox lease tbx_01m41qamm36efs6pzegc7hm8bk: node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json --threads=1 src/agents/worktrees/checkout.ts src/gateway/worker-environments/local-workspace-template.ts, zero warnings/errors in 12.5 s (38.79 s whole remote command including frozen dependency installation). Lease stopped. It also failed checks-ui-e2e (1/2) in board-mcp-app.e2e.test.ts:527 (602 px iframe gap). Source/history attributes the latter to inherited commit 668c06211e6c / #164493: .mount now relies on a flex host while board.css forces that host to display: block. The full ui/ tree and browser fixture inputs are unchanged by this PR; no browser reproduction or upstream fix is claimed.

Platform gap: live dependency-template proof is Linux/Btrfs/Podman. APFS/ReFS reuse the existing clone backends; no new native-platform proof was run. Existing sessions are not reinstalled automatically after their own lockfile edits.

Linux rig staged-check summary (original exit 1; lint correction verified separately)
Gate Time Result
Conflict markers 0.486 s Passed
Line-cap growth ratchet 0.641 s Passed
Max-lines suppression ratchet 11.00 s Passed
Assertion SAFETY comment ratchet 57.59 s Passed
SQLite worker ratchet 4.54 s Passed
Test timeout race ratchet 1.98 s Passed
Changelog attributions 0.359 s Passed
Doctor deprecation registry 0.287 s Passed
Guarded extension wildcard re-exports 0.325 s Passed
Plugin SDK wildcard re-exports 0.299 s Passed
Duplicate scan target coverage 0.491 s Passed
Dependency pin guard 0.479 s Passed
Changed-file formatting 0.502 s Passed
Config docs baseline 5.82 s Passed
Plugin boundaries 3.08 s Passed
Wrapper shadowing 14.41 s Passed
Package patch guard 0.813 s Passed
Test temp creation report 0.495 s Passed
Core tsgo graph boundary 104.39 s Passed
Core typecheck 65.59 s Passed
Core test typechecks 1721.35 s Passed
Coercion helper declaration guard 9.08 s Passed
Deprecated API usage 13.24 s Passed
Dead export scan 103.79 s Passed
Core lint 486.28 s Failed: two callback-shadowing errors, corrected afterward

Current-head CI: run 37152085073 completed on 9705e3d535317b92e02befff859daf075547fbcb. All jobs passed or were intentionally skipped except checks-ui-e2e (1/2) and its aggregate gate. The UI job reproduced the same inherited 602 px iframe gap; the core-lint correction and production types passed. This PR remains open pending an upstream UI repair; no merge was requested by this lane. All Testbox leases and live-proof containers have been stopped.

@clawsweeper

clawsweeper Bot commented Oct 3, 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 October 3, 2026 20:23
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: XL labels Oct 3, 2026
@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 9705e3d535317b92e02befff859daf075547fbcb
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/sandbox/context.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/agents/sandbox/dependency-template.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/agents/sandbox/local-workspace.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.

Carefully review these changes before merging.

@steipete
steipete enabled auto-merge (squash) October 3, 2026 20:26
@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 3, 2026, 4:50 PM ET / 20:50 UTC (Revision 3).

ClawSweeper review

What this changes

The PR prepares pnpm dependencies in a disposable sandbox and reuses filesystem templates for new private managed-worktree checkouts, with source-only fallback and worker-backed registry access.

Merge readiness

✅ Ready for maintainer review

Keep open: current main lacks this optimization, and the reviewed patch has useful production-path evidence with no concrete blocking defect found. Maintainer-authored work also remains outside automatic closure.

Likely related people: steipete — recent worktree and projection contributor, medium confidence.

Priority: P2
Reviewed head: 9705e3d535317b92e02befff859daf075547fbcb

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful implementation with strong scoped runtime evidence and focused regressions; no blocking patch defect was identified.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured Linux/Btrfs/Podman run exercises managed-session creation through sandbox preparation and a real repository import, observing faster reuse plus generation invalidation, sibling isolation, and clean fallback. Existing projections and registry schema remain intact; no stored-data model migration is introduced.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured Linux/Btrfs/Podman run exercises managed-session creation through sandbox preparation and a real repository import, observing faster reuse plus generation invalidation, sibling isolation, and clean fallback. Existing projections and registry schema remain intact; no stored-data model migration is introduced.
Evidence reviewed 8 items Pinned introduction and clean checkout: Reviewed the introduced delta from the pinned merge base to the exact original PR head. Initial and final status checks showed a clean checkout; origin identifies openclaw/openclaw. The supplied stale test merge was not used to infer removal of current-main behavior.
Still necessary on current main: Fetched main still invokes ordinary private projection preparation without the dependency-template path; neither new dependency-template implementation exists at that revision. No merged replacement fixing this requested behavior is established by the supplied related context.
Installer containment and cleanup: The builder removes configured environment credentials, binds, and setup commands; pins the image identity; mounts independent Git metadata read-only; checks current custody around installation; and awaits builder retirement in finally before template publication.
Findings None None.
Security None None.

How this fits together

Managed worktrees give agent sessions independent repository checkouts. Sandbox projection preparation turns a selected repository commit and sandbox policy into a private execution workspace whose accepted changes reconcile with the canonical worktree.

flowchart TD
  A[Repository commit and sandbox policy] --> B[Private workspace preparation]
  B --> C{Reusable template available}
  C -->|No| D[Disposable sandbox installation]
  D --> E[Validate output and retire builder]
  E --> F[Prepared or source-only template]
  C -->|Yes| F
  F --> G[Independent session checkout]
  G --> H[Agent execution and reconciliation]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +793, Tests +484, Docs +29, Other +2. Total +1308 across 17 files.

View PR surface stats
Area Files Added Removed Net
Source 12 1006 213 +793
Tests 3 484 0 +484
Docs 1 31 2 +29
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 0 +2
Total 17 1523 215 +1308

Review metrics

Metric Value Why it matters
Production and test growth Production +1006/-213; tests +483/-0 The PR explains production growth through isolated guest installation, shared cleanup custody, output validation, and worker-backed registry access.
Reported warm-checkout latency 77.961 s → 38.749 s The real Linux/Podman flow demonstrates the intended benefit, with the baseline contention caveat disclosed.

Technical review

Best possible solution:

Keep dependency preparation under the existing template lifecycle, preserve private-session isolation, and retain clean source-only fallback when acceleration cannot safely apply.

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

Not applicable as a bug reproduction: this is a performance optimization, and the captured body provides before/after measurements through the real sandbox checkout flow.

Is this the best way to solve the issue?

Yes: sharing the existing template registry and cleanup owner while installing inside an isolated guest preserves the host boundary and avoids a competing package-cache lifecycle.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded managed-worktree performance improvement with measured benefit and preserved fallback behavior.
  • 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 captured Linux/Btrfs/Podman run exercises managed-session creation through sandbox preparation and a real repository import, observing faster reuse plus generation invalidation, sibling isolation, and clean fallback. Existing projections and registry schema remain intact; no stored-data model migration is introduced.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured Linux/Btrfs/Podman run exercises managed-session creation through sandbox preparation and a real repository import, observing faster reuse plus generation invalidation, sibling isolation, and clean fallback. Existing projections and registry schema remain intact; no stored-data model migration is introduced.

Evidence

What I checked:

  • Pinned introduction and clean checkout: Reviewed the introduced delta from the pinned merge base to the exact original PR head. Initial and final status checks showed a clean checkout; origin identifies openclaw/openclaw. The supplied stale test merge was not used to infer removal of current-main behavior. (9705e3d53531)
  • Still necessary on current main: Fetched main still invokes ordinary private projection preparation without the dependency-template path; neither new dependency-template implementation exists at that revision. No merged replacement fixing this requested behavior is established by the supplied related context. (src/agents/sandbox/local-workspace.ts:27, 930bd387bbaa)
  • Installer containment and cleanup: The builder removes configured environment credentials, binds, and setup commands; pins the image identity; mounts independent Git metadata read-only; checks current custody around installation; and awaits builder retirement in finally before template publication. (src/agents/sandbox/dependency-template.ts:22, 9705e3d53531)
  • Validation and compatibility boundary: Template validation rejects tracked-source changes, retains real node_modules directories, and rejects external virtual stores before caching a clean source-only fallback. Existing projections use the reuse path without reinstalling. Registry operations retain the existing table and record shape while moving execution behind worker admission and native settlement. (src/gateway/worker-environments/local-workspace-template.ts:202, 9705e3d53531)
  • Real behavior proof: The captured PR body describes Linux/Btrfs/Podman execution through ManagedWorktreeService.create, persisted sandbox-required session preparation, resolveSandboxContext, and an actual repository import. It reports second-checkout time improving from 77.961 s to 38.749 s, plus observed lockfile invalidation, sibling isolation, clean failed-install fallback, and existing-projection reuse under allocation contention. APFS/ReFS were not exercised. Prepared media belongs to the unrelated UI PR and was not counted as worktree proof.
  • Regression coverage and review continuity: The new tests exercise generation reuse, source mutation, ignored children, missing template directories, external virtual stores, cancellation cleanup, and failed builder retirement. The body records pre-fix failures for three regressions and final Testbox validation. The preceding completed review at this same head recorded no findings; no unresolved prior finding was supplied. (src/gateway/worker-environments/local-workspace-template.test.ts:151, 9705e3d53531)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; 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 (2 earlier review cycles)
  • reviewed 2026-10-03T20:29:24.229Z sha 938e42b :: needs maintainer review before merge. :: none
  • reviewed 2026-10-03T20:42:11.811Z sha 9705e3d :: needs maintainer review before merge. :: none

@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 Oct 3, 2026
@steipete
steipete merged commit 7283a5c into main Oct 3, 2026
163 of 167 checks passed
@steipete
steipete deleted the steipete/perf-micro-worktree-deps-provisioning-20260919 branch October 3, 2026 20:56
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 4, 2026
* perf(worktrees): reuse sandbox dependency templates

* fix(worktrees): avoid shadowing template records
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 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. scripts Repository scripts security-sensitive-changed size: XL 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