Skip to content

perf(worktrees): keep repository maintenance out of removal - #167695

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-worktree-removal-pack-repair-20260919
Oct 9, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-worktree-removal-pack-repair-20260919

Conversation

@steipete

@steipete steipete commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Removing one managed worktree rebuilds the shared repository's entire multi-pack index. Large partial clones pay that repository-wide cost for every removal. Snapshot creation can then spend another two minutes implicitly fetching missing objects through inconsistent commit-graph state.

User Impact

Individual removals stop rebuilding pack indexes. Snapshot Git operations use local objects and preserve the checkout when required objects are missing; an explicit fetch or repository repair followed by retry completes ordinary removal. Native object validation, pending recovery pins, ownership checks, timeout budgets, and the existing explicit force/capacity-eviction snapshot-loss policy remain intact. No configuration or schema migration is required.

Why This Change Was Made

The existing background maintenance owner now exclusively owns pack repair and consolidation. It includes retained snapshot repositories, so removing the last live checkout cannot strand a backlog. Commit-graph/loose-object failures suspend those tasks while bounded pack consolidation continues; a pack failure still requires explicit retry or restart.

The unconditional repair and timing stage originated in #165913. Consolidation from #167453 runs only in maintenance; #167473's fetch healing is not invoked by removal. This change removes the old removal call, exported internal repair helper, optional consolidation branch, and obsolete timing field. The snapshot broker applies its no-fetch policy to inventory, ordinary snapshots, and exact-state verification through one operation-owned environment.

Production LOC: 28 additions, 31 deletions; net -3.

Evidence

Real ManagedWorktreeService.remove runs on a synthetic partial clone with 4,700 indexed packs, 2,405,376 filler objects, and 20,000 tracked files. Each of 30 samples adds one fresh indexed pack outside the removal timer. Both revisions start with the same maintained MIDX state and preserve dirty tracked/untracked content in snapshots.

Measurement Before After
Removal p50 1,946 ms 1,372 ms (29.5% lower; 1.42×)
Warm-sample empirical p99 2,193 ms 1,647 ms
Cold-inclusive empirical p99 6,799 ms 7,456 ms
Per-removal MIDX writes, 30 samples 30 0
Packs after five bounded maintenance passes 1 (from 4,730) 1 (from 4,730)

Cold-inclusive p99 is dominated by worker bootstrap; no cold-start improvement is claimed. A separate intentionally unindexed run measured p50 1,566 → 1,974 ms: without a MIDX, native reads are slower until maintenance builds one. This is the tradeoff for moving repository maintenance entirely off removal. Sample percentiles are not population-tail estimates, and synthetic data does not reproduce production filesystem pressure or complete history. Healthy benchmarks used the same no-fetch environment on both sides to isolate pack-repair cost.

Validation:

  • Blacksmith Testbox tbx_01m4fmt7geda3ef0ywp6t67ch6, openclaw-check: benchmark command node --import ./scripts/tsx.mjs .local/lane696/bench.mts --samples 30 --seed-midx --pack-churn, once per revision; combined run 255.1s, passed. Separate stale-MIDX probe confirms safe removal with an index referring to deleted packs. The lease was stopped after a later sync exceeded its fixed two-minute timeout before running tests.
  • AWS Crabbox fallback cbx_b7bb79c88d88: pnpm test src/agents/worktrees/service.gc-performance.test.ts --maxWorkers=1 — 13 passed, 45.96s wall time including cold worker preparation (about 22.6s actual tests; the new missing-object case is 1.42s). Real Git/object loss and SQLite admission require this boundary.
  • The removal/maintenance regressions fail on unchanged base e670b178f9dbdde25a074913d9c97fa9b8b533b6. The missing-object regression also fails on that base, then proves the candidate preserves files without upload-pack, permits explicit repair, and succeeds on retry.
  • node scripts/run-vitest.mjs src/agents/worktrees src/infra/git-worker.lifecycle.test.ts src/infra/git-worker.diagnostics.test.ts src/infra/git-operation-timing.retention.test.ts src/infra/git-content-budget.test.ts src/infra/git-exec.test.ts — 695 passed, 34 platform-specific skips, 58 passing / 6 skipped files, 508.44s on AWS. All 59 worktree sibling files were selected.
  • node scripts/check-changed.mjs — production types, all 27 test type graphs, and preceding guards passed; dead-export scan fails identically on the unchanged base and candidate for bindCliQuestionAnswerAuthority, prepareSessionEventTargetForHost, readSessionEntryCreationTransition, and RESTART_CONTINUATION_CONTEXT_PREFIX. All are outside this diff. Candidate lint (zero warnings/errors), native schema, legacy-store, media-helper, runtime-sidecar, import-cycle, webhook-body, and pairing guards all pass. The full gate is recorded as an inherited failure, not green.
  • pnpm build — passed, 308.8s on AWS. It emitted a non-blocking, unrelated UI startup gzip warning: 373,491 B versus a 373,454 B budget; no UI files are changed.
  • Independent review — scoped clean; no actionable P0/P1 findings.

