Skip to content

perf(sandbox): attribute slow setup and reuse clean failed-install source - #181996

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-micro-attempt-setup-attribution-20260919
Oct 24, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-micro-attempt-setup-attribution-20260919

Conversation

@steipete

@steipete steipete commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Slow sandboxed chat startup can report tens of seconds under attempt.setup without its nested worktree phases in the same line. A failed dependency installation also rebuilds the entire source checkout even when the installer left tracked files unchanged.

User Impact

Slow-send diagnostics identify the setup work directly. Clean dependency-install failures reuse the validated source checkout after removing generated files; changed or unverified source still rebuilds. No configuration, schema, or authority changes.

Why This Change Was Made

A recent startup had attempt.setup=67201ms and a separate earlier worktree=23891ms. The sandbox owner already recorded 67198ms, including 42428ms of template preparation, 24666ms of accumulated checkout work, and a dependency install that failed in 442ms. Its unattributed time was only 16ms. These nested timings overlap and must not be summed.

Request-owned checkpoints now separate setup policy, baseline waiting, workspace, skills, backend, and browser preparation. The worktree owner forwards its recorded durations as detail.worktree.managed.* and detail.worktree.sandbox.*; it does not remeasure them. Labels are fixed and elapsed timing is monotonic. The existing template validator removes partial dependencies and installer debris before reusing unchanged source, eliminating the second checkout in the clean-failure case.

Historical owner attribution (milliseconds; inclusive parents and accumulated children overlap):

Owner phase Duration Meaning
attempt.setup 67,201 Whole setup
worktree.sandbox 67,198 Sandbox preparation inside setup
worktree.sandbox.reservation 63,850 Inclusive allocation/preparation
worktree.sandbox.templatePrepare 42,428 Source, dependency install and fallback
worktree.sandbox.checkout 24,666 Accumulated checkout work, including rebuild
worktree.sandbox.templateApply 12,339 Clone prepared template
worktree.sandbox.synchronizeProjection 4,271 Reconcile canonical content
worktree.sandbox.snapshot 3,260 Initial projection manifest
worktree.sandbox.containerStart 3,090 Builder/runtime preparation
worktree.sandbox.workspaceLayout 1,240 Workspace/skills layout
worktree.sandbox.setup 442 Failed dependency installer
worktree.sandbox.unattributed 16 Outside the union of recorded owner phases

The earlier chat worktree=23891ms surrounds a separate managed preparation (durationMs=23622, unattributedMs=61); it must not be subtracted from attempt.setup. The repeated “Native image: sandbox validation failed” warning validates prompt image-file paths, not container images. It occurs outside this setup boundary, with no retry loop in that validation path, so this change does not alter it.

Evidence

  • Regression: both new baseline-wait attribution cases fail on base because the slow-send line omits the phase; all 11 attempt-setup tests pass with the change.
  • Regression: clean install failure and external-store fallback both perform two template creations on base and one with the fix. Successful and failed installers that change tracked source still rebuild. The existing tests verify original source/lockfile bytes and no installer debris.
  • Focused verification: 30 tests passed across template recovery, slow-send diagnostics, workspace sandbox authority, and worktree timing. One earlier check aborted because source changed during worker compilation; the stable-source run passed.
  • Review: independent subagent review (autoreview route unavailable), scoped clean through P2. The configured autoreview provider did not match the operator configuration; no configuration was changed.

Measurement contract (recorded before paired runs)

Use a real isolated Gateway with synthetic model transport, 5,000 sessions, 6,000 retained runs, 5,000 distinct 4 KiB tracked files, managed worktrees, Podman session sandboxes, and synthetic plugin/Streamable HTTP MCP tools verified at the model boundary. Generate distinct same-tree commits so each of 32 cold samples per side prepares a cold dependency template; use four concurrent turns per 16-core side, keep the resident Gateway, and reuse the final four sessions for 200 warm turns. Report send-to-first-model-request p50/p99, sample counts, CPU, GC/work, promotion, loop tails and maximum pauses. Cold means session/template, not a fresh Gateway process.

