Skip to content

perf(worktrees): batch-prune stale local metadata - #17278

Merged
nwparker merged 1 commit into
stablyai:mainfrom
nwparker:nwparker/perf-authoritative-local-worktree-metadata-gc
Aug 29, 2026
Merged

nwparker merged 1 commit into
stablyai:mainfrom
nwparker:nwparker/perf-authoritative-local-worktree-metadata-gc

Conversation

@nwparker

Copy link
Copy Markdown
Contributor

ELI5

Orca keeps a metadata card for each worktree so it can remember names, pins, links, and activity. Deleted worktrees could leave thousands of cards behind, and cleaning them one at a time repeatedly rescanned Git and copied session state. A fresh local Git inventory can now retire only the cards that are both missing and unused, in one batch.

This fixes the stale-metadata CPU amplifier from #15412. It does not claim to fix every independent source of high CPU described there.

What Changed

  • Capture a native-local metadata expectation before one asynchronous git worktree list scan.
  • Let only the fresh producer of a successful, non-empty scan batch-prune missing metadata; cached, coalesced, failed, aborted, invalidated, or rerouted scans do nothing.
  • Treat every Git-listed row, including prunable registrations, plus the configured repo path as live evidence.
  • Probe only captured metadata paths absent from Git with asynchronous fs/promises.stat, using bounded workers and one process-wide two-probe semaphore. A two-second batch deadline and caller abort both settle as unverifiable; existing paths and non-absence errors also fail closed.
  • Carry a common { generation, authorizedRootsRevision } side-effect token for every local scan, including WSL, through all three listing callers. Recheck it after probes and immediately before mutation; repo updates, worktree notifications, runtime changes, or newer root publication fence the older observation.
  • Revalidate metadata values and identities, local aliases, canonical rows, repo routing, and persisted ownership immediately before removal.
  • Preserve every candidate referenced by any WorkspaceSessionState field or host partition, mobile selection, SSH lease, migration entry, active automation, or non-final automation run. Session state is neither cloned nor mutated.
  • Remove qualifying legacy/canonical metadata, matching lineage, and cleanup/space-analysis sidecar rows in one batch with one scheduled save.
  • Carry every captured candidate not removed into synchronous lineage pruning as protected, and skip both root and lineage side effects if generation or root authority changes while Git, probes, or the caller is pending.

Why

The old cleanup shape could perform thousands of Git scans, session clones, and persistence schedules for one stale fleet. This keeps the authoritative Git observation singular and makes the persistence work linear while treating uncertainty as retention.

Linked Issue

Fixes #15412

Visual Proof

N/A — this changes main-process listing and persistence behavior only; there is no rendered UI or interaction change.

Safety and provider boundary

The governing invariant is agent-session.provider-ownership: only the execution host that owns an authoritative observation may retire its metadata. Loss of contact is never proof of process death, and this path does not stop a PTY, agent, process, delete a directory, or delete a Git ref.

Observation Metadata pruning Reason
Fresh, successful, non-empty native-local scan; candidate is absent from Git and disk and sessionless Allowed after synchronous revalidation One authoritative native Git inventory plus bounded native path verification proves absence
Any Git-listed registration, including a prunable row No A temporarily unavailable removable or network volume must not turn registration into deletion evidence
Path exists or filesystem result is unverifiable No Symlink/canonical spellings, permissions, and non-absence errors fail closed
Cached, coalesced, failed, empty, aborted, invalidated, routing-generation-stale, or superseded-root scan No The observation is not fresh authoritative absence
Metadata, alias, repo, settings, or project routing changed during Git No Captured identity/value/generation checks reject the stale decision
Candidate has any persisted session/recovery owner No Session-bearing state stays with its existing teardown/recovery authority
WSL No v1 cannot prove Linux-path and UNC aliases equivalent
SSH or runtime-remote No The remote execution host owns the observation
Folder workspace No There is no Git worktree inventory to prove absence
Malformed, folder-instance, foreign-host, ambiguous, or wrong-platform identity No Candidate validation and alias ownership fail closed

This is deliberately a native-local, sessionless v1. Remote/WSL/folder cleanup and broader terminal-manager or event-loop diagnostics remain out of scope. ui.showDotfilesByWorktree and cleanup dismissal preferences are not treated as live session ownership and remain under their existing cleanup paths.

Performance evidence

Opt-in 2,709-row in-memory benchmark:

metadata+session:     961.49ms -> 16.28ms
modeled Git scans:    2,709 -> 1
session clones:       2,709 -> 0
minimum save schedules: 5,418 -> 1

Command:

ORCA_LOCAL_METADATA_PRUNE_BENCH=1 pnpm exec vitest run \
  --config config/vitest.config.ts \
  src/main/persistence/tracking-repos/local-worktree-metadata-batch-pruning.bench.test.ts \
  --reporter=verbose

The wall times cover only modeled in-memory metadata/session work and vary by machine. They exclude filesystem-presence probes and do not claim end-to-end UI latency. A separate temporary real-Git measurement observed 2,709 git worktree list calls at 13.77s versus one call at 0.01s; those figures are illustrative, not a CI performance budget.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Local verification:

  • Changed-file Vitest suites: 239 passed; the opt-in benchmark was skipped in that run.
  • Adjacent native/Windows/WSL/SSH/catalog and ownership suites: 148 passed.
  • Focused timeout, semaphore, and authoritative-scan race suites: 33 passed.
  • pnpm tc:node passed.
  • pnpm run check:code-quality:changed passed with 0 findings across the changed files.
  • pnpm run check:reliability-gates passed for 99 gates.
  • git diff --check passed.
  • The opt-in 2,709-row benchmark passed.

Full repository lint/build and the platform matrix are left to PR CI.

Coverage includes capture-before-Git ordering, fresh/coalesced/cached behavior, invalidation during Git and filesystem probes, hung-probe timeout, external abort, global two-probe accounting and permit reuse, all three listing-call continuation gaps, WSL setup/root-publication races, native-to-WSL route races, Git-folder-Git repo updates, repo/project/settings/metadata/alias races, persisted JSON projection equality, every persisted session ownership shape, host/provider isolation, Unicode/macOS/Windows path aliases, prunable retention, symlink spellings, filesystem-error retention, batch save/sidecar behavior, and lineage ordering without rematerialization.

No Electron validation was run because this has no UI change. No live physical Windows, WSL, SSH, runtime-remote, or folder-workspace journey was run; those boundaries have deterministic coverage and fail closed.

Residual gaps: Node cannot cancel an already-running stat, so two permanently wedged filesystem calls can retain the two global permits; current and later batches still settle at their own deadlines and preserve every candidate. Real Windows drive/UNC behavior remains covered by mocks rather than a physical host. Direct-SSH lineage pruning also retains a pre-existing concurrent-create setup gap; this diff does not change that behavior and never enables metadata pruning from an SSH observation.

Compatibility notes:

  • No new Git command or option; the existing path remains Git 2.25 compatible.
  • No public IPC/RPC shape, stream opcode, or remote-wire behavior changes.
  • No provider-specific GitHub behavior was added.

AI Disclosure

Review

Primary risk is deleting metadata without enough authority. The implementation biases false negatives: any ambiguous ownership, changed state, path presence/error, unsupported provider, or stale scan preserves the row for a later scan. Sidecar pruning is best-effort and refetchable.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Reviewed for security, cross-platform behavior, SSH/remote ownership, mobile persisted owners, backwards compatibility, and performance.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@greptile-apps

greptile-apps Bot commented Aug 29, 2026

Copy link
Copy Markdown

Greptile Summary

This PR replaces repeated stale-worktree metadata cleanup with a single authoritative native-local Git scan followed by bounded filesystem verification and batch persistence updates.

  • Captures metadata and routing expectations before fresh local scans and fences side effects with scan-generation and root-authority tokens.
  • Retains metadata referenced by Git, the filesystem, session/recovery state, remote ownership, automation, or unsupported routing modes.
  • Batch-removes revalidated metadata, lineage, and sidecar snapshots while scheduling persistence once.
  • Adds bounded, abort-aware path probes and extensive race, ownership, platform, and performance coverage.

Confidence Score: 5/5

The PR appears safe to merge because no concrete changed-code failure remains after reviewing its authority, ownership, race, and fail-closed cleanup paths.

Destructive cleanup is confined to fresh native-local scans, uncertain filesystem and routing states retain metadata, persisted owners are comprehensively protected, and each candidate is synchronously revalidated before mutation.

Important Files Changed

Filename Overview
src/main/ipc/worktrees/listing/detected-worktree-scan-cache.ts Coordinates fresh-scan ownership, generation fencing, metadata pruning, root publication, and lineage cleanup without exposing cached or coalesced scans to destructive side effects.
src/main/ipc/worktrees/listing/authoritative-local-worktree-metadata-pruning.ts Restricts batch pruning to current native-local authoritative scans and retains Git-listed, existing, unverifiable, malformed, WSL, folder, and foreign candidates.
src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.ts Revalidates repository routing, persisted ownership, metadata identity, and aliases before deleting metadata and associated lineage.
src/main/persistence/restoring-sessions/session-worktree-ownership.ts Exhaustively classifies persisted session fields and collects worktree owners across local and host-specific partitions.
src/main/local-worktree-path-presence.ts Adds globally bounded asynchronous path probes whose timeouts, cancellation, and non-absence errors conservatively retain metadata.
src/main/worktree-lineage-pruning.ts Protects retained metadata candidates and path-equivalent live worktrees during synchronous lineage reconciliation.

