Skip to content

Reclaim stale temporary indexes with age-based cleanup - #4469

Merged
max-sixty merged 5 commits into
max-sixty:mainfrom
jonaheaton:jonah/sweep-stale-temp-indexes-v2
Oct 23, 2026
Merged

max-sixty merged 5 commits into
max-sixty:mainfrom
jonaheaton:jonah/sweep-stale-temp-indexes-v2

Conversation

@jonah-osmo

@jonah-osmo jonah-osmo commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Abruptly terminated commands can leave full temporary Git index copies behind. The contributor reported 52,786 files totaling 127 GB after three days of frequent statusline cancellations.

Reclaim index copies and their Git lock siblings older than one hour when a command next creates a temporary index. Keep the existing filename prefix so cleanup also handles files left by older versions. Sweep the system temp directory once per process, without making other probe threads wait, and retain best-effort cleanup in the Git-directory fallback. Normal exits still remove their own temporary indexes.

This uses age alone: no PID-tagged filenames, process checks, or platform-specific liveness behavior. Move commit-preview approval before temporary-index creation so an unattended approval prompt cannot age out an index needed afterward. The one-hour limit is a retention policy; a suspended operation or unusually slow Git filter can still exceed it. Statusline computations are unchanged.

Validation: regression tests cover stale indexes and locks, recent/future/unrelated files, both storage locations, cleanup failures, real-index preservation, and the actual approval wait. The approval test fails with the old ordering and passes with the fix. Independent review, lint, docs sync, and docs build passed. The local full gate passed 5,412 tests; three PowerShell tests failed because the installed pwsh also crashes with Stack overflow on a standalone arithmetic command outside the repository.

This was written by Codex on behalf of max-sixty

`TempIndex`'s `Drop` is the only thing that removes the index copy
`temp_index()` writes, so a `SIGKILL` strands it. A host that renders the
statusline in the background does exactly that as a matter of course: it
supersedes a slow `wt list statusline` on the next refresh. Each orphan is a
full copy of the repository index, so the files accumulate without bound —
measured at 52,786 files and 127 GB of `/tmp` over three days on a machine
running ~25 concurrent sessions against a 2.6 MB index.

Name each temp index after its creating PID and sweep the directory before
creating the next one, reclaiming entries whose owner is gone. Only
worktrunk's own files are candidates, so a foreign temp file in a shared
directory is never touched, and an age backstop covers a reused PID. The
sweep is best-effort in the manner of `cache::sweep_lru`: errors are logged
at debug and the next call tries again.

Drop still handles every ordinary exit; this only covers the kill.

Co-Authored-By: Claude Opus 5 <[email protected]>

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

temp_index() is called once per worktree during wt list (the conflict probe in src/commands/list/collect/tasks.rs calls write_tracked_worktree_tree / write_index_tree, and working_tree_diff_stats calls it again when untracked files exist). The picker preview calls it too. Because the sweep runs inside temp_index(), each of those calls reads the whole system temp directory, mostly in parallel threads. That cost grows with the number of worktrees and the size of /tmp, and it lands on the statusline path this PR is meant to help. A per-process Once keeps the reclaim and cuts this to one sweep per wt invocation. Orphans can only come from other processes, so sweeping more often within a single process doesn't reclaim anything extra.

Comment thread src/git/repository/working_tree.rs Resolved
temp_index() runs once per worktree during wt list, mostly in parallel,
and each call re-read the whole temp directory. Orphans only come from
other processes, so the first caller sweeps and the rest skip it without
waiting. Collapse the sweep's logging and cover process_is_alive and the
failed-remove path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
worktrunk-bot
worktrunk-bot previously approved these changes Oct 14, 2026
process_is_alive's test is Unix-only, so importing it at module scope
left an unused import on Windows. Log a NotFound remove like any other
error, and fold the root check into the assertion, so no line is left
that tests never reach.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@worktrunk-bot
worktrunk-bot dismissed their stale review October 14, 2026 13:46