Run concurrent pairs under one shared quiet lock and production guard, then swap interleaved CPU sets. Discard guard-interrupted pairs. Decide on paired means; reject at >=20% adverse mean or >=10% adverse in both pairs. Opposite-signed deltas or baselines differing by >5x are inconclusive, with absolute deltas and a third pair if gating. p99 needs 1,000 samples per side, p95 needs 200; smaller tails are context. Apply the GC collection-count, absolute pause-delta, and maximum-pause exceptions from the campaign rules.

The comparison uses candidate 127ddf47af7742f5e663a59baa3443bf97b70446 and baseline production 9538d3ab0bb5d1d5de262fe53ec0c24da0b2f0cc, with the same benchmark harness on both sides. Its continuous whole-workload histogram supplies event-loop p99 and count, including cold session creation between cohorts.

Measurement and landing decision

Metric Baseline Candidate Paired delta Qualification
Cold first-model p50 55,643.70 ms 52,543.51 ms −3,100.19 ms (−5.57%) 32 turns/side
Cold first-model p99 114,349.72 ms 114,231.09 ms −118.64 ms (−0.10%) Context: 32/32 samples
Warm first-model p50 3,774.47 ms 3,564.26 ms −210.21 ms (−5.57%) 200 turns/side
Warm first-model p95 5,765.73 ms 5,536.17 ms −229.55 ms (−3.98%) Eligible: 200/200 samples
Warm first-model p99 8,241.33 ms 7,454.86 ms −786.47 ms (−9.54%) Context: 200/200 samples
Total observed GC/turn 40.2196 ms 40.3099 ms +0.0903 ms (+0.22%) Includes incremental GC; 1,954/2,037 events
Promotion/turn 28.0124 MB 28.0492 MB +0.0368 MB (+0.13%) Whole measured workload
Whole-loop p99 47.7757 ms 45.1215 ms −2.6542 ms (−5.56%) Eligible: 62,744/63,110 samples
Whole-loop maximum 296.7470 ms 367.5259 ms +70.7789 ms (+23.85%) Context; loop p99 is the gate
Maximum single GC pause 108.503 ms 106.955 ms −1.548 ms Below max(50 ms, 2× baseline max)
Minor-GC p95 / p99 6.505 / 17.745 ms 6.135 / 18.211 ms −0.370 / +0.466 ms 1,812/1,895 collections; final absolute-mean rule pending pair 2
Major-GC p95 / p99 56.097 / 69.186 ms 60.103 / 106.955 ms +4.006 / +37.769 ms Context: 71/71 collections, below percentile minima
Main-isolate CPU/turn 555.39 ms 531.14 ms −24.25 ms (−4.37%) Measured rounds
Gateway-process CPU/turn 2,295.31 ms 2,302.89 ms +7.58 ms (+0.33%) Measured rounds
Aggregate scope CPU/turn 8,861.06 ms 8,694.70 ms −166.36 ms (−1.88%) Common start through driver exit; excludes warmup/cleanup
Cold checkout mean 2,112.44 ms 1,055.19 ms −1,057.25 ms (−50.05%) 32 cold templates/side; two checkouts become one

Both model-bound catalogs contained the synthetic plugin and MCP tools. No dropped diagnostic events, histogram samples, or collection errors occurred. Interleaved 16-core sets and sandbox-container placement were verified. The common barrier produced measurement starts 1 ms apart; first-cohort admission differed by 22.23 ms. One high-load minute (67.36) recovered without meeting the shared guard's three-consecutive-minute abort rule; both drivers and the orchestrator exited 0. This is a qualified first pair, not a completed performance verdict.

