Skip to content

perf(worktrees): avoid cleanup stalls and maintenance fetches - #167030

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-worktree-maintenance-main-thread-20260919
Oct 8, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-worktree-maintenance-main-thread-20260919

Conversation

@steipete

@steipete steipete commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Managed-worktree cleanup could block the Gateway while classifying hundreds of session owners, and automatic Git maintenance could wait on network hydration in a partial clone.

User Impact

Cleanup classifies owners from worker-read placement facts and yields between batches. Background Git maintenance uses local objects only; explicit fetch remains responsible for hydration. No configuration or schema changes.

Why This Change Was Made

The session census already used a database worker, but its placement checks synchronously queried SQLite for every owner before the cleanup loop reached its first checkpoint. The census now indexes one worker placement read and reuses the existing classification logic. Its advisory facts are discarded after the pass; exact session and placement checks still guard destructive cleanup. This retained boundary protects against active turns, changed placement generations, and foreign writers.

Git's commit-graph auto-threshold check resolves historical refs and can trigger promisor fetches even when no graph write is needed. Apply the existing local-only environment contract from #166461 to automatic maintenance and pack-index repair.

The reported 609 protections were 257 moved branches, 223 nested repositories, 70 prior snapshot timeouts, 55 owners classified as active, three unavailable Git metadata cases, and one unreadable checkout. Their totals are expected disposition accounting, not evidence of 609 leaked live leases. Existing registry revisions, checkout fingerprints, timed retry, and explicit retry own invalidation. The nine fresh failures were six snapshot write-tree timeouts, two missing-object write-tree failures, and one diff-files timeout. This patch does not discard those protected files or claim to repair missing snapshot objects.

Evidence

  • Linux Git 2.53 partial clone, five automatic-maintenance calls with a one-second failing promisor remote: mean 2046.78 → 6.00 ms, maximum 2066.76 → 8.51 ms, transport attempts 10 → 0. Task isolation attributes the fetches to commit-graph threshold traversal, not incremental repack. The historical timeout lacks child trace data, so its exact child/object remains unknown.
  • Blacksmith Testbox tbx_01m4d3pa7v1xsfg65kmvf0z6dr, 609 synthetic session owners, five passes: census mean 181.05 → 5.99 ms; longest census callback 216.32 → 3.41 ms. Full ManagedWorktreeService.gc longest callback 194.38 → 4.59 ms, below the 50 ms target. Warm full-pass mean (four passes after initialization) 226.59 → 29.86 ms (7.6×). This retained-worktree census and sweep executed no caller-thread SQL; destructive removals retain their exact checks. Callback spans were measured with async hooks; these are isolated measurements, not a post-deployment production claim. Instrumented final full-pass RSS was 687.0 → 538.6 MiB; retained SQL-observer data contributes to that difference, so it is not an allocation claim.
  • Baseline: Blacksmith Testbox tbx_01m4d25kk938jwmvp3d8pj5kj3, focused owner-protection, GC-performance, and Gateway maintenance suites passed. The initial missing-dependency failure was resolved with frozen installation. Candidate sync then timed out; AWS and Hetzner fallback admission both hit the shared fleet limit. An isolated Linux rig reached 0 MiB free and could not complete snapshot tests; it was not used as passing proof. A fresh Testbox completed the same tests.
  • Candidate changed suites: 35 tests passed with node scripts/run-vitest.mjs src/agents/worktrees/owner-protection.test.ts src/agents/worktrees/service.gc-performance.test.ts --maxWorkers=1 (36.86 s wall including cold worker compilation; new census case 491 ms, new partial-clone case 77 ms). Both new regressions fail against the original production code for caller-thread SQL and unexpected promisor transport. Sibling run: 601 tests passed, with 33 platform-dependent cases skipped; one old lifecycle mock lacked the async placement capability. After the fixture correction, its two tests passed (8.27 s wall with --maxWorkers=1). Two independent Codex P0–P2 reviews were scoped-clean. The staged gate also requires removing the now-obsolete mock-baseline entry; that exact shrink is included. Final node scripts/check-changed.mjs --staged passed on the same Testbox (28m50s), including all 27 core test-type partitions, production types, lint, dead-code scans, and runtime guards. CI run 37744244078 passed on the published head: 720 seconds from first job start to last completion; selected Node jobs totaled 5,470 job-seconds, with the longest taking 633 seconds. These are whole-run costs, not incremental costs of the new regressions.

