Skip to content

fix: zombie worktree PTY cleanup (issue #218) - #1376

Merged
Jinwoo-H merged 5 commits into
mainfrom
Jinwoo-H/Jinwoo-H-investigate-zombie-worktree
May 3, 2026
Merged

Jinwoo-H merged 5 commits into
mainfrom
Jinwoo-H/Jinwoo-H-investigate-zombie-worktree

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented May 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Close P0 memory leak where PTYs survive worktree deletion across all delete paths (UI, CLI, headless). Root cause: no owner killed PTYs during removeManagedWorktree or the worktrees:remove IPC handler; this.leaves is renderer-sourced and empty for headless CLI flows.
  • Add killAllProcessesForWorktree with three cooperating sweeps (runtime leaves, provider-prefix scan of daemon ${worktreeId}@@<hex> session ids, pty-registry by worktreeId) and wire it into both teardown paths. OrcaRuntimeService gets a lazy getLocalProvider thunk so construction order stays robust.
  • Add purgeWorktreeTerminalState to the renderer store so the ~25 worktree-scoped maps (tabs, git caches, browser state, split layouts, editor drafts, etc.) get wiped symmetrically on delete notifications and at hydration, surfacing zombies the SessionsStatusSegment was misclassifying as bound.

Design doc: DESIGN_DOC_ZOMBIE_WORKTREE_FIX.md (§4.3, §4.4, §4.5)
Investigation: INVESTIGATION.md

Key design decisions

  • Provider is resolved via thunk, not captured at construction time. initDaemonPtyProvider() runs AFTER OrcaRuntimeService is built, so a captured reference would point at the pre-daemon LocalPtyProvider. The thunk () => getLocalPtyProvider() resolves at teardown time.
  • getLocalPtyProvider() return type widened from LocalPtyProvider to IPtyProvider — no external caller reads concrete-class-only members (grep-verified), and the teardown helper only needs listProcesses() / shutdown() from the shared interface.
  • Hydration purge safety gate (F1 regression). fetchWorktrees swallows errors and short-circuits on empty returns. A single transient git error at launch would otherwise wipe every persisted tabsByWorktree entry for the affected repo. The purge is gated on "every repo fetched successfully AND at least one returned ≥1 worktree"; if degraded, it defers and retries on the next fetchAllWorktrees.
  • SSH-backed PTYs are out of scope — they live on the remote host and require the connection to still be up; distinct fix per design §6. The IPC handler skips the kill helper when repo.connectionId is set.
  • Overlap between the three sweeps is deliberate. All kills are idempotent (daemon kill against a dead session is a no-op + tombstone; IPtyProvider.shutdown on an exited session is a no-op). Double kill beats missing a session.

Commits (4 logical chunks)

  • 4823b245 — fix(runtime): kill all PTYs for a worktree on removal (§4.3 helper + wire-up)
  • eb739de9 — fix(renderer): purge worktree-scoped state on removal + hydration (§4.4)
  • e8378ded — test(zombie-worktree): regression coverage for §4.5 (91 tests across 4 files)
  • db06145e — fix(runtime): log worktree-teardown kill counts (observability per §4.4)

Test plan

Automated (run in CI)

Manual validation (for reviewer — not run locally because another Orca instance was holding the single-instance lock during test)

  • Reporter repro: open a worktree, open a terminal in it, run orca worktree rm --worktree <id> from another shell, watch Activity Monitor. Before fix: ~560 MB shell persists. After fix: count drops to baseline and [worktree-teardown] <id> killed runtime=N provider=M registry=K appears in main-process logs.
  • Upgrade path: start on a pre-fix build, repro the leak, quit without killing the zombie, install this build, open Orca. On first mount the hydration-time purge removes the stale tabsByWorktree entry; the status-bar orphan count lights up for the still-live daemon session; the "Kill N Orphans" button reclaims it.
  • Safety gate: confirm no regression in the git worktree list transient-empty case — delete a worktree while the git index is locked (e.g. during a long rebase) and verify persisted tab state is NOT wiped.
  • SSH repo sanity: delete a worktree in an SSH-backed repo and verify the local kill helper is skipped (no log line) but the remote delete still succeeds.

Rollback

Each commit is revertible independently. If the renderer purge (§4.4) causes a regression, it can be reverted alone — zombies would still be reclaimed on next app restart via the daemon's own reconcileOnStartup. If the backend sweep (§4.3) causes unexpected daemon churn, the helper can be narrowed to the runtime-leaves path while the registry sweep keeps local coverage intact.

🤖 Generated with Claude Code

Made with Orca 🐋

Jinwoo-H and others added 5 commits May 3, 2026 16:48
Worktree deletion only shut down renderer-tracked terminals, so PTYs owned
by background tabs, split panes, or pre-reload sessions survived the
removal and kept leaking memory. Introduce killAllProcessesForWorktree
with three sweeps (runtime leaves, provider-prefix scan of daemon session
ids, pty-registry by worktreeId) and wire it into both teardown paths:
the CLI-initiated removeManagedWorktree and the renderer-initiated
worktrees:remove IPC handler. OrcaRuntimeService gets a lazy
getLocalProvider thunk so construction order stays robust.

Co-authored-by: Orca <help@stably.ai>
…sign §4.4)