The small 20 MiB tracked-source fixture makes checkout much cheaper than the historical production case. Do not extrapolate its absolute saving to production. Mean owner-unattributed time fell from 1,205.79 to 105.05 ms because quiesce/resume now have labels; that is attribution coverage, not latency saved.

paired measurement deferred: Team outage; simplification. The lead explicitly authorized landing this duplicate-work removal without further pairs under the updated decision rule. The valid first pair showed no qualifying regression; it is not a completed swapped-pair estimate.

The first swapped attempt timed out during the initial cold cohort on both sides before completing a round. Its partial data is retained and excluded. Owner logs show progress: final setup completed at 164.495s on baseline and 159.721s on candidate, leaving insufficient time under the 170s observation ceiling. The prepared retry uses fresh cold fixtures and an identical, independently reviewed benchmark-only overlay: setup-image provider/turn deadlines increase to 600s and RPC observation to 610s. Workload, timestamps, and product source stay unchanged; pair 1 never reached its original deadlines. Overlay driver SHA-256: b16beddfcea43656c0f8c2f293bf5d1e66f9258921531e4d3eeafd27310a8302. The subsequent Team outage prevented the retry. The host has recovered, but no retry will run under the lead’s landing instruction; no complete swapped result exists.

Captured live diagnostic signal

The real candidate sandbox emitted this synthetic slow-send excerpt during pair 1:

detail.attempt.setup=22377ms
detail.attempt.setup.workspace=22376ms
detail.attempt.setup.workspace.sandbox=22357ms
detail.worktree.sandbox=22355ms
detail.worktree.sandbox.templatePrepare=18993ms
detail.worktree.sandbox.checkout=1016ms
detail.worktree.sandbox.containerStart=1592ms
detail.worktree.sandbox.setup=50ms
detail.worktree.sandbox.templateApply=303ms
detail.worktree.sandbox.snapshot=1191ms
detail.worktree.sandbox.synchronizeProjection=395ms
detail.worktree.sandbox.unattributed=23ms

These are nested/inclusive facts, not additive buckets. New fields are verified in a running isolated Gateway, not yet in production. Production observation requires the normal deployment; this lane does not restart or deploy a production Gateway.

Initial CI run 40037827662 passed the production checks but found an implicit-array-type error in the benchmark's nested summary construction. Two direct summaries fix that inference error without changing the reported samples. Pre-rebase CI run 40039266721 passed all 88 jobs and verifies the repair. The required main rebase also brought a general chat diagnostic capture into this block; the independently reviewed resolution keeps ordinary chat and the dedicated attempt-setup capture correctly named and reported.

Changed-file lint/format, the tsgo:core lane (native tsrs), export-name collision guard, and the two source-closure files passed (22 closure tests). Focused test wall time was 45.42s for attempt setup, 64.75s across the four recovery/timing files, and 26.73s for closure checks; this includes compilation. Broad tests are delegated to PR CI; no Testbox/Crabbox lease was used under the lane's compute policy.

Runtime production delta is +90 lines: +81 for the explicitly requested continuous attribution and worktree-fact bridge, and +9 for source-only recovery while preserving the integrity rebuild. The deleted work is a complete second source checkout, not an alternate cached implementation. Benchmark fixtures and tests are separate from that runtime count.

The complete functional Gateway smoke passed plugin/MCP catalog assertions and a sandbox README read. It exercised a cold-template failed install and a warm reused sandbox. Added runtimeQuiesce/runtimeResume timings after that smoke exposed pause/resume work outside the existing worktree phases; both focused pause/resume behavior cases passed. These smoke timings are not paired performance evidence.

The final main rebase resolved a conflict in adjacent benchmark summary fields by preserving both sets. Independent review and focused lint/format passed; range-diff confirms the runtime changes remained identical. All paired measurements use this final head. Exact-head CI completed with the inherited failure below.

Exact-head CI: inherited failure