Production LOC grows to preserve the exact destructive-mutation contract while introducing a short-lived read adapter for advisory census facts; both paths use the same classification function. The removed per-owner census SQL is not retained as a fallback. Production TypeScript delta: +41 lines across three existing modules (no new module or export). The requested diff excluding tests/test support/docs is +40 net lines, including the one-line baseline reduction.

Read placement facts once through the worker for the advisory owner census and yield classification in batches. Preserve exact session and placement checks before destructive cleanup. Keep automatic Git maintenance and pack-index repair local-only so partial clones cannot block cleanup on promisor fetches.
@clawsweeper

clawsweeper Bot commented Oct 8, 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 agents Agent runtime and tooling size: S labels Oct 8, 2026
@steipete
steipete marked this pull request as ready for review October 8, 2026 07:34
@steipete
steipete enabled auto-merge (squash) October 8, 2026 07:35
@clawsweeper clawsweeper Bot added 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 8, 2026
@clawsweeper

clawsweeper Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 8, 2026, 3:41 AM ET / 07:41 UTC.

ClawSweeper review

What this changes

The branch batches worker-placement reads and yields during owner classification, while keeping background Git maintenance and pack-index repair local-only.

Example: Automatic cleanup runs in a partial clone with a missing historical branch head.

  • Before: The reported five-call measurement averages 2046.78 ms and makes 10 transport attempts.
  • After: The reported candidate measurement averages 6.00 ms and makes zero transport attempts.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused patch is useful and supported by real Git and production-owner measurements, with confidence limited by isolated harness rather than shipped Gateway execution.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (live_output): The supplied Linux partial-clone measurements exercise the actual Git maintenance path with transport attempts falling to zero, and Testbox measurements exercise the census and full cleanup service with reduced callback spans. Source confirms advisory facts cannot replace final removal checks. No stored-data contract changes require migration; deployed-Gateway performance remains unmeasured.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes
User problem: Background worktree cleanup can pause Gateway responsiveness or wait on unwanted partial-clone downloads.
Reason: The measured delays justify the focused change. Prior merged history connects the author to these owners, and the proposal preserves their cleanup and recovery contracts.

Merge readiness

✅ Ready for maintainer review

This PR remains useful: current main retains both bottlenecks, and the reviewed patch preserves cleanup safeguards. No actionable defect was found.

Priority: P2
Reviewed head: ab4bc54b96b30cf1ad4306821904db4351f67490

Before merge

None.

Findings

None.

Agent review details

How this fits together

Managed worktrees give agent tasks separate Git checkouts. Background cleanup classifies their owners, protects active work, removes eligible checkouts, and maintains shared Git storage.

flowchart TD
 A[Registered checkouts] --> B[Worker reads session and placement facts]
 B --> C[Batched owner classification]
 C --> D[Cleanup eligibility]
 D --> E[Exact live owner checks]
 E --> F[Preserve or remove checkout]
 F --> G[Local-only Git maintenance]
Loading

Technical review

Best possible solution:

Keep advisory classification worker-backed and pass-scoped, retain exact checks before removal, and reserve object hydration for explicit fetches.

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

Yes: source identifies synchronous placement reads during the census, and the supplied partial-clone and 609-owner measurements establish focused failing paths; no runtime execution occurred in this review.

Is this the best way to solve the issue?

