Garbage-collect stale worktreeMeta for externally-deleted worktrees (#7107)
* Garbage-collect stale worktreeMeta for externally-deleted worktrees at load worktreeMeta rows are minted for every worktree Orca ever discovers but were only deleted by Orca-initiated removal flows. Worktrees deleted outside Orca (git worktree remove, rm -rf, agent scripts) purge renderer session state without ever removing the meta, so the map grew monotonically - 318 of 503 entries (63%, ~110KB) on the reference machine pointed at long-deleted paths. These entries never reach the renderer; they only cost disk bytes, parse time, and memory. GC at load is deliberately narrow: local-host entries only (SSH/runtime repos, remote meta.hostId, and WSL UNC paths are skipped - a local existsSync would falsely condemn remote paths), only when the checkout path no longer exists, only after a 30-day idle grace (preserving pushTarget cleanup for recently-vanished worktrees and quick recreations), and never when the entry lacks timestamps to prove idleness. Lineage rows cascade like removeWorktreeMeta. Co-authored-by: Orca <help@stably.ai> * Fix GC false positives: folder-workspace instances, WSL paths on Windows From adversarial review of the GC commit: - Folder-project workspace instances are keyed repoId::path::workspace: <uuid>; splitting on the first :: made the existence probe test a path-with-suffix that never exists, deleting idle folder workspaces - whose meta IS the workspace record - and cascading into terminal- history deletion. Instance keys are now skipped entirely. - On Windows, WSL linked worktrees carry Linux-style paths from git porcelain that a Windows existsSync cannot probe; skip non-Windows paths on win32. - Idle-grace check now runs before existsSync (skips the stat fan-out for active entries and shrinks the slow-NFS startup tail), and a null worktreeMeta map in the file is normalized instead of throwing outside the parse guard. Co-authored-by: Orca <help@stably.ai> --------- Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -4584,6 +4584,92 @@ describe('Store', () => {
|
||||
expect(statSync(dataFile()).ino).toBe(inoBefore)
|
||||
})
|
||||
|
||||
// ── worktreeMeta startup GC ────────────────────────────────────────
|
||||
|
||||
it('garbage-collects stale local worktreeMeta at load with a 30-day grace', async () => {
|
||||
const OLD = Date.now() - 40 * 24 * 60 * 60 * 1000
|
||||
const RECENT = Date.now() - 1 * 24 * 60 * 60 * 1000
|
||||
const missing = (name: string): string => join(testState.dir, 'gone', name)
|
||||
const meta = (lastActivityAt: number, extra: Record<string, unknown> = {}) => ({
|
||||
displayName: '',
|
||||
comment: '',
|
||||
lastActivityAt,
|
||||
...extra
|
||||
})
|
||||
const liveKey = `r1::${testState.dir}`
|
||||
const deadKey = `r1::${missing('dead')}`
|
||||
const recentKey = `r1::${missing('recent')}`
|
||||
const sshKey = `ssh-repo::/home/alice/gone`
|
||||
const remoteHostKey = `r1::${missing('remote-host')}`
|
||||
const orphanKey = `removed-repo::${missing('orphan')}`
|
||||
const wslKey = `r1::\\\\wsl$\\Ubuntu\\home\\gone`
|
||||
|
||||
writeDataFile({
|
||||
repos: [
|
||||
makeRepo(),
|
||||
makeRepo({ id: 'ssh-repo', path: '/home/alice/repo', connectionId: 'conn-1' })
|
||||
],
|
||||
worktreeMeta: {
|
||||
[liveKey]: meta(OLD),
|
||||
[deadKey]: meta(OLD),
|
||||
[recentKey]: meta(RECENT),
|
||||
[sshKey]: meta(OLD),
|
||||
[remoteHostKey]: meta(OLD, { hostId: 'ssh:conn-1' }),
|
||||
[orphanKey]: meta(OLD),
|
||||
[wslKey]: meta(OLD)
|
||||
},
|
||||
worktreeLineageById: { [deadKey]: { parentWorktreeId: liveKey } }
|
||||
})
|
||||
|
||||
const store = await createStore()
|
||||
const kept = Object.keys(store.getAllWorktreeMeta())
|
||||
|
||||
expect(kept).toContain(liveKey) // path exists
|
||||
expect(kept).toContain(recentKey) // inside the grace window
|
||||
expect(kept).toContain(sshKey) // SSH repo: remote paths never checked locally
|
||||
expect(kept).toContain(remoteHostKey) // remote hostId on the meta itself
|
||||
expect(kept).toContain(wslKey) // WSL UNC path
|
||||
expect(kept).not.toContain(deadKey)
|
||||
expect(kept).not.toContain(orphanKey)
|
||||
expect(store.getWorktreeLineage(deadKey)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('never GCs folder-workspace instance metas — the meta IS the workspace', async () => {
|
||||
const OLD = Date.now() - 40 * 24 * 60 * 60 * 1000
|
||||
const folderInstanceKey = `r1::${join(testState.dir, 'gone-folder')}::workspace:11111111-1111-4111-8111-111111111111`
|
||||
writeDataFile({
|
||||
repos: [makeRepo({ kind: 'folder' })],
|
||||
worktreeMeta: {
|
||||
[folderInstanceKey]: { displayName: 'Session A', comment: '', lastActivityAt: OLD }
|
||||
}
|
||||
})
|
||||
|
||||
const store = await createStore()
|
||||
expect(Object.keys(store.getAllWorktreeMeta())).toContain(folderInstanceKey)
|
||||
})
|
||||
|
||||
it('never GCs Linux-style WSL worktree paths on Windows', async () => {
|
||||
const OLD = Date.now() - 40 * 24 * 60 * 60 * 1000
|
||||
const wslLinkedKey = 'r1::/home/user/gone-worktree'
|
||||
writeDataFile({
|
||||
repos: [makeRepo()],
|
||||
worktreeMeta: {
|
||||
[wslLinkedKey]: { displayName: '', comment: '', lastActivityAt: OLD }
|
||||
}
|
||||
})
|
||||
|
||||
await withPlatform('win32', async () => {
|
||||
const store = await createStore()
|
||||
expect(Object.keys(store.getAllWorktreeMeta())).toContain(wslLinkedKey)
|
||||
})
|
||||
})
|
||||
|
||||
it('tolerates a null worktreeMeta map in the durable file', async () => {
|
||||
writeDataFile({ worktreeMeta: null })
|
||||
const store = await createStore()
|
||||
expect(store.getAllWorktreeMeta()).toEqual({})
|
||||
})
|
||||
|
||||
// ── GitHub cache sidecar ───────────────────────────────────────────
|
||||
|
||||
it('cache refreshes never rewrite the durable state file', async () => {
|
||||
|
||||
+87
-1
@@ -112,6 +112,7 @@ import {
|
||||
type ExecutionHostId
|
||||
} from '../shared/execution-host'
|
||||
import { toRelaySshPtyId } from './providers/ssh-pty-id'
|
||||
import { isWslUncPath } from '../shared/wsl-paths'
|
||||
import {
|
||||
isTerminalLeafId,
|
||||
makePaneKey,
|
||||
@@ -125,9 +126,14 @@ import {
|
||||
import { agentHookServer } from './agent-hooks/server'
|
||||
import { pruneLocalTerminalScrollbackBuffers } from '../shared/workspace-session-terminal-buffers'
|
||||
import { pruneWorkspaceSessionBrowserHistory } from '../shared/workspace-session-browser-history'
|
||||
import { getRepoIdFromWorktreeId, getWorktreePathBasenameFromId } from '../shared/worktree-id'
|
||||
import {
|
||||
FOLDER_WORKSPACE_INSTANCE_SEPARATOR,
|
||||
getRepoIdFromWorktreeId,
|
||||
getWorktreePathBasenameFromId
|
||||
} from '../shared/worktree-id'
|
||||
import {
|
||||
isPathInsideOrEqual,
|
||||
isWindowsAbsolutePathLike,
|
||||
normalizeRuntimePathForComparison
|
||||
} from '../shared/cross-platform-path'
|
||||
import { normalizeTerminalQuickCommands } from '../shared/terminal-quick-commands'
|
||||
@@ -335,6 +341,82 @@ function getGithubCacheFile(): string {
|
||||
return join(dirname(getDataFile()), 'orca-github-cache.json')
|
||||
}
|
||||
|
||||
// Why: worktrees deleted outside Orca (git CLI worktree remove, rm -rf,
|
||||
// agent scripts) purge renderer session state but nothing removed their
|
||||
// worktreeMeta, so the map grew monotonically (63% dead entries measured on
|
||||
// a heavy install). GC is deliberately narrow: local-host entries only
|
||||
// (SSH/runtime metas embed remote paths a local existsSync would falsely
|
||||
// condemn; WSL UNC paths are skipped the same way), and only after a
|
||||
// 30-day idle grace so pushTarget cleanup for recently-vanished worktrees
|
||||
// and quick recreations keep their metadata.
|
||||
const WORKTREE_META_GC_GRACE_MS = 30 * 24 * 60 * 60 * 1000
|
||||
|
||||
function gcStaleWorktreeMeta(state: PersistedState): number {
|
||||
// Why: a hand-corrupted file with `"worktreeMeta": null` overrides the
|
||||
// defaults merge; normalize instead of throwing outside the parse guard.
|
||||
state.worktreeMeta ??= {}
|
||||
const repoById = new Map(state.repos.map((repo) => [repo.id, repo]))
|
||||
const projectIds = new Set((state.projects ?? []).map((project) => project.id))
|
||||
const now = Date.now()
|
||||
let removed = 0
|
||||
for (const key of Object.keys(state.worktreeMeta)) {
|
||||
// Why: folder-project workspace instances are keyed
|
||||
// `repoId::path::workspace:<uuid>` and their meta IS the workspace
|
||||
// record — never a filesystem-checkout row. Skip them entirely.
|
||||
if (key.includes(FOLDER_WORKSPACE_INSTANCE_SEPARATOR)) {
|
||||
continue
|
||||
}
|
||||
const separator = key.indexOf('::')
|
||||
if (separator === -1) {
|
||||
continue
|
||||
}
|
||||
const ownerId = key.slice(0, separator)
|
||||
const worktreePath = key.slice(separator + 2)
|
||||
const meta = state.worktreeMeta[key]
|
||||
const repo = repoById.get(ownerId)
|
||||
if (repo) {
|
||||
if (repo.connectionId || getRepoExecutionHostId(repo) !== LOCAL_EXECUTION_HOST_ID) {
|
||||
continue
|
||||
}
|
||||
} else if (projectIds.has(ownerId)) {
|
||||
// Project-owned metas keep project/host semantics on the entry itself;
|
||||
// stay conservative and leave them to their own lifecycle.
|
||||
continue
|
||||
}
|
||||
// Unowned entries (repo removed before removeProject pruned metas) fall
|
||||
// through to the same missing-path + idle-grace gate.
|
||||
if (meta?.hostId && meta.hostId !== LOCAL_EXECUTION_HOST_ID) {
|
||||
continue
|
||||
}
|
||||
if (!isAbsolute(worktreePath) || isWslUncPath(worktreePath)) {
|
||||
continue
|
||||
}
|
||||
// Why: WSL linked worktrees on Windows carry Linux-style paths from git
|
||||
// porcelain; a Windows existsSync cannot probe those and would falsely
|
||||
// condemn live worktrees.
|
||||
if (process.platform === 'win32' && !isWindowsAbsolutePathLike(worktreePath)) {
|
||||
continue
|
||||
}
|
||||
// Why keep timestamp-less entries: without lastActivityAt/createdAt we
|
||||
// cannot prove the 30-day idle grace elapsed; the measured dead entries
|
||||
// all carry timestamps, so this costs almost nothing in reclaimed bytes.
|
||||
// Grace runs before the stat so healthy profiles skip the existsSync
|
||||
// fan-out (and its slow-NFS tail) for active entries entirely.
|
||||
const newestTouch = Math.max(meta?.lastActivityAt ?? 0, meta?.createdAt ?? 0)
|
||||
if (newestTouch === 0 || now - newestTouch < WORKTREE_META_GC_GRACE_MS) {
|
||||
continue
|
||||
}
|
||||
if (existsSync(worktreePath)) {
|
||||
continue
|
||||
}
|
||||
delete state.worktreeMeta[key]
|
||||
delete state.worktreeLineageById[key]
|
||||
delete state.workspaceLineageByChildKey[worktreeWorkspaceKey(key)]
|
||||
removed++
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
function readGithubCacheSnapshot(): PersistedState['githubCache'] | null {
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(getGithubCacheFile(), 'utf-8')) as unknown
|
||||
@@ -3322,6 +3404,10 @@ export class Store {
|
||||
}
|
||||
result = folderScopeConnectionMigration.state
|
||||
|
||||
if (gcStaleWorktreeMeta(result) > 0) {
|
||||
this.loadNeedsSave = true
|
||||
}
|
||||
|
||||
const migrated = this.migrateTelemetry(result, fileExistedOnLoad)
|
||||
|
||||
// githubCache lives in a sidecar file now (see getGithubCacheFile). A
|
||||
|
||||
Reference in New Issue
Block a user