Read-only journal evidence identifies write-tree's implicit fetch as the observed two-minute snapshot failure. The regression exercises that fetch boundary and recoverability without recreating production corruption or sleeping through its timeout. This is service/native-Git boundary proof, not an installed CLI/Gateway end-to-end run. Hosted CI 37901007450 is green on f3aab3944acf6582b1f670bacfcb92c8422613e4 (49 successful jobs, 25 intentional skips), as are CodeQL and OpenGrep. ClawSweeper reports no findings or before-merge requirements.

CI test cost: service.gc-performance.test.ts — 13 passed, 11.180s summed case time (missing-object regression 0.516s), in a 128s job; service.diagnostics.test.ts — 7 passed, 9.854s summed case time, in a 203s job. Job wall times include other tests and setup.

Let background maintenance own pack repair and consolidation, including repositories retained only by snapshots. Keep bounded pack work progressing when graph or loose-object tasks fail.

Prevent snapshot operations from implicitly fetching missing promisor objects. Preserve native object validation and checkout custody so explicit repository repair can be followed by a safe retry.
@clawsweeper

clawsweeper Bot commented Oct 9, 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: M labels Oct 9, 2026
@steipete
steipete marked this pull request as ready for review October 9, 2026 07:47
@steipete
steipete enabled auto-merge (squash) October 9, 2026 07:49
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 9, 2026
@clawsweeper

clawsweeper Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Managed worktrees are isolated Git checkouts; this PR moves shared repository maintenance out of individual removal and preserves checkouts when snapshot objects are missing.

Example: An operator removes a checkout whose README.md snapshot object is missing.

  • Before: Snapshot creation can implicitly fetch the missing object and stall removal.
  • After: Removal preserves README.md and new.txt without fetching; an explicit fetch followed by retry saves both files and removes the checkout.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is coherent and useful, with convincing native-Git boundary evidence limited to a production-service harness.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (live_output): Reported Linux runs exercise ManagedWorktreeService.remove and the snapshot broker with real native Git, showing fewer index writes and preserved snapshot content. The object-loss run rejects removal without upload-pack, preserves files, and succeeds after explicit fetch; this supports the internal production-boundary behavior, with synthetic workload and harness limits disclosed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes
User problem: Removing a managed checkout repeatedly pays shared repository maintenance costs and can stall while snapshotting missing objects.
Reason: Matched native-Git measurements establish avoidable removal work, and the existing area contributor records the recovery tradeoff. The change simplifies production ownership without adding configuration or storage formats.

Merge readiness

✅ Ready for maintainer review

This PR retains a distinct, measured improvement absent from current main. No actionable introduced defect was found.

Priority: P2
Reviewed head: f3aab3944acf6582b1f670bacfcb92c8422613e4

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The evidence drives the production service and native Git, but does not demonstrate removal through the shipped CLI or Gateway.
Agent review details

How this fits together

OpenClaw gives agent sessions isolated Git checkouts and saves recoverable snapshots before removing them. Its cleanup service also maintains the shared repository that stores checkout and snapshot objects.

flowchart TD
A[Removal request] --> B[Existing ownership and removal claim]
B --> C[Snapshot using local objects]
C --> D{Required objects available?}
D -->|Yes| E[Save snapshot and remove checkout]
D -->|No| F[Preserve checkout for repair and retry]
G[Periodic cleanup] --> H[Maintain repositories with live checkouts or snapshots]
Loading

Technical review

Best possible solution:

Keep repository-wide work in the existing maintenance owner and retain lossless snapshot failure and explicit repair-and-retry behavior.

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