Yes: it reuses the existing worker reader and classification owner, preserves live removal checks, and applies the established local-only Git contract.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • src/agents/worktrees/owner-protection.ts keeps the original intent (4de57f2: Batch narrow session facts for GC while retaining fresh destructive-mutation checks and preserving uncertain owner state.)
  • src/agents/worktrees/git-maintenance.ts: automatic maintenance changes intended behavior with a stated reason (22af012: Use threshold-gated incremental tasks, preserve unique objects and reflogs, and suspend repeated repository failures until explicit retry.)
  • src/agents/worktrees/git-maintenance.ts: pack-index repair keeps the original intent (788f8f1: Rebuild stale pack lookup with Git's native explicit-pack atomic writer while preserving repository objects.)

Testing

Proof path: in-process harness. Added test files: 3.

Security

None.

Evidence

What I checked:

  • Introduced patch: Inspected the pinned merge-base-to-head diff; changes are confined to advisory owner classification, local-only Git execution, supporting tests, documentation, and one obsolete mock-baseline removal. (src/agents/worktrees/owner-protection.ts:134, ab4bc54b96b3)
  • Current main still needs the change: The production owners and affected tests/docs have no intervening changes between the merge base and fetched main; main still performs synchronous placement classification and lacks the maintenance transport restrictions. The shared mock baseline has unrelated reductions. (src/agents/worktrees/owner-protection.ts:128, 17bdf57ee5df)
  • Destructive cleanup retains fresh checks: The service passes census classification only to preliminary eligibility and passes the original exact policy to removal. Removal prepares registry guards and invokes exact owner checks before effects; the new prepared placement cache is separate from the mutation cache. (src/agents/worktrees/service.ts:1139, ab4bc54b96b3)
  • Worker adapter matches existing reconciliation: The existing async reader obtains placement records through the state worker; the adapter excludes local and reclaimed records exactly as the reconciliation query does. No persisted format, schema, configuration, or public plugin API changes. (src/gateway/worker-environments/placement-read-store.ts:47, ab4bc54b96b3)
  • Recorded production-boundary measurements: The fully supplied PR body records Linux Git 2.53 partial-clone maintenance with transport attempts falling 10→0, and Testbox census/full-service measurements with longest full-pass callback falling 194.38→4.59 ms. It reports both new regressions failing on original production code, 35 changed-suite tests passing, corrected lifecycle fixtures passing, and the final changed gate passing. These are isolated measurements, not deployed-Gateway proof; source identity is 5cc002e89b730cd5541b2745967590a71b39512067295407bb9f4f36c37922c4. (ab4bc54b96b3)
  • Existing owner intent: The merged census work explicitly preserves fresh destructive-mutation checks: perf(worktrees): avoid full session parsing during GC #166072. Earlier maintenance and pack-index repairs preserve repository objects and suspend failures with recovery guidance: fix(worktrees): stop repeated Git maintenance failures #165204 and fix(git): rebuild stale worktree pack indexes #165995. This patch retains those contracts. (src/agents/worktrees/owner-protection.ts:128, 4de57f22aa1d)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

PR surface

Source +41, Tests +123, Docs +2, Other -1. Total +165 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 3 53 12 +41
Tests 3 124 1 +123
Docs 1 3 1 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 8 180 15 +165

Labels

Label changes:

  • add P2: This bounded performance repair reduces cleanup callback stalls and unwanted background network waits without changing user settings.
  • 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 bounded performance repair reduces cleanup callback stalls and unwanted background network waits without changing user settings.
  • 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.

@steipete
steipete merged commit 8a31a24 into main Oct 8, 2026
205 of 207 checks passed
@steipete
steipete deleted the steipete/perf-micro-worktree-maintenance-main-thread-20260919 branch October 8, 2026 07:47
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
…aw#167030)

Read placement facts once through the worker for the advisory owner census and yield classification in batches. Preserve exact session and placement checks before destructive cleanup. Keep automatic Git maintenance and pack-index repair local-only so partial clones cannot block cleanup on promisor fetches.
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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S 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