Run 40041421575 completed all 88 jobs. The only failing leaf was checks-node-changed-compact-large-24: two progress-card-refresh.integration.test.ts cases, “steers duplicate active refreshes…” with unconfirmed=false/true, expected an accepted retry but received PROGRESS_CARD_REFRESH_TERMINAL. The aggregate CI gate failed downstream; other jobs passed.

The same single file reproduced 2 failed / 7 passed on both PR head 127ddf47 and unchanged main baseline 9538d3ab, using CI's pinned OpenClaw Bun 1.4.4-canary.1+ef37c31de in the isolated sandbox. Command: OPENCLAW_VITEST_RUNTIME=bun node scripts/run-vitest.mjs src/gateway/server-methods/progress-card-refresh.integration.test.ts --maxWorkers=1. No broad suite or CI rerun was used.

Main's #181953 moved steering after ACK. This fixture still completes the target run immediately after ACK, before awaiting its queueMessage call, so the hidden refresh can fall back and settle without changing the card. The failing test, fixture, and causal dispatch/receipt owners are byte-identical on baseline, PR head, and CI's tested merge 6dd740a1 (main parent 215cb73b). All gateway-method source files are also unchanged between the replayed main baseline and that CI parent. This PR's instrumentation adds no receipt mutation or await on that path. That prior-head failure was baseline-attributed; it is not a claim of green CI. Final rebased-head CI is checked separately below.

Final landing head

Rebased cleanly onto main 40e0e5ab151484228a9f6072ee9a20ede6db3fed; final head 2a85d12991c761cfefbc3c3b5e9712ff0b3531de. Range-diff shows only surrounding perf-fixture context changes; the reviewed runtime patch is unchanged. Measurements above remain evidence for the explicitly named pre-rebase source, not a claim of a new run. Exact-head CI run 40058889539 completed successfully: 62 jobs passed and 26 were skipped. The earlier baseline-attributed progress-refresh failures did not recur. Independent rebase review confirmed the runtime diff is byte-for-byte unchanged and found no actionable P0–P2 issues.

@clawsweeper

clawsweeper Bot commented Oct 23, 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 agents Agent runtime and tooling size: L labels Oct 23, 2026
@steipete
steipete force-pushed the steipete/perf-micro-attempt-setup-attribution-20260919 branch from ffa4031 to 0c04ec6 Compare October 23, 2026 23:06
@steipete
steipete marked this pull request as ready for review October 23, 2026 23:07
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T03:37:27.008188Z 2a85d12 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.

@github-actions

github-actions Bot commented Oct 23, 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: 2a85d12991c761cfefbc3c3b5e9712ff0b3531de
  • 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/workspace-sandbox.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 force-pushed the steipete/perf-micro-attempt-setup-attribution-20260919 branch from 0c04ec6 to e47053f Compare October 23, 2026 23:18
@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. labels Oct 23, 2026
@steipete
steipete force-pushed the steipete/perf-micro-attempt-setup-attribution-20260919 branch from a586f24 to 127ddf4 Compare October 23, 2026 23:45
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. 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 Oct 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR adds detailed sandbox setup timings and reuses validated source after dependency installation fails without changing tracked files.

Example: A pnpm installation fails after leaving partial node_modules and .env.installer files but unchanged source.ts and pnpm-lock.yaml.

  • Before: The template owner deletes the checkout and creates a second source checkout.
  • After: The validator removes generated files and reuses the original checkout; changed tracked source still triggers rebuilding.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The implementation is focused and source-consistent, but supplied evidence does not yet establish the changed runtime behavior and performance acceptance.
