Skip to content

feat(codex): prune expired Codex runtime session logs (#16776) - #16990

Closed
maxmilian wants to merge 2 commits into
stablyai:mainfrom
maxmilian:fix/16776-prune-codex-rollout-sessions
Closed

maxmilian wants to merge 2 commits into
stablyai:mainfrom
maxmilian:fix/16776-prune-codex-rollout-sessions

Conversation

@maxmilian

Copy link
Copy Markdown
Contributor

ELI5

Orca keeps a copy of every Codex conversation it has ever run, and never throws any of them away. The reporter's folder had grown to 11 GB and 1,000+ files going back to September 2025. This adds a quiet sweep at startup that deletes the ones older than 90 days — while always keeping the 50 most recent, no matter how old they are.

What Changed

  • New src/main/codex/codex-session-log-retention.ts: walks the managed Codex home's sessions/ tree, removes rollout-*.jsonl files whose mtime is older than the cutoff, then removes the date directories that became empty. The sessions root itself is never removed.
  • src/main/index.ts: three lines, kicking the sweep off in the background inside app.whenReady(), right after the existing Codex backfill recovery.

No UI, no new setting. Two environment overrides exist for escape hatches (below).

Why

Fixes #16776.

There is currently no retention of any kind for these logs — I checked before writing anything. observability/local-file-sink.ts has rotation, but only for observability logs; ai-vault/session-delete.ts deletes a single session on user action. Nothing is age- or size-based, so the directory only ever grows.

Two deliberately conservative choices, because this deletes user data:

  1. 90 days, not the 7 the issue's workaround uses. Orca surfaces these sessions in AI Vault and can resume them, so they aren't pure garbage. A quarter still covers the window in which people realistically go back to a session, while turning "unbounded" into a bounded fraction of the app's lifetime.
  2. The 50 most recent rollouts are always kept, regardless of age. This is the guard that matters: without it, someone who hasn't opened Orca in four months would launch it and watch their entire history disappear. With it, the sweep can only remove history the user already has newer replacements for.

Escape hatch: ORCA_CODEX_SESSION_LOG_RETENTION_DAYS (0 disables the sweep entirely; a non-positive or unparseable value falls back to the default). This follows the existing ORCA_USER_DATA_PATH env-override convention rather than introducing the first "number of days" global setting and the UI that would come with it.

The sweep never throws. Unreadable or undeletable entries are counted into a failures tally and the rest are still reclaimed, so a permissions problem in one directory can't take startup down with it.

Linked Issue

Fixes #16776

Visual Proof

N/A — this is a background filesystem sweep with no UI surface and no user-visible interaction change. The only observable effect is that an old rollout-*.jsonl is gone from disk.

Testing

src/main/codex/codex-session-log-retention.test.ts, 11 cases: expired files removed while recent ones stay; the min-retained guard holds old files when there are fewer than 50; non-rollout files are never touched; emptied date directories are reclaimed but the sessions root is not; a directory that still holds a retained file is left alone; a missing root returns a zero summary instead of throwing; and four cases covering environment-variable parsing (unset, 0, garbage, valid).

Symlinked entries are skipped — only entry.isFile() qualifies — so a rollout linked in from elsewhere can't be deleted through this path.

  • pnpm lint — clean
  • pnpm typecheck — clean
  • pnpm test — the new file: 11 passed. Full suite: 6,857 passed / 43 skipped, with 6 failures in relay/git-handler-fork-remote-exec and ssh/ssh-connection-host-key-store-wiring. Those 6 fail identically on a clean origin/main on this machine (I re-ran them against a stashed tree to check), so they're pre-existing and unrelated.
  • pnpm run build:desktop — clean. pnpm build fails on this machine at build:native macOS codesign (errSecInternalComponent), which also fails on clean origin/main — a local keychain problem, not something this change introduces.

Platform: developed and tested on macOS. The implementation is fs/path.join only with no platform-specific branches, so Linux and Windows behaviour follows from the same code path; I have not run it on either.

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

AI Disclosure

Written with Claude (Claude Code, Opus). Every claim in this description was verified against the repository rather than assumed: the "no existing retention" statement comes from reading local-file-sink.ts and ai-vault/session-delete.ts, and the pre-existing test failures were confirmed by re-running them on a clean tree.

Review

Agent skill upstream boundary

  • Not applicable — this change touches no skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Security — deletion is confined to the Orca-managed Codex home resolved by resolveOrcaManagedCodexHomePath(); the user's real ~/.codex is never walked. Only names matching ^rollout-.*\.jsonl$ are eligible, symlinks are excluded, and the sessions root is never removed.
  • Cross-platform — path.join throughout, no shell invocation, no platform branches.
  • Remote SSH — the sweep runs against the local managed home in the main process only; remote worktrees and remote sessions are untouched.
  • Backwards compatibility — no schema, config, or IPC surface changes. Setting ORCA_CODEX_SESSION_LOG_RETENTION_DAYS=0 restores exactly the current behaviour.
  • Performance — one directory walk in the background after ready, off the critical path; failures don't propagate.

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) — see Testing for the two documented, pre-existing exceptions

