Skip to content

[lib] Write the Codex session cache atomically (#689) - #1102

Merged
NiveditJain merged 9 commits into
mainfrom
claude/combine-689-963b4b
Nov 30, 2026
Merged

NiveditJain merged 9 commits into
mainfrom
claude/combine-689-963b4b

Conversation

@NiveditJain

@NiveditJain NiveditJain commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Closes #689

findCodexTranscript caches the sessionId → transcript path map in ~/.failproofai/state/codex-session-paths.json. writeCacheEntry wrote that file in place, so a write that died partway (a full disk, a killed hook process) left half a JSON document. The next readCache() failed to parse it and returned {}, and the next write replaced the file with only the new entry, which lost every earlier one. The cache is now written to a temp file in the same directory and renamed over the old one.

This combines the two community PRs for the issue. Their commits are cherry-picked (-x) with their authors kept.

From @AshSgDe29071999 (#692)

  • The first fix: write to a per-process .tmp beside the cache, rename it over the cache, and remove the temp file if anything fails.
  • The happy-path test in __tests__/lib/codex-sessions.test.ts: the cache entry is readable after a lookup and no .tmp file is left. This test is unchanged in the final diff.

From @lakshya-dhariwal (#847)

  • The same fix, with a comment explaining why rename makes it atomic. The cherry-pick conflict with fix: write Codex session cache atomically #692 was resolved into one write that keeps that comment.
  • __tests__/lib/codex-sessions-cache.test.ts and its setup, with the rename-failure test: a directory sits where the cache file belongs, the rename fails after the temp write, and no .tmp file may be left.
  • The read-only-state-dir test, renamed here to say what it checks (see below).

Both inline fixes are in the branch history. In the final diff, writeCacheEntry instead calls the existing shared helper (next section).

Added here

  • writeCacheEntry calls writeJsonAtomically from lib/atomic-write.ts. That is the same temp-file-and-rename, already used by 11 other modules, and the file's header says it exists so inline copies stop drifting. The helper adds a random suffix to the temp name.
  • A regression test for the bug itself: writeFileSync is made to write half its data and fail with ENOSPC, and the earlier cache must still parse with its entries intact.
  • Two happy-path tests in the new file repeated fix: write Codex session cache atomically #692's test, so they were dropped. Its afterEach now restores FAILPROOFAI_HOME instead of deleting it.
  • The CHANGELOG.md entry.

How the claims were checked

  • On main, the regression test fails with SyntaxError: Unterminated string in JSON, so the cache file held half a document. It passes with the contributors' inline version and with the helper.
  • With the helper's temp cleanup deleted, the regression test and the rename-failure test both fail. The read-only-dir test still passed, because there the temp file is never created. So it is renamed to what it checks, that the lookup still returns the transcript when the cache can't be written, and it asserts that return value. Root can write a 0500 directory, so as root it passes trivially.
  • lib/codex-sessions.ts and both test files pass eslint, plus a tsc run scoped to those files under the repo's tsconfig.json.
  • git merge-tree against the open PRs that also touch lib/codex-sessions.ts: [hooks] Block agent edits to its own hook settings (#1794) #1053 merges cleanly. feat(audit): detect leaked credentials and get them in front of the user #789 has no conflict in this file, and its conflicts elsewhere are with main as well.

Worth a look: file modes
On an actual write at umask 0002, main leaves the cache 0664 and a newly created state dir 0775. Through the helper they are 0600 and 0700, and so is ~/.failproofai if the cache write is what creates it. That matches backfill-request.json (written through the same helper) and telemetry-id (written 0600) in the same directory. The JSON is now pretty-printed, and readCache() parses an existing compact file the same way.

Merging: the main ruleset allows only squash merges, so the squash commit should carry Co-authored-by trailers for AshSgDe29071999 and lakshya-dhariwal, as #1067's did. Their original commits stay in this PR's history.

Type of Change

  • Bug fix
  • New feature
  • Refactor
  • Documentation

Checklist

All four were confirmed by CI on ff122c45 (the quality, test ×3, test-e2e and build jobs).

  • npm run lint passes
  • npx tsc --noEmit passes
  • npm run test:run passes
  • npm run build succeeds

🤖 Generated with Claude Code

AshSgDe29071999 and others added 6 commits November 30, 2026 17:17
writeCacheEntry used writeFileSync on the live JSON map. A torn write
turns the next read into invalid JSON and wipes every cached path.
Write to a pid-unique temp file, rename into place, and unlink the
temp on failure.

Fixes #689

(cherry picked from commit a1375c8)
… write

Both community fixes wrote the temp file and renamed it inline. The repo
already has lib/atomic-write.ts for exactly this, used by a dozen other
state files, so writeCacheEntry now calls writeJsonAtomically. It also
gives the temp file a random suffix beside the pid, and makes the cache
0600 like the rest of ~/.failproofai/state.

Neither PR tested the bug itself: that a write which fails halfway leaves
the previous cache whole. The new test makes writeFileSync write half its
data and then fail with ENOSPC. It fails on main, where the half-written
JSON makes readCache() start over from {}, and passes with the fix.

The two happy-path tests from the cache test file are dropped. The test in
codex-sessions.test.ts already checks the same things: the entry is
readable and no .tmp file is left. The afterEach also restores
FAILPROOFAI_HOME rather than deleting it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Explain Change →

Caution

Review failed

The pull request is closed.

No actionable comments were generated in the recent review.

Walkthrough

Codex session-cache writes now use writeJsonAtomically instead of direct file writes. Tests cover successful cache creation and lookup, partial-write preservation, and temporary-file cleanup after write or rename failures.

Changes: Codex Session Cache

Layer / File(s) Summary
Atomic cache writes
lib/codex-sessions.ts, __tests__/lib/codex-sessions.test.ts, CHANGELOG.md
writeCacheEntry now persists the updated cache through writeJsonAtomically. The transcript lookup test checks the cache entry and verifies that no temporary files remain. The changelog records the change.
Write failure cleanup
__tests__/lib/codex-sessions-cache.test.ts
Tests cover partial writes, a read-only state directory, and rename failures. They check that lookup does not throw and that temporary files do not remain.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Low

Suggested reviewers: chhhee10

Merge Risk: Minimal · previous review ff122

Codex session-cache writes now go through a temporary file and rename, so an interrupted write no longer corrupts the cache. Lookups still return the transcript when the cache cannot be written. No merge-blocking risk remains.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "[lib] Write the Codex session cache atomically (#689)" names the main change. The changeset replaces the in-place cache write in writeCacheEntry with the shared writeJsonAtomically helper, …
Linked Issues check Passed [#689] Requires an atomic, best-effort cache write in lib/codex-sessions.ts. The write needs a process-unique temp file, a rename into place, temp cleanup on failure, and no thrown errors to the calle…
Out of Scope Changes check Passed The lib/codex-sessions.ts diff changes only the cache-write path and its imports. It removes the now-unused mkdirSync, writeFileSync, and dirname imports, and adds the writeJsonAtomically import. The …
Description check Passed The description is thorough and covers the template. It states the problem and the fix, and it credits both community PRs. It also describes how the claims were checked and the file-mode impact. The T…
Full details: Title check

Explanation

The title "[lib] Write the Codex session cache atomically (#689)" names the main change. The changeset replaces the in-place cache write in writeCacheEntry with the shared writeJsonAtomically helper, which writes a temp file and renames it over the cache. The title is specific and concise, and the issue number matches the linked issue.

Full details: Linked Issues check

Explanation

[#689] Requires an atomic, best-effort cache write in lib/codex-sessions.ts. The write needs a process-unique temp file, a rename into place, temp cleanup on failure, and no thrown errors to the caller. At head, writeCacheEntry calls writeJsonAtomically(CACHE_PATH, cache) inside a try/catch that swallows errors. writeJsonAtomically (lib/atomic-write.ts) writes to a temp path built from the pid and a random suffix, renames it over the target, and removes the temp file in its catch before rethrowing. This meets the issue's approach. The helper's random suffix differs from the literal ${CACHE_PATH}.${process.pid}.tmp path the issue names, but it stays process-unique. Tests at head: tests/lib/codex-sessions.test.ts adds a happy-path test that reads the cache entry and checks that no .tmp files remain. tests/lib/codex-sessions-cache.test.ts adds a half-write regression test, a read-only state-dir test, and a rename-failure test that checks for no .tmp files. The test files use the _getCacheFilePath export the issue mentions. The author reports that the existing lib/codex-sessions tests and targeted lint and type checks pass. I did not run the tests myself. Test results rest on the PR description.

Full details: Out of Scope Changes check

Explanation

The lib/codex-sessions.ts diff changes only the cache-write path and its imports. It removes the now-unused mkdirSync, writeFileSync, and dirname imports, and adds the writeJsonAtomically import. The test changes cover the same cache-write behavior. The CHANGELOG.md entry describes the same fix. The helper lib/atomic-write.ts is unchanged in this PR. Its side effects are disclosed in the PR description: cache file mode 0600, a 0700 parent directory when created, and pretty-printed JSON. These side effects follow from reusing the shared helper. They are a behavior change, but the PR states them, and readCache() still parses the new format. I found no unrelated hunks.

Full details: Description check

Explanation

The description is thorough and covers the template. It states the problem and the fix, and it credits both community PRs. It also describes how the claims were checked and the file-mode impact. The Type of Change section marks Bug fix, and all four checklist items are marked and confirmed by CI on a named commit. The template's required sections are all present and filled in, so the check passes.

  • 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

A rabbit checks the cache at night,
Each entry lands in place just right.
If writing stops before the end,
The old cache stays, still safe to mend.
No stray temp files remain in sight,
The transcript path is found outright.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ff7e5dee-3911-40db-86aa-833438300233
Commits

Reviewing files that changed from the base of the PR and between eec0e1f and ff122c4.

Files selected for processing: 1

  • __tests__/lib/codex-sessions-cache.test.ts

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

NiveditJain and others added 2 commits November 30, 2026 17:25
In a read-only state dir the temp file is never created, so the test passed
even with the helper's cleanup removed. What it does check is that the
lookup still returns the transcript when the cache cannot be written. The
test is renamed to say that, and asserts the return value. The halfway-write
and rename-failure tests are the ones that catch a missing cleanup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@NiveditJain
NiveditJain merged commit 4e95ebe into main Nov 30, 2026
28 of 29 checks passed
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 session cache write is not atomic — a torn write loses the whole cache

4 participants