Sequence Diagram

sequenceDiagram
  participant Caller
  participant Cache as Scan cache
  participant Git
  participant FS as Path probes
  participant Store
  Caller->>Cache: List local worktrees
  Cache->>Store: Capture metadata/routing expectation
  Cache->>Git: One fresh worktree list
  Git-->>Cache: Non-empty inventory
  Cache->>FS: Probe captured candidates absent from Git
  FS-->>Cache: Missing or unverifiable results
  Cache->>Store: Revalidate authority, owners, rows, and aliases
  Store-->>Cache: Batch-remove qualifying metadata
  Cache->>Store: Publish roots and prune unprotected lineage
  Cache-->>Caller: Authoritative worktree list
Loading

Reviews (1): Last reviewed commit: "perf(worktrees): batch-prune stale local..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This change adds authoritative local worktree metadata pruning with race guards for scan generations, routing, caller currency, and registered-root revisions. It adds bounded filesystem path probing with timeout and abort handling. It preserves session-owned metadata, normalized live paths, WSL roots, and lineage candidates. Persistence operations now invalidate local scan generations when repository or Windows runtime settings change. Listing handlers use centralized guarded side effects, and extensive tests cover pruning, invalidation, ownership, lineage, concurrency, and routing cases.

Merge Risk: 🟡 Moderate · up to c38f3

The batch cleanup can delete persistent worktree metadata after an authorized-root change because that change is detected only after pruning has started, weakening the intended fail-closed behavior. Merge should wait for the authorization check to guard entry to pruning; the positive pruning tests should also pin their platform assumptions so they remain reliable across operating systems.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR satisfies the local batch-cleanup requirements in #15412, including authoritative scanning, metadata and ownership pruning, save coalescing, fail-closed behavior, and regression coverage. It do… Either implement the remaining coding requirements from #15412, or link this PR to a narrower child issue and remove the Fixes #15412 relationship. Document which issue items remain unresolved and provide follow-up issue links for them.
Docstring Coverage ⚠️ Warning Docstring coverage is 6.41% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 78 functions across 38 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary change: batch pruning of stale local worktree metadata.
Description check ✅ Passed The description follows the required template, explains the change and rationale, documents scope and safety boundaries, links issue #15412, records testing, and completes the relevant checklist items…
Out of Scope Changes check ✅ Passed The changes support the stated local metadata-pruning objective. Scan generations, root revisions, path probing, ownership protection, lineage handling, semaphore cancellation, persistence wiring, ben…
Full details: Description check

Explanation

The description follows the required template, explains the change and rationale, documents scope and safety boundaries, links issue #15412, records testing, and completes the relevant checklist items.

Full details: Linked Issues check

Explanation

The PR satisfies the local batch-cleanup requirements in #15412, including authoritative scanning, metadata and ownership pruning, save coalescing, fail-closed behavior, and regression coverage. It does not implement other requested issue items, including terminal-manager lifecycle cleanup, diagnostics, timeout instrumentation, and a supported stale-state CLI/RPC.

Full details: Out of Scope Changes check

Explanation

The changes support the stated local metadata-pruning objective. Scan generations, root revisions, path probing, ownership protection, lineage handling, semaphore cancellation, persistence wiring, benchmarks, and tests are directly related to correctness, safety, or performance.

  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 94c50f35-7655-44bb-8d66-0a2616489c02

📥 Commits

Reviewing files that changed from the base of the PR and between 0bf5361 and c38f37d.