Proof confidence 🧂 unranked krab (1/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: Sandboxed chats can spend substantial time preparing workspaces while diagnostics hide the nested costs and failed installs repeat source checkout work.
Reason: The maintainer-authored direction has concrete value: remove unnecessary checkout work and expose costs through existing diagnostic owners without changing product configuration or authority.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses a source-confirmed redundant checkout and useful setup attribution; no discrete correctness or security defect was found.

Priority: P2
Reviewed head: 127ddf47af7742f5e663a59baa3443bf97b70446

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The reported Gateway smoke lacks captured changed-path output, and the declared cold/warm baseline-versus-candidate measurements have not been supplied.
Agent review details

How this fits together

Gateway chat dispatch prepares an agent workspace and sandbox, consuming managed-worktree templates and publishing request-scoped setup timings to slow-send diagnostics.

flowchart TD
  A[Gateway chat dispatch] --> B[Attempt workspace preparation]
  B --> C[Sandbox owner]
  C --> D[Dependency template owner]
  D --> E[Source validation and cleanup]
  C --> F[Recorded worktree timings]
  F --> G[Slow send diagnostics]
  B --> G
Loading

Technical review

Best possible solution:

Reuse the existing validator and timing owners while preserving full rebuilds for changed or unverified source.

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

Source inspection confirms that main recreates source after every failed dependency installation, including clean failures; the PR reports red-to-green checkout-count and attribution regressions, but no target code was executed during this read-only review.

Is this the best way to solve the issue?

The patch follows the smallest complete approach: extend the existing validator to discard generated outputs, retain its tracked-source checks, and forward existing timing facts through the request observer.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +90, Tests +93, Docs +70, Other +252. Total +505 across 16 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 8 120 30 +90
Tests 3 128 35 +93
Docs 2 70 0 +70
Config 0 0 0 0
Generated 0 0 0 0
Other 3 263 11 +252
Total 16 581 76 +505

Review metrics

Metric Value Why it matters
Runtime production versus tests Production +120/-30; tests +128/-35 Runtime growth primarily adds requested attribution through existing owners; recovery removes a second checkout without introducing another cache or lifecycle owner.
Benchmark options 5 new tooling flags The fixture and measurement scripts add worktree-file-bytes, worktree-install-failure, worktree-cold-commits, attempt-setup-image, and cold-session-rounds; no product configuration option is added.

Labels

Label changes:

  • add P2: This improves sandbox startup cost and diagnosis without evidence of an urgent availability or data-integrity regression.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This improves sandbox startup cost and diagnosis without evidence of an urgent availability or data-integrity regression.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • 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.

  • Publish captured changed-path Gateway output and the already planned paired cold/warm measurements.

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 October 23, 2026, 8:02 PM ET / October 24, 2026, 00:02 UTC.

Expose attempt setup checkpoints and recorded worktree phase durations in slow chat send diagnostics. Preserve full rebuilds when installation changes tracked source. Add a reproducible cold-template and warm-turn Gateway workload.
@steipete
steipete force-pushed the steipete/perf-micro-attempt-setup-attribution-20260919 branch from 127ddf4 to 2a85d12 Compare October 24, 2026 03:34
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Final head: 2a85d12991c761cfefbc3c3b5e9712ff0b3531de. The clean main rebase preserves the reviewed runtime diff byte-for-byte. The PR body now includes the completed first-pair results, captured sandbox diagnostic phases, and the explicit maintainer decision: paired measurement deferred: Team outage; simplification. Independent review remains clean; exact-head CI is running.

@clawsweeper

clawsweeper Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete merged commit 6f323c4 into main Oct 24, 2026
155 of 156 checks passed
@steipete
steipete deleted the steipete/perf-micro-attempt-setup-attribution-20260919 branch October 24, 2026 03:45
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 24, 2026
…urce (openclaw#181996)

* perf(sandbox): reuse clean source after dependency install failure

Expose attempt setup checkpoints and recorded worktree phase durations in slow chat send diagnostics. Preserve full rebuilds when installation changes tracked source. Add a reproducible cold-template and warm-turn Gateway workload.

* test(perf): exercise cold sandbox templates and attribute runtime pauses

* fix(perf): type setup summaries and capture whole-workload loop tails
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. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts security-sensitive-changed 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