Reported by @dev4java.

@coderabbitai

coderabbitai Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
Walkthrough

The change adds Codex session-log retention with a 90-day default and a 50-rollout minimum. A valid environment setting can change the retention period or disable pruning. The sweep scans rollout files, checks modification times before removal, reports filesystem results, and removes empty descendant directories. When given a published sessions root, it checks for the corresponding published file before removing a rollout. Startup now launches the sweep and supplies that root when system-default session migration is eligible. Tests cover pruning, concurrent modification, and migration.

Severity of issue fixed: Medium

Merge Risk: Moderate · previous review e33ec

The sweep can permanently delete old Codex session logs that have not yet been copied to the host Codex home, or whose copy differs from the managed file. Those logs were the only copy of that history. Fix the ineligible-migration case and the published-file identity check before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: a feature that prunes expired Codex runtime session logs. It matches the retention sweep in the changeset and includes the issue reference. It is 62 characters, which …
Description check Passed The description follows the repository template. It includes ELI5, What Changed, Why, Linked Issue (Fixes #16776), Visual Proof (N/A with reason), Testing with checklist items, Risk discussion in Note…
Linked Issues check Passed Directly linked issue #16776 asks for an automatic cleanup policy based on age or count, or a total-size cap. The first listed expected behavior is an automatic cleanup policy. The PR implements an ag…
Out of Scope Changes check Passed All changed areas connect to the retention objective. The new retention module implements the sweep and its environment override. The tests cover that module. The main-process-account-services.ts chan…
Full details: Title check

Explanation

The title names the main change: a feature that prunes expired Codex runtime session logs. It matches the retention sweep in the changeset and includes the issue reference. It is 62 characters, which fits the short single-sentence expectation.

Full details: Description check

Explanation

The description follows the repository template. It includes ELI5, What Changed, Why, Linked Issue (Fixes #16776), Visual Proof (N/A with reason), Testing with checklist items, Risk discussion in Notes, AI Disclosure, the upstream boundary checkbox, and the checklist. The Risk section has no explicit Level value and no dedicated back-out instructions. The Testing section lists the test file path as src/main/codex/codex-session-log-retention.test.ts, but the raw summary places the tests under src/main/codex/history/rollouts/. The description also does not mention the migration guard or the active-race and migration test files that the objectives describe. These gaps are minor, so the check passes.

Full details: Linked Issues check

Explanation

Directly linked issue #16776 asks for an automatic cleanup policy based on age or count, or a total-size cap. The first listed expected behavior is an automatic cleanup policy. The PR implements an age-based policy in src/main/codex/history/rollouts/codex-session-log-retention.ts: rollout-*.jsonl files older than 90 days are removed, and the 50 most recent rollouts are always kept. Empty date directories are removed, and the sessions root is kept. The sweep runs at startup through src/main/startup/main-process-account-services.ts. The reported test suite (17 retention tests) covers expiry, the minimum-retained guard, non-rollout files, empty-directory cleanup, invalid roots, unreadable directories, and the environment override. The issue's "at minimum, an in-app Clear session history option" is not implemented. The issue wording makes that option a fallback, not a required item, because automatic cleanup is listed as the primary expectation. The PR description is partly stale: it names src/main/index.ts and the old file path, while the current wiring is in main-process-account-services.ts and the files were moved to history/rollouts/. These are documentation issues and do not change the coding verdict. Remaining limits: the reviewed evidence is the PR summary and the author's reported test results. I did not run the tests. The check-then-unlink race is documented by the author as a residual window.

Full details: Out of Scope Changes check

Explanation

All changed areas connect to the retention objective. The new retention module implements the sweep and its environment override. The tests cover that module. The main-process-account-services.ts change starts the sweep and passes the migration source root when migration is eligible. The migration guard keeps a managed rollout until its published copy exists, so the sweep does not delete the only copy before migration publishes it. The migration integration test covers this behavior. The active-race test checks the modification-time recheck before unlink. The change adds no UI, no settings, and no IPC surface, which matches the stated scope. No unrelated changes were identified in the summary.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@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: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1528812f-bada-405b-a966-b245ba1c47c2

📥 Commits

Reviewing files that changed from the base of the PR and between c4b3929 and ef6049c9e776f606a5f6fd93bb433c865e6f9a4b.

📒 Files selected for processing (3)
  • src/main/codex/codex-session-log-retention.test.ts
  • src/main/codex/codex-session-log-retention.ts
  • src/main/index.ts

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

Comment thread src/main/index.ts Resolved

@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

♻️ Duplicate comments (1)
src/main/codex/codex-session-log-retention.ts (1)

128-163: 🔒 Security & Privacy | 🟠 Major

Path Traversal (CWE-59)

Reachability: External · Exploitability: Difficult

Prevent symlink replacement during recursive traversal.

Line 147 checks a Dirent, but Line 148 reopens entryPath by name. Another process can replace that directory with a symlink before the recursive readdir(). The traversal can then follow the target, and the later unlink() or empty-directory removal can affect paths outside sessionsRoot. Use no-follow directory handles or an equivalent traversal that rejects replacement symlinks. This repeats the unresolved path from the previous review.

Also applies to: 165-194


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c86f826d-f82e-49f2-b4a0-3bc0fe1ebc07

📥 Commits

Reviewing files that changed from the base of the PR and between ef6049c9e776f606a5f6fd93bb433c865e6f9a4b and 0a87000b1ef7436c897796ebc091aff64a0e1ef2.

📒 Files selected for processing (2)
  • src/main/codex/codex-session-log-retention.test.ts
  • src/main/codex/codex-session-log-retention.ts

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

@maxmilian

Copy link
Copy Markdown
Contributor Author

Status update — all CodeRabbit findings on this PR are now resolved.

  • symlink TOCTOU and whenReady unhandled rejection — withdrawn by the reviewer after I explained the existing behaviour.
  • unreadable directory counted as absent — fixed in 0a87000.
  • ENOTDIR counted as absent — fixed in 467e4c4 (latest head). isDirectoryAbsence() now recognises only ENOENT, so a sessions root that exists but is not a directory is reported as a failure instead of a clean no-op sweep. Details in the thread.

Local verification on the current head: 13 passed in src/main/codex/codex-session-log-retention.test.ts, plus oxfmt --check, oxlint and typecheck:node clean.

One thing I can't do from my side: PR Checks and PR test LoC have been sitting at action_required for this branch, so no CI has actually run on any head of this PR yet. Whenever a maintainer has a moment to approve the workflow run, that would give the change real coverage beyond my local run.

@greptile-apps

greptile-apps Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR adds startup retention for managed Codex rollout logs, preserving the newest 50 and removing expired files and empty date directories.

  • Adds configurable 90-day retention with an environment-variable opt-out.
  • Starts the sweep asynchronously from the Electron main-process startup path.
  • Adds filesystem, configuration, and concurrent-resume tests.

Confidence Score: 4/5

The PR is not yet safe to merge because an active Codex rollout can still be deleted during the remaining stat-to-unlink race.

The reply states “Fixed in 4b9c7178,” but an append after the new stat returns is a concrete residual counterexample: the unchanged comparison has already passed, and the subsequent unlink removes the active session pathname.

Files Needing Attention: src/main/codex/codex-session-log-retention.ts and src/main/codex/codex-session-log-retention-active-race.test.ts

Important Files Changed

Filename Overview
src/main/codex/codex-session-log-retention.ts Implements retention and a freshness recheck, but the separate stat and unlink leave the previously reported active-session deletion race reachable.
src/main/codex/codex-session-log-retention-active-race.test.ts Covers modification during the second stat but not the remaining interval after stat returns and before unlink.
src/main/codex/codex-session-log-retention.test.ts Thoroughly covers age retention, minimum preservation, directory cleanup, failures, and environment parsing.
src/main/index.ts Starts the retention sweep asynchronously during managed Codex runtime initialization.

Sequence Diagram

sequenceDiagram
  participant Sweep as Retention sweep
  participant FS as Filesystem
  participant Codex as Codex process
  Sweep->>FS: stat(expired rollout)
  FS-->>Sweep: unchanged mtime
  Codex->>FS: append to rollout
  Sweep->>FS: unlink(rollout path)
  Note over Codex,FS: Active conversation continues on an unlinked file
  Note over FS: Path is absent from discovery and resume scans
Loading

Reviews (3): Last reviewed commit: "test(codex): pin single-counting of an u..." | Re-trigger Greptile

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/codex/codex-session-log-retention.ts (1)

181-183: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Record directory-read failures.

At Line 181, removeEmptyDirectories discards readdir errors and returns false without updating summary.failures. An unreadable date directory after rollout deletion makes the cleanup partial while the returned tally can report no failure. Count non-ENOENT errors here, as collectRollouts does.

Proposed fix
-  } catch {
+  } catch (error) {
+    if (!isDirectoryAbsence(error)) {
+      summary.failures += 1
+    }
     return false
   }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f3b24882-3379-4ed5-90bb-cc2ab53924af

📥 Commits

Reviewing files that changed from the base of the PR and between 467e4c4c134fb9fbb30600fed8e35ec321e4603c and 4b9c7178757e3550ac9323a2fccb03d6881ecf9c.

📒 Files selected for processing (2)
  • src/main/codex/codex-session-log-retention-active-race.test.ts
  • src/main/codex/codex-session-log-retention.ts

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

@maxmilian

Copy link
Copy Markdown
Contributor Author

Checked this one rather than taking it — the tally is already correct, and the proposed fix makes it wrong.

collectRollouts and removeEmptyDirectories both walk the tree, so an unreadable directory is reachable twice in a single sweep. Counting the readdir failure in the second place as well reports two failures for one directory.

Measured, with an expired rollout present so the cleanup phase actually runs (the existing counts an unreadable directory as a failure test doesn't reach it — its rollout is 8 days old, so removedRollouts is 0 and removeEmptyDirectories is never called):

summary.failures
current head of this branch 1
with the proposed diff 2

The gap you're pointing at is real but narrower than described: it needs the directory to become unreadable between the scan and the cleanup, since otherwise collectRollouts has already counted it. Closing that would need dedup by path, and double-counting the common case to catch a mid-sweep permission change isn't a trade I'd make here.

e7c84f630 pins the current behaviour instead: counts an unreadable directory once even when the sweep also removes directories. I verified it isn't vacuous — applying your diff turns it red with expected 2 to be 1.

Comment on lines +93 to +97
const current = await stat(rollout.path)
if (current.mtimeMs !== rollout.mtimeMs) {
continue
}
await unlink(rollout.path)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Active rollout race remains

If Codex appends to an expired rollout after the second stat resolves but before unlink executes, the unchanged-mtime check has already passed and the sweep deletes the active pathname, causing the conversation to disappear from discovery and resume while subsequent writes continue to an unlinked inode.

Knowledge Base Used:

@maxmilian

Copy link
Copy Markdown
Contributor Author

You're right about the window, and right about the test — but I don't think the endpoint you're asking for exists, so I'd rather make the case than ship another round that appears to close it.

Where you're correct. codex-session-log-retention.ts does stat → compare mtime → unlink as three separate steps, and an append landing after the stat returns but before the unlink executes is not caught. Your reading of the test is also right: codex-session-log-retention-active-race.test.ts seams inside the second stat call, so it covers scan → stat and nothing after it. My earlier "Fixed in 4b9c7178" claimed more than the change delivered — that commit narrowed the window from scan → unlink down to stat → unlink; it did not remove it.

Why the remaining window can't be closed here. Suppose the ideal primitive existed — an atomic unlink-if-mtime-unchanged. It still wouldn't help, because open(O_APPEND) does not update mtime; only the write does. So Codex can open the file, our atomic check passes against an unchanged mtime, the file is unlinked, and only then does Codex write — into an unlinked inode, exactly the outcome you're describing. Verified rather than assumed:

mtime unchanged by open(O_APPEND): True
mtime changed by write:            True

The window is a property of deleting by path while another process may hold a descriptor, not a defect in this function. Closing it requires the deleter to know which sessions are live, which means cross-process coordination — an active-session registry or lockfile owned by the Codex runtime. That's an architectural change, and a retention sweep is the wrong place to introduce it.

The partial mitigation I considered and rejected, for completeness: rename to a tombstone, re-stat the tombstone, rename back if it moved, unlink only if it didn't. That converts one half of the failure — a resume that opens the path after we commit to deleting — into a clean ENOENT instead of a write into a detached inode. It does nothing for the half where Codex already holds the descriptor. For that partial gain it adds a rename-and-rollback path to a sweep that runs once per desktop start, guarding a case that needs a rollout to be simultaneously older than 90 days, outside the newest 50, and resumed inside a sub-millisecond window. I don't think that trade is worth it, but if you'd rather have it than the current two-step, say so and I'll add it.

What I'd suggest instead: leave the two existing bounds (retentionDays=90, minRetainedRollouts=50) as the real protection, and document the residual window in the function so the next reader doesn't re-derive this. Happy to add that comment.

Separately, this PR still has zero CI coverage — PR Checks and PR test LoC are both action_required, waiting on the fork workflow approval I mentioned in an earlier comment. Whatever we land here, it'd be good to get a run on it.

@maxmilian
maxmilian force-pushed the fix/16776-prune-codex-rollout-sessions branch from e7c84f6 to 464dfde Compare September 4, 2026 03:58
@maxmilian
maxmilian force-pushed the fix/16776-prune-codex-rollout-sessions branch from 464dfde to 8a57adf Compare October 12, 2026 12:24
@maxmilian

Copy link
Copy Markdown
Contributor Author

Rebased onto current main. The only conflict was the startup wiring in main-process-account-services.ts, which I re-applied next to startCodexStateDbBackfillRecoveryInBackground.

The new session migration (createCodexSessionMigrationScheduler) interacts with this sweep, so I added one fix. The sweep runs at startup, while the migration waits for its initial delay before hardlinking managed-home rollouts into the real Codex home. On a host where the migration is eligible, an expired managed rollout the migration hadn't published yet could be deleted first, and that was its only copy. The sweep now takes an optional publishedSessionsRoot. When the migration is eligible, it only removes a managed rollout once the same relative path exists under the real home's sessions root. Non-eligible hosts behave exactly as before. codex-session-log-retention-migration.test.ts drives the real backfill for both orders: sweep-before-migration keeps the file, and the next sweep after publishing reclaims the managed name while the published copy stays intact.

@maxmilian
maxmilian force-pushed the fix/16776-prune-codex-rollout-sessions branch from 8a57adf to 67870d0 Compare October 19, 2026 07:03
@maxmilian

Copy link
Copy Markdown
Contributor Author

Rebased onto current main. The only conflict was again the startup wiring: #29209 moved account-service construction into createProviderAccountServices, so the retention sweep now starts right after startCodexStateDbBackfillRecoveryInBackground, once state.codexRuntimeHome comes from the shared services. I also replaced the as NodeJS.ErrnoException cast in the retention errno check with in-guard narrowing (same pattern as wsl-distro-holder-record.ts), since the changed-code casting gate now flags it. No behavior change otherwise.

@maxmilian
maxmilian force-pushed the fix/16776-prune-codex-rollout-sessions branch from 67870d0 to a505855 Compare October 26, 2026 15:15
@AmethystLiang

Copy link
Copy Markdown
Contributor

I'm trying to land it

@maxmilian

Copy link
Copy Markdown
Contributor Author

Thanks for picking this up. It has gone conflicting again since the Codex modules moved under src/main/codex/history/ (#38023).

I have a rebase onto 83f8e6340d ready locally. The sweep and its three test files move to src/main/codex/history/rollouts/, and the only code changes are import paths. The startup wiring still sits right after startCodexStateDbBackfillRecoveryInBackground, and pnpm run check:changed passes. It squashes the review-round commits into one, because the paths changed under all of them.

I haven't pushed it, in case you already have the branch checked out locally. Should I push it, or would you rather do the rebase yourself while landing it?

The runtime home's `sessions/` tree kept every `rollout-*.jsonl` forever —
no TTL, no size cap, no in-app way to reclaim the space. One report hit
11 GB across 1,000+ files spanning almost a year.

Adds a startup sweep that removes rollout logs older than 90 days, plus
the date directories they leave empty. Guards keep it from being a
data-loss hazard: the newest 50 rollouts survive regardless of age, only
regular files matching `rollout-*.jsonl` are touched (symlinks are left
alone), a rollout touched after the scan is skipped, and when the
host-system-default session migration is eligible only rollouts already
published to the system home are removed.
`ORCA_CODEX_SESSION_LOG_RETENTION_DAYS` tunes the window; `0` opts out.

The sweep never throws: unreadable or undeletable entries are counted in
the summary and the rest of the reclaim still happens.
@maxmilian
maxmilian force-pushed the fix/16776-prune-codex-rollout-sessions branch from a505855 to e33ec81 Compare November 11, 2026 02:17
@maxmilian

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (ec95c931f0). It had gone conflicting because #38023 moved the Codex modules under src/main/codex/history/, and the startup wiring in main-process-account-services.ts picked up unrelated import-path changes from #39969/#39996.

The sweep and its three test files now live in src/main/codex/history/rollouts/. Compared with the previous head, the only changes are import paths. The wiring still runs right after startCodexStateDbBackfillRecoveryInBackground, with the same migration-published guard. The review-round commits are squashed into one, because the paths changed under all of them.

pnpm run check:changed passes (25/25, including typecheck), and so do the 17 retention tests. Each of these mutations turns them red: making unlink a no-op, dropping the migration guard, and dropping the post-scan mtime recheck.

@AmethystLiang, if you already have a local rebase in progress, feel free to keep yours. I'm happy to drop this push.

@AmethystLiang

Copy link
Copy Markdown
Contributor

@maxmilian thanks a lot! will take it over

@AmethystLiang

Copy link
Copy Markdown
Contributor

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor
Action performed

Full review finished.

@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: 2

Additional comments: 2

src/main/codex/history/rollouts/codex-session-log-retention.ts-66-66: 1

66-66: Major · Data Integrity & Integration · Quick win

Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.

Reject a symlinked sessionsRoot before pruning.

If sessionsRoot is a symlink to the real Codex sessions directory, collectRollouts reads that target. The later unlink calls can then remove real Codex history. The Dirent checks protect entries inside the root, not the root itself. Check the root with lstat before the sweep; treat a symlink as a failure. (raw.githubusercontent.com)

src/main/codex/history/rollouts/codex-session-log-retention.ts-150-150: 1

150-150: Major · Stability & Availability · Quick win

Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.

Append child rollouts without spreading the array.

When a subtree contains enough rollouts, spreading its result into push exceeds the JavaScript argument limit. The sweep then rejects instead of pruning the large history it is meant to handle. Append entries in a loop, as the existing session-file listing code does for large histories. (raw.githubusercontent.com)

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 753a1a3e-c41b-409e-8044-df534d243077
Commits

Reviewing files that changed from the base of the PR and between f78d5a6 and e33ec81.

Files selected for processing: 5

  • src/main/codex/history/rollouts/codex-session-log-retention-active-race.test.ts
  • src/main/codex/history/rollouts/codex-session-log-retention-migration.test.ts
  • src/main/codex/history/rollouts/codex-session-log-retention.test.ts
  • src/main/codex/history/rollouts/codex-session-log-retention.ts
  • src/main/startup/main-process-account-services.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

}
if (
publishedSessionsRoot !== undefined &&
!(await isPublished(join(publishedSessionsRoot, relative(sessionsRoot, rollout.path))))

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.

Major · Data Integrity & Integration · Quick win

Verify that the published file is the managed rollout.

isPublished accepts any regular file at the same relative path. If that file is an older, separate copy, the sweep deletes the managed rollout even if the published file lacks later content. Backfill also skips an existing target, so a later migration cannot restore the missing content. For the hardlink publication path, compare file identity before removing the managed path; keep files whose publication cannot be established. (raw.githubusercontent.com)

Comment on lines +72 to +75
state.codexRuntimeHome.isHostSystemDefaultSessionMigrationEligible()
? resolveCodexSessionBackfillPaths(resolveHostCodexSessionSourceHome(store.getSettings()))
.systemSessionsRoot
: undefined

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.

Major · Data Integrity & Integration · Quick win

Keep unpublished rollouts when the startup sweep runs while migration is ineligible.

When isHostSystemDefaultSessionMigrationEligible() is false, this call passes undefined as publishedSessionsRoot. The published-copy check runs only when that root is defined, so an expired managed rollout outside the newest 50 is deleted before any copy is published. Eligibility depends on the current settings, and the settings listener can change it later. A later switch to the host system-default account then starts a migration that may have no copy of the deleted rollout to publish. This conflicts with the stated intent at line 69: never prune a copy the migration has not published.

Run the sweep only when migration is eligible, so the published root is always supplied:

Suggested fix

--- "a/src/main/startup/main-process-account-services.ts"
+++ "b/src/main/startup/main-process-account-services.ts"
@@ -67,13 +67,13 @@
   state.claudeAccounts = services.claudeAccounts
   void startCodexStateDbBackfillRecoveryInBackground(getOrcaManagedCodexHomePath())
   // Why: prune unbounded rollout logs (#16776), but never a copy the migration hasn't published yet.
-  void startCodexSessionLogRetentionSweepInBackground(
-    getOrcaManagedCodexHomePath(),
-    state.codexRuntimeHome.isHostSystemDefaultSessionMigrationEligible()
-      ? resolveCodexSessionBackfillPaths(resolveHostCodexSessionSourceHome(store.getSettings()))
-          .systemSessionsRoot
-      : undefined
-  )
+  if (state.codexRuntimeHome.isHostSystemDefaultSessionMigrationEligible()) {
+    void startCodexSessionLogRetentionSweepInBackground(
+      getOrcaManagedCodexHomePath(),
+      resolveCodexSessionBackfillPaths(resolveHostCodexSessionSourceHome(store.getSettings()))
+        .systemSessionsRoot
+    )
+  }
   // Defer shared-home migration; compatibility launches re-arm non-destructive scans for new rollouts (#4444, #8612, #12480).
   state.codexSessionMigration.scheduleInitialRun()
   store.onSettingsChanged((updates) => {

This change also means retention does not run on launches where migration is ineligible. Those managed rollouts are not pruned until an eligible launch.

- isPublished now requires the published path to share the managed
  rollout's inode; a separate, older copy no longer licenses deletion
  (backfill never replaces an existing target).
- The startup sweep always checks the host system sessions root, so a
  later switch to the host system default still finds every rollout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VNM2N9DJTT2rs6oJfM83oC
@maxmilian

Copy link
Copy Markdown
Contributor Author

Thanks for running the full review. Both findings were real, and both are fixed in 7f526ce25a:

  1. Published-copy check (codex-session-log-retention.ts): isPublished now requires the file at the published path to share the managed rollout's inode (dev + ino). Any other file there, such as an older copy, keeps the managed rollout. Since backfill never replaces an existing target, deleting in that case would have lost the newer content permanently. The delete step also re-checks the inode alongside the existing mtime re-check. One trade-off: a rollout published as a separate copy rather than a hardlink is now never pruned. That costs disk space, never data. New test: keeps an expired rollout when the published path holds a separate, older copy. It fails without the inode check.

  2. Sweep while migration is ineligible (main-process-account-services.ts): the startup sweep now always passes the host system sessions root instead of undefined. A later switch to the host system default can still publish every rollout. While migration stays ineligible, only rollouts already hardlinked there get pruned, so the sweep frees less space for users who never use the host system default. If you'd prefer it to prune unconditionally in that case, that's a one-line change and I'm happy to make it.

pnpm run check:changed --base=origin/main: 25/25 passed (unit tests, typecheck, lint, ratchets).

@AmethystLiang

Copy link
Copy Markdown
Contributor

Thanks for this, @maxmilian, and sorry for the wait. Our review found the sweep can delete data it shouldn't in a few edge cases: a session Codex is still writing to, a same-path file that isn't the same history, and a symlinked sessions root. It also showed that removing a hardlinked copy frees no disk space. Because this deletes user history, we're redesigning the cleanup from scratch on our side. Your PR is the reference for it. We'll credit you as co-author on the new PR and link it here when it's up.

@maxmilian

Copy link
Copy Markdown
Contributor Author

Thanks @AmethystLiang, that makes sense. Since this deletes user history, a redesign that handles the in-progress, same-path and symlinked-root cases is the safer route, and good catch that dropping a hardlinked copy frees nothing. Happy to review the new PR or test it locally when it is up. I will close this one once it is linked.

@AmoabaKelvin

Copy link
Copy Markdown
Collaborator

Thanks @maxmilian, and for the patience through the review rounds. We rebuilt this inside Workspace Cleanup: #42959 adds a "Delete chat history with the workspace" setting, and #43000 extends it to Codex. Instead of an age cutoff, it deletes a session only once its Orca workspace folder is gone and every copy of the rollout (~/.codex, managed and account homes, .zst and archived) is idle and not open in Codex. Your PR was the starting point for #43000, and you're credited as co-author on its commit. Closing this one in favour of those.

@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks again @maxmilian. The follow-up to this landed in #43894: Settings › Agents now shows how much space Codex chat history takes on each host, measured read-only, next to the opt-in "Delete agent history when a workspace is deleted" setting from #43000. Your work on this PR shaped it, and you're credited as co-author on the merged commit (3ceb785).

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.

codex-runtime-home/sessions grows unbounded, consumed 11GB with no cleanup mechanism

4 participants