📒 Files selected for processing (38)
  • src/main/ipc/registered-worktree-roots-cache.ts
  • src/main/ipc/worktrees-authoritative-local-metadata-pruning.test.ts
  • src/main/ipc/worktrees-test-harness.ts
  • src/main/ipc/worktrees-test-ipc-surface.ts
  • src/main/ipc/worktrees-test-metadata-pruning-store.ts
  • src/main/ipc/worktrees-windows.test.ts
  • src/main/ipc/worktrees/listing/authoritative-local-worktree-metadata-pruning.ts
  • src/main/ipc/worktrees/listing/detected-provider-listing.ts
  • src/main/ipc/worktrees/listing/detected-worktree-scan-cache.ts
  • src/main/ipc/worktrees/listing/register-worktree-catalog-handlers.ts
  • src/main/local-worktree-path-presence.test.ts
  • src/main/local-worktree-path-presence.ts
  • src/main/local-worktree-scan-generation.ts
  • src/main/persistence-initial-load.test.ts
  • src/main/persistence-repo-lifecycle.test.ts
  • src/main/persistence-settings-update.test.ts
  • src/main/persistence-update-repo.test.ts
  • src/main/persistence/applying-settings/settings-update.ts
  • src/main/persistence/loading-store/metadata-lineage-batch-pruning.test.ts
  • src/main/persistence/loading-store/metadata-lineage-operations.ts
  • src/main/persistence/loading-store/profile-preferences.ts
  • src/main/persistence/loading-store/project-collection-operations.ts
  • src/main/persistence/loading-store/repo-lifecycle-operations.ts
  • src/main/persistence/loading-store/worktree-identity-metadata.ts
  • src/main/persistence/restoring-sessions/session-worktree-ownership.test.ts
  • src/main/persistence/restoring-sessions/session-worktree-ownership.ts
  • src/main/persistence/tracking-repos/local-worktree-metadata-batch-pruning.bench.test.ts
  • src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.test.ts
  • src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.ts
  • src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts
  • src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.ts
  • src/main/persistence/tracking-repos/project-host-operations.ts
  • src/main/persistence/tracking-repos/repo-update-operations.ts
  • src/main/worktree-lineage-pruning.test.ts
  • src/main/worktree-lineage-pruning.ts
  • src/main/worktree-retention-path-comparison.ts
  • src/shared/priority-semaphore.test.ts
  • src/shared/priority-semaphore.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

const hostSessionSnapshot = structuredClone(hostSession)
const cloneSpy = vi.spyOn(globalThis, 'structuredClone')

const removed = pruneCaptured(state, scan, staleIds)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Description: Determine whether CI runs the Vitest suites on Windows, and confirm platform-dependent candidate validation.
set -euo pipefail

fd -H -t f -e yml -e yaml . .github/workflows 2>/dev/null | while IFS= read -r file; do
  echo "== $file"
  rg -n 'runs-on|matrix|windows|os:' "$file"
done

fd -t f 'missing-local-worktree-metadata-pruning.ts' src | while IFS= read -r file; do
  echo "== $file"
  ast-grep outline "$file" --items all
  rg -n -C 5 'isValidCandidateId|win32|isWindowsAbsolutePathLike|startsWith\(.\/.\)' "$file"
done

Repository: stablyai/orca

Length of output: 20994


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== repository conventions and learnings'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -type f -name '*.md' -print

echo '== operation-level test context'
sed -n '1,190p' src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts
sed -n '300,365p' src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts
sed -n '455,485p' src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts

echo '== facade test context'
sed -n '1,80p' src/main/persistence/loading-store/metadata-lineage-batch-pruning.test.ts

echo '== directly bound declarations and call sites'
rg -n -C 4 'function pruneCaptured|const pruneCaptured|pruneCaptured\(|pruneSessionlessMissingLocalWorktreeMetadataForRepo\(' src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts src/main/persistence/loading-store/metadata-lineage-batch-pruning.test.ts src/main/persistence

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== applicable conventions'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/repo-wide.md
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/src.md

echo '== operation implementation and facade'
sed -n '90,155p' src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.ts
sed -n '195,225p' src/main/persistence/loading-store/metadata-lineage-operations.ts
rg -n -C 3 'vitest|unit-tests|test:unit|missing-local-worktree-metadata-pruning|metadata-lineage-batch-pruning' .github/workflows package.json

echo '== workflow test commands on Windows-capable jobs'
sed -n '1,75p' .github/workflows/unit-tests.yml
sed -n '640,715p' .github/workflows/pr.yml
sed -n '715,760p' .github/workflows/pr.yml
sed -n '1,75p' .github/workflows/skill-update-roundtrip.yml

Repository: stablyai/orca

Length of output: 26420


Make the pruning tests independent of the runner OS. pruneSessionlessMissingLocalWorktreeMetadataForRepo defaults to process.platform and rejects /workspace/... paths on win32. Pin 'linux' in the positive pruneCaptured cases. Use platform-appropriate paths in metadata-lineage-batch-pruning.test.ts, because its facade does not expose platform.

📍 Affects 2 files
  • src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts#L102-L102 (this comment)
  • src/main/persistence/loading-store/metadata-lineage-batch-pruning.test.ts#L44-L47

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Main process reaches 100% CPU after terminal/worktree churn and retains thousands of removed worktrees

1 participant