When a worktree is deleted, ~25 worktree-scoped maps (tabsByWorktree,
git caches, browser state, split-tab models, per-file editor drafts,
etc.) kept references to the gone worktree, so SessionsStatusSegment
kept mis-classifying orphaned PTYs as bound and dropdowns rendered stale
ids. Add purgeWorktreeTerminalState as a single atomic action that
wipes every scoped map plus cascades top-level actives. Fire it from
the worktrees:changed listener on the set-diff of removed ids, and once
more at hydration via fetchAllWorktrees to clean up persisted entries
from pre-fix sessions. The hydration-time purge is gated behind a
per-repo success check: a single transient IPC error or an all-empty
fetch defers the purge so a degraded launch cannot wipe legitimate
persisted state.

Co-authored-by: Orca <help@stably.ai>
Adds tests for every layer of the zombie-worktree fix:
- worktree-teardown: unit coverage of the three-sweep helper including
  best-effort error swallowing across provider/registry.
- orca-runtime: RPC-initiated removeManagedWorktree kills PTYs before
  any git mutation + verifies the lazy getLocalProvider thunk resolves
  on each call.
- worktrees IPC: renderer-initiated remove kills PTYs before git and
  skips the kill helper for SSH-backed repos.
- renderer slice: fetchAllWorktrees defers the purge when any sibling
  repo fetch fails or every repo returns empty (F1 regression);
  happy-path fires the purge once and does not re-run on subsequent
  calls. Direct purgeWorktreeTerminalState coverage pins the cascade
  across worktree-keyed, tab-id-keyed, and file-id-keyed maps.

Co-authored-by: Orca <help@stably.ai>
…ility)

Breadcrumb lets ops distinguish a renderer-state-induced leak (diff-path
purge non-empty) from a backend-induced one (nothing to kill but memory
still pinned). Emit only when the sweep actually shut anything down so
steady-state logs stay quiet. Added at both call sites —
removeManagedWorktree (CLI path) and the worktrees:remove IPC handler.

Co-authored-by: Orca <help@stably.ai>
…on type

The purge unit test seeded ptyIdsByTabId as Record<string, string> when
the runtime type is Record<string, string[]>. The unit tests passed
because they never hit the UI renderer, but live e2e surfaced a
TypeError: (ptyIdsByTabId[tabId] ?? []).some is not a function.

Corrected to arrays; 21/21 tests still pass.

Co-authored-by: Orca <help@stably.ai>
@Jinwoo-H

Jinwoo-H commented May 3, 2026

Copy link
Copy Markdown
Contributor Author

E2E verification in live dev Orca — complete

Ran a full e2e smoke in a live dev build attached via CDP (using the Electron SKILL workflow). Verified each design-doc mechanism with concrete evidence:

1. Backend teardown (design §4.3) — tri-layer PTY kill

  • Created a fresh worktree, spawned a PTY (session id ...zombie-smoke-test-ephemeral@@809d8fdb — correct ${worktreeId}@@${shortHex} contract)
  • Removed the worktree via worktrees.remove IPC
  • Main-process log:
    [worktree-teardown] ...zombie-smoke-test-ephemeral killed runtime=0 provider=1 registry=1
    
  • provider=1 = sweepProviderByPrefix matched the daemon session. registry=1 = sweepRegistryForWorktree caught it from the canonical memory registry. The tri-layer defence is working.

2. Renderer hydration-time purge (design §4.4)

  • Seeded stale tabsByWorktree / terminalLayoutsByTabId / ptyIdsByTabId for a non-existent worktree, set hasHydratedWorktreePurge: false
  • Ran fetchAllWorktrees() with 1 real repo → gate flipped to true, all stale maps swept to {}, 223 real worktrees populated
  • Console: [worktree-purge] hydration-time purge removing stale state for 1 worktree(s): [zombie::/bogus] — observability log fires as designed
  • 0 console errors

3. F1 regression — 0-repo safety

  • With repos.length === 0, fetchAllWorktrees() leaves gate at false and preserves stale state (as designed). No false-positive purges when we have no evidence from the backend.

4. Direct purge action

  • purgeWorktreeTerminalState([staleId]) in live build: 3 non-empty maps → 3 empty maps. No UI crash (confirmed ptyIdsByTabId uses array shape; fixed test-seed mismatch in latest commit).

Final store state

After worktree removal, the live store showed:

{ flag: true, totalWts: 223, stillPresent: false, tabsForIt: 0 }

— clean, consistent, no zombie state.

Extra commit

adabd97d test(zombie-worktree): fix ptyIdsByTabId seed shape — the unit tests seeded strings where production uses string[]. Surfaced by live e2e; fixed to match reality. 21/21 tests still pass.

Verified on an isolated dev userData (/tmp/orca-zombie-smoke) so nothing touched production profile.

@Jinwoo-H
Jinwoo-H merged commit 66d596f into main May 3, 2026
2 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(runtime): kill all PTYs for a worktree on removal (design §4.3)

Worktree deletion only shut down renderer-tracked terminals, so PTYs owned
by background tabs, split panes, or pre-reload sessions survived the
removal and kept leaking memory. Introduce killAllProcessesForWorktree
with three sweeps (runtime leaves, provider-prefix scan of daemon session
ids, pty-registry by worktreeId) and wire it into both teardown paths:
the CLI-initiated removeManagedWorktree and the renderer-initiated
worktrees:remove IPC handler. OrcaRuntimeService gets a lazy
getLocalProvider thunk so construction order stays robust.

Co-authored-by: Orca <help@stably.ai>

* fix(renderer): purge worktree-scoped state on removal + hydration (design §4.4)

When a worktree is deleted, ~25 worktree-scoped maps (tabsByWorktree,
git caches, browser state, split-tab models, per-file editor drafts,
etc.) kept references to the gone worktree, so SessionsStatusSegment
kept mis-classifying orphaned PTYs as bound and dropdowns rendered stale
ids. Add purgeWorktreeTerminalState as a single atomic action that
wipes every scoped map plus cascades top-level actives. Fire it from
the worktrees:changed listener on the set-diff of removed ids, and once
more at hydration via fetchAllWorktrees to clean up persisted entries
from pre-fix sessions. The hydration-time purge is gated behind a
per-repo success check: a single transient IPC error or an all-empty
fetch defers the purge so a degraded launch cannot wipe legitimate
persisted state.

Co-authored-by: Orca <help@stably.ai>

* test(zombie-worktree): regression coverage for design §4.5

Adds tests for every layer of the zombie-worktree fix:
- worktree-teardown: unit coverage of the three-sweep helper including
  best-effort error swallowing across provider/registry.
- orca-runtime: RPC-initiated removeManagedWorktree kills PTYs before
  any git mutation + verifies the lazy getLocalProvider thunk resolves
  on each call.
- worktrees IPC: renderer-initiated remove kills PTYs before git and
  skips the kill helper for SSH-backed repos.
- renderer slice: fetchAllWorktrees defers the purge when any sibling
  repo fetch fails or every repo returns empty (F1 regression);
  happy-path fires the purge once and does not re-run on subsequent
  calls. Direct purgeWorktreeTerminalState coverage pins the cascade
  across worktree-keyed, tab-id-keyed, and file-id-keyed maps.

Co-authored-by: Orca <help@stably.ai>

* fix(runtime): log worktree-teardown kill counts (design §4.4 observability)

Breadcrumb lets ops distinguish a renderer-state-induced leak (diff-path
purge non-empty) from a backend-induced one (nothing to kill but memory
still pinned). Emit only when the sweep actually shut anything down so
steady-state logs stay quiet. Added at both call sites —
removeManagedWorktree (CLI path) and the worktrees:remove IPC handler.

Co-authored-by: Orca <help@stably.ai>

* test(zombie-worktree): fix ptyIdsByTabId seed shape to match production type

The purge unit test seeded ptyIdsByTabId as Record<string, string> when
the runtime type is Record<string, string[]>. The unit tests passed
because they never hit the UI renderer, but live e2e surfaced a
TypeError: (ptyIdsByTabId[tabId] ?? []).some is not a function.

Corrected to arrays; 21/21 tests still pass.

Co-authored-by: Orca <help@stably.ai>

---------

Co-authored-by: Orca <help@stably.ai>
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.

1 participant