CI failed on d0c8f41 — test (windows): unused import process_is_alive (the author's 60feb4f addresses it; the next review covers that head).

@max-sixty

Copy link
Copy Markdown
Owner

@jonah-osmo thanks!

@worktrunk-bot please explain the impact of this? where are temp indexes accruing / how would that be happening? something needs to be killing wt processes? this change deletes them after a wt process created them a day ago?

remind me: are the indexes always specific to a single wt process? why doesn't it use a temp / xdg path that is recoverable?

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Short version: every wt list / wt list statusline run copies .git/index into the system temp dir once per worktree it probes. If the process is killed before it finishes, that copy stays behind. Claude Code kills slow statusline scripts as a matter of course, so on a busy machine the copies pile up. The PR deletes a copy on the next wt run, as soon as the PID in its name is dead. The one-day rule is only a fallback for reused PIDs.

Where they accrue. WorkingTree::temp_index() writes $TMPDIR/worktrunk-temp-index-* (falling back to <gitdir>/ when the system temp dir isn't writable). Each file is a byte-for-byte copy of the worktree's index. wt list and the statusline call it in their conflict probes, once per worktree (tasks.rs), and a second time for diff stats when untracked files exist. wt step diff, step commit/squash, and the picker preview also call it. The reporter's numbers fit this: 127 GB over 52,786 files is about 2.4 MB per file, against a 2.6 MB index.

What kills wt. Only TempIndex::drop removes the file, and destructors don't run under SIGKILL. Claude Code's statusline docs say: "If a new update triggers while your script is still running, Claude Code cancels the in-flight script." The docs don't name the signal. The PR author reports it as SIGKILL; I haven't confirmed that. Either way, a statusline render that's slower than the update rate gets cancelled over and over. With ~25 sessions, each probing several worktrees, every cancellation can leave several index copies behind. OOM kills and closing the terminal leave files the same way, only less often.

Does it delete files a wt process made a day ago? Not as the main rule. A file is deleted when either:

  • the PID in its name (worktrunk-temp-index-<pid>-<random>) no longer exists. This is the normal case, and it happens on the next wt run that creates a temp index, however old the file is.
  • the file is older than 24 h (STALE_TEMP_INDEX_MAX_AGE), even if its PID is alive. This covers a PID that was reused by an unrelated process, which would otherwise keep the file forever. No wt command holds a temp index for more than one git probe, so a live owner never gets close to that age.

Are they per-process? They're narrower than that: each one lasts for a single operation, and one wt list creates many of them, in parallel. Today's names don't record the creating process. The PR adds the PID so the sweep can tell which files are orphans. The sweep only looks at names that match that pattern, and it runs once per process (AtomicBool guard).

Why the system temp dir rather than an XDG/worktrunk-owned path? That choice came from #3906. Probe storage goes to system temp first so wt list works in read-only checkouts and writes nothing into the repo, with .git as the fallback. Moving the files wouldn't fix this leak, because a SIGKILL leaves the file wherever it is. A dedicated directory (e.g. under $XDG_CACHE_HOME/worktrunk/ or <git-common-dir>/wt/) would make cleanup simpler: the sweep could clear stale entries from a directory only worktrunk writes to, instead of scanning a shared /tmp, and the files would show up next to worktrunk's other state. The cost is that it needs its own read-only fallback and loses the OS's /tmp reaping (on systems that do it, e.g. systemd-tmpfiles' age cleanup, or a reboot). The PID-tagged sweep in this PR works the same in either location.

Two related gaps, from reading the code:

  • redirect_objects_for_observation creates $TMPDIR/worktrunk-list-objects-* directories (mod.rs) that leak the same way under a kill, and this PR doesn't sweep them. They only hold the probe's objects, so they're probably much smaller than index copies, but they also grow without bound.
  • The FAQ's "Temporary files" section still says "an interrupted process can leave one behind for manual cleanup". With this PR, that becomes true only for the object directories and for Windows, where the sweep falls back to the 24 h age check.

@max-sixty

Copy link
Copy Markdown
Owner
  • can we put these somewhere where the os will clean them up?
  • even if not: can we simplify all this pid etc? no wt process is likely to be alive for long — maybe an alias or hook — but is there anything that could create a temp index that could be? can we just remove anything that's old, no need to look at the pid etc?
  • at what cadence does this run atm? on which thread? how does the proposed code manage this?

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Short answers: (1) They're already in the OS temp dir, but the OS clears it far too slowly for this leak, and git needs a real path, so there's no "delete when the process dies" option. (2) Yes, age-only works. The one thing to get right is the threshold: it trades simplicity against how many orphans pile up. (3) It sweeps once per wt process, synchronously, on whichever thread first creates a temp index.

1. OS cleanup. temp_index() already writes to std::env::temp_dir() ($TMPDIR, otherwise /tmp). OS reaping works on a scale of days. For example, this Ubuntu 24.04 runner's /usr/lib/tmpfiles.d/tmp.conf has D /tmp 1777 root root 30d, which means boot-time clearing plus a 30-day age limit. The report reached 127 GB in three days, so OS cleanup alone doesn't contain it. The kind of file the kernel removes when its owner dies (an unlinked or O_TMPFILE file, or delete-on-close on Windows) doesn't work here either. Git needs GIT_INDEX_FILE to be a named path, because it writes the index by creating a <path>.lock sibling and renaming it over the original.

2. Age-only. No current holder lives long:

  • wt list and statusline probes, plus the picker preview, hold one for milliseconds to seconds.
  • wt step commit --dry-run and wt step squash --dry-run hold one across the LLM call (commit.rs, squash.rs). That's seconds to minutes.
  • wt step diff keeps the file alive for as long as the user sits in git's pager (diff.rs). Git loads the index before it starts paging, though, so deleting it at that point should be harmless.

Hooks and aliases run as child processes and never receive a temp index, so a long-running hook doesn't matter here.

The real hazard with age-only is deleting the file while a git command is about to read it. That fails silently instead of with an error: git treats a missing GIT_INDEX_FILE as an empty index. I checked this. GIT_INDEX_FILE=<missing> git write-tree returns the empty tree 4b825dc…, and git diff --cached shows every file as deleted. So the threshold needs to sit well above the longest hold, and even a short one like 10–60 minutes clears that.

What the PID check buys is a shorter steady state. Under age-only, orphans build up to roughly threshold × leak rate. The report's rate (127 GB over three days) works out to about 1.8 GB per hour, so a 1-hour threshold would leave about 1.8 GB on that machine and the PR's current 24 h about 42 GB. The PID check reclaims an orphan on the next run instead. Without it, the change drops temp_index_prefix_for, temp_index_owner_pid, both process_is_alive variants, and the PID in the file name. The sweep becomes "prefix matches and mtime is older than N". I'd take that simplification with a short threshold (~1 h), unless the remaining GB on heavy machines matters to you.

3. Cadence. The sweep runs inside temp_index(), guarded by a process-wide AtomicBool (working_tree.rs#L1161-L1164):

  • Which commands: only those that create a temp index: wt list / statusline when they run the conflict or diff probes, wt step diff, step commit / squash --dry-run, and the picker preview. Other commands never sweep.
  • Which thread: in wt list, the first parallel worker to reach temp_index() sweeps synchronously before creating its own file. The other workers see the flag already set and continue without waiting. That one probe takes the hit.
  • Cost: one read_dir of the temp dir, comparing names by prefix, then a stat, a kill(pid, 0), and possibly an unlink for each worktrunk-named file. Once orphans are cleared, that's a single directory listing per process. The exception is the first run on a machine like the reporter's: it has to unlink tens of thousands of files inside a statusline render, which may itself get killed. It still makes progress each time, because every unlink sticks.
  • Fallback path: when the system temp dir isn't writable, the <gitdir> fallback sweeps <gitdir> on every such call (L1168). That path isn't behind the AtomicBool. The directory is small, so it's cheap, but it isn't once per process.

@max-sixty

Copy link
Copy Markdown
Owner

one more idea: why are we producing so many & large temp index files? I thought these were really small? is there anything we can do there?

would much rather rely on OS cleanups than managing it ourselves, if possible

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Short version: each copy is the whole index, and an index holds about 100 bytes for every tracked file. It's small in a small repo; the reporter's 2.6 MB index means roughly 25k tracked files. We can cut how often copies are made, and on the statusline path we can stop making them, which is the lever that would let OS cleanup be enough. Making each copy smaller isn't practical.

Why each copy is large. Git has no partial index. write-tree and diff read the full one, so a copy has to be the full one too. I measured a 2,000-file repo at 207 KB, about 103 B per entry (stat data, OID, and path). We copy rather than use the real index because git write-tree on the real index takes index.lock. With a lock present it fails with fatal: Unable to create '.git/index.lock': File exists (checked on git 2.55). That would fight with the user's own git and with agents running git in the same worktree.

Why there are so many. The statusline renders one worktree but runs every wt list task (statusline_options). A worktree with changes gets up to two copies per render:

  • the working-tree conflict probe, when tracked files changed (tasks.rs#L609): copy, add -u, write-tree, then merge-tree
  • the diff stats, when untracked files exist (tasks.rs#L491): untracked paths are added to the copy as intent-to-add, so renames pair up

A worktree an agent is editing nearly always meets both conditions. A copy leaks only if the render is killed partway. Claude Code debounces updates at 300 ms and cancels an in-flight script when a new update fires. So while an agent is streaming, any render slower than the update rate gets cancelled again and again, and each cancellation can leave ~5 MB behind. Across ~25 sessions that adds up to the reported 52k files.

What we could do, roughly in order of effect:

  1. Drop the working-tree conflict probe from the statusline. It does the most git work in the render (it re-hashes modified files, writes a tree, and runs a merge), so dropping it should make renders faster and less likely to be cancelled. It also removes one copy per render. The statusline would fall back to the commit-based conflict check that clean worktrees already use. The cost is that uncommitted edits that would conflict no longer show in the statusline; wt list still shows them.
  2. Count untracked lines without a temp index on the statusline, giving up rename pairing there. This removes the other copy. It changes the numbers for a moved file that hasn't been staged (shown as +N/−N rather than as a rename).
  3. Share one copy between the two tasks, which halves the copies. It couples two parallel tasks, so it's the least appealing.

With 1 and 2, the statusline creates no temp index at all, so there's nothing on that path for a cancellation to leave behind. The remaining leaks would come from a killed wt list, wt step diff, or the picker, which are interactive and rarely SIGKILLed. At that rate, the OS's /tmp cleanup (reboot, or tmpfiles age-out) would be enough, and this PR's sweep could be dropped or cut down to the age-only version.

I haven't measured where the reporter's render time goes. A wt -vv list statusline profile from their machine would confirm whether the conflict probe is what pushes renders past the cancellation window. If 1 and 2 sound right, I can open a PR for them.

Dead ends checked
  • Hardlinking instead of copying. Git writes an index through <path>.lock plus a rename, so a hardlinked copy would be safe. But the link has to be on the same filesystem as .git, which puts the files back in the repo, where the OS never cleans them up.
  • Delete-on-exit files (O_TMPFILE, /proc/self/fd/N). Git needs a path where it can create a .lock sibling. write-tree and add -u both write the index back that way.
  • Split index. The shared half lives in .git and has its own expiry. It's a lot of machinery for a probe.

@max-sixty max-sixty changed the title Reclaim temp indexes orphaned by a killed process Reclaim stale temporary indexes with age-based cleanup Oct 22, 2026
@max-sixty
max-sixty merged commit 90da247 into max-sixty:main Oct 23, 2026
38 of 39 checks passed
max-sixty added a commit to max-sixty/tend that referenced this pull request Nov 21, 2026
Tend's review approved any PR with no defect. Submit said "If there are
no issues, approve with an empty body — silence means correct", and a
`code-review` finding needs a file, line and failure scenario, so a
correct change that wasn't worth its cost got an `APPROVE` unless
another check, such as the duplication check, turned its cost into a
finding. A repository overlay asking for a `COMMENT` on such changes
didn't override that default: worktrunk's reviews opened its
proportionality rule and approved anyway (max-sixty/worktrunk#4664,
max-sixty/worktrunk#4665, max-sixty/worktrunk#4666,
max-sixty/worktrunk#4670, max-sixty/worktrunk#4689,
max-sixty/worktrunk#4694).

Submit now says an `APPROVE` tells the maintainer the whole PR is worth
merging. Before one, including after a trivial increment, the session
says who loses what if the PR never merges and how they come to need it,
what it adds that later changes must keep working, and the cheapest
other way to get the benefit. It approves when the benefit pays for what
the PR adds and nothing materially cheaper exists; otherwise it posts a
`COMMENT` naming the cost or the cheaper way. On a self-authored PR,
where the review stays silent instead of approving, the same weighing
runs before that silence, so a correct bot PR that isn't worth merging
is raised as a concern, which Review's "carry its weight" bullet used to
ask for. That bullet goes, since Submit now owns the judgment. A
`COMMENT` that holds the verdict names its reason once, as a
merge-readiness hold already did, so a later push doesn't restate it,
and a re-targeted review that empties takes its verdict from Submit
instead of approving.

## Evidence

Eleven trajectory cases (`evals/cases/review-worth-*`) replay real
worktrunk PRs at their reviewed heads. On 20 Nov, with main (including
#1646 and #1712) merged in, this PR's review skill ran against main's,
three attempts per case per arm. On the four PRs that independent
reviewers judged not worth merging as written (max-sixty/worktrunk#4664,
max-sixty/worktrunk#4665, max-sixty/worktrunk#4666,
max-sixty/worktrunk#4694), these attempts held the verdict and named the
cost or a cheaper route:

| Executor | main | This PR |
| --- | --- | --- |
| Codex gpt-6.1-sol | 6 of 10 (2 attempts failed on model capacity) | 10
of 12 |
| Claude Opus 5.5 | 2 of 12 | 7 of 12 |

- Main's six Codex holds are on max-sixty/worktrunk#4666 and
max-sixty/worktrunk#4694, which the old text approved in all three
attempts on the 5 Nov base. Each review of max-sixty/worktrunk#4666
names the second cache as a copy of the existing cached `git remote
get-url` lookup, the kind of copy #1646 widened the duplication check to
flag; the reviews of max-sixty/worktrunk#4694 name the hand-written URL
parsing as more than the IPv6 fix needs. This PR also holds
max-sixty/worktrunk#4665 and max-sixty/worktrunk#4664 (2 of 3 each),
which main's text approved in every attempt that completed.
- On the PRs that should be approved (max-sixty/worktrunk#4334,
max-sixty/worktrunk#4469, max-sixty/worktrunk#4668,
max-sixty/worktrunk#4669, max-sixty/worktrunk#4680), Codex approved in
all 15 attempts on each arm. Claude, run on this PR's text only, held
max-sixty/worktrunk#4668 in 3 of 3, citing a `git rev-parse` per noted
directory on every pane refresh and a narrower fix, and held
max-sixty/worktrunk#4669 (2 of 3) and max-sixty/worktrunk#4680 (1 of 3)
over defects.
- On the 5 Nov base, not re-run: a standing hold that should survive a
test-only push stayed silent 6/6, a hold on a per-render cost stayed
held 6/6, and `review-landing-continuation` passed 3/3 on Codex.

## Costs

A trivial follow-up push now gets a whole-PR read.

> _This was written by Claude Code on behalf of max-sixty_
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.

4 participants