Yes: current main unconditionally repairs the shared index during removal, and the real-object-loss fixture exposes snapshot lazy fetching. The supplied remote runs report baseline failures; this read-only review did not rerun them.

Is this the best way to solve the issue?

Yes: the patch removes the competing removal maintenance path, uses the existing repository owner, and changes snapshot policy at the host Git broker without weakening native object validation or checkout custody.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Still necessary on current main: Fetched main still calls repairWorktreePackIndex immediately before snapshot capture. None of the seven touched files changed between the pinned merge base and fetched main, so the introduced patch remains distinct and has no overlapping main changes. (src/agents/worktrees/removal.ts:162, 83c8fea9408f)
  • Complete maintenance cutover: The removal call and exported repair helper are removed. The existing maintenance owner inventories retained records, continues bounded pack work after broader maintenance failures, and retains repository deferral, cancellation, and command guards. (src/agents/worktrees/git-maintenance.ts:229, f3aab3944acf)
  • Snapshot policy and custody: The host Git broker applies the local-only environment to ordinary and exact-state snapshots. Existing native write-tree validation, claim checks, pending recovery refs, and explicit snapshot-loss policy remain in place. (src/infra/git-worker.ts:240, f3aab3944acf)
  • Recorded production-boundary proof: The fully supplied PR body, source revision 86958ce35fc43451b84e6bc2e7f1a58b6fd7dc8732a7e576f101ba91d7205c87, records real ManagedWorktreeService.remove runs with native Git on a synthetic partial clone. Warm median removal improved 29.5%, per-removal index writes fell from 30 to zero, dirty content remained snapshotted, and five maintenance passes converged both revisions to one pack. These are reported remote observations, not reviewer-executed checks. (f3aab3944acf)
  • Real object-loss recovery regression: The added service-boundary case deletes a real promised blob, checks that failed removal preserves tracked and unpublished files without upload-pack, explicitly fetches the object, and verifies successful retry and snapshot contents. The body reports failure on the unchanged base and passage on the candidate. (src/agents/worktrees/service.gc-performance.test.ts:94, f3aab3944acf)
  • Area-owner tradeoff: The author also appears in prior merged maintenance and removal history. The PR explicitly accepts slower native reads before an index exists and preservation of missing-object checkouts until explicit repair, while retaining force/capacity-eviction policy. The recovery direction is documented at https://docs.openclaw.ai/concepts/managed-worktrees. (docs/concepts/managed-worktrees.md:208, f3aab3944acf)

Likely related people:

  • Peter Steinberger: Raw commit 3c66417 adds src/agents/worktrees/git-maintenance.ts:23 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3c66417c08e3; files: src/agents/worktrees/git-maintenance.ts)

PR surface

Source -3, Tests +130, Docs 0. Total +127 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 28 31 -3
Tests 2 144 14 +130
Docs 1 2 2 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 174 47 +127

Review metrics

Metric Value Why it matters
Production versus test delta Production +28/-31, net -3; tests +144/-14, net +130 Production shrinks through a complete ownership cutover while tests add native object-loss recovery coverage.

Labels

Label changes:

  • add P2: This improves managed-checkout removal performance and recovery within a bounded subsystem.
  • add merge-risk: 🚨 compatibility: Existing partial clones with missing snapshot objects now require explicit repair and retry; the area owner expressly accepts this checkout-preserving tradeoff.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp 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 managed-checkout removal performance and recovery within a bounded subsystem.
  • merge-risk: 🚨 compatibility: Existing partial clones with missing snapshot objects now require explicit repair and retry; the area owner expressly accepts this checkout-preserving tradeoff.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

Reviewed October 9, 2026, 3:53 AM ET / 07:53 UTC.

@steipete
steipete merged commit e376a19 into main Oct 9, 2026
208 of 209 checks passed
@steipete
steipete deleted the steipete/perf-micro-worktree-removal-pack-repair-20260919 branch October 9, 2026 07:56
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
…#167695)

Let background maintenance own pack repair and consolidation, including repositories retained only by snapshots. Keep bounded pack work progressing when graph or loose-object tasks fail.

Prevent snapshot operations from implicitly fetching missing promisor objects. Preserve native object validation and checkout custody so explicit repository repair can be followed by a safe retry.
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 merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M 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