codex icon indicating copy to clipboard operation
codex copied to clipboard

[CLI] Active rollout writer keeps writing to an unlinked inode after the session path is replaced

Open ckarabulut opened this issue 3 months ago • 5 comments

What version of Codex CLI is running?

Observed with codex-cli 0.143 and onwards

What subscription do you have?

N/a

Which model were you using?

Model-independent; this occurs in the local rollout persistence layer.

What platform is your computer?

Linux 6.16

What terminal emulator and version are you using?

Not terminal-specific.

Codex doctor report

N/A

What issue are you seeing?

Codex keeps the file descriptor for an active session rollout JSONL open across turns. If a synchronization, backup, or restore tool replaces the rollout pathname using normal Unix unlink-and-copy or rename-over semantics, the pathname starts referring to a new inode while Codex keeps writing to the old, unlinked inode.

Those later writes and flushes succeed, so Codex emits no error. The visible rollout path remains stale, and when the Codex process exits the unlinked inode—and every turn appended to it after replacement—disappears. codex resume <thread-id> then reloads the stale file and appears to go backward in time.

This is not specific to one synchronization product; any process that replaces $CODEX_HOME/sessions/...jsonl while a thread is live can trigger it.

What steps can reproduce the bug?

Use a disposable thread because this intentionally demonstrates loss of its post-replacement tail.

  1. On Linux, start a new interactive Codex thread and send FIRST_SENTINEL. Record the thread UUID from /status or its rollout filename.
  2. In a second terminal, replace that rollout path with a byte-identical file on a different inode:
THREAD_ID='<disposable-thread-uuid>'
CODEX_HOME_DIR="${CODEX_HOME:-$HOME/.codex}"
ROLLOUT="$(find "$CODEX_HOME_DIR/sessions" -type f -name "*${THREAD_ID}.jsonl" -print -quit)"
test -n "$ROLLOUT"
OLD_ID="$(stat -c '%d:%i' "$ROLLOUT")"
cp --preserve=all "$ROLLOUT" "$ROLLOUT.replacement"
mv -f "$ROLLOUT.replacement" "$ROLLOUT"
NEW_ID="$(stat -c '%d:%i' "$ROLLOUT")"
printf '%s -> %s\n' "$OLD_ID" "$NEW_ID"
test "$OLD_ID" != "$NEW_ID"
  1. In the still-running Codex thread, send SECOND_SENTINEL_AFTER_REPLACEMENT and wait for the response.
  2. Inspect the visible rollout path:
grep -F 'SECOND_SENTINEL_AFTER_REPLACEMENT' "$ROLLOUT"

The command finds no match even though the turn completed successfully. While Codex is still running, lsof +L1 can also show its writable descriptor for the deleted rollout inode.

  1. Exit Codex and run codex resume "$THREAD_ID". The resumed transcript contains the first turn but not the second.

What is the expected behavior?

Codex should not report a successful durable write to a rollout file that is no longer reachable through the configured pathname. After the second prompt, the canonical rollout path and a resumed thread should contain that turn.

If Codex cannot safely reconcile a replacement with the live branch, it should surface the conflict and preserve the local tail at a recoverable path rather than silently losing it. Reopening the current pathname—or comparing the open descriptor's (st_dev, st_ino) with the pathname and then safely reopening/forking—before each non-empty durable batch would detect this case.

Additional information

The current writer lifecycle in codex-rs/rollout/src/recorder.rs appears to explain the behavior:

  • RolloutWriterState caches Option<JsonlWriter>.
  • ensure_writer_open returns immediately when that option is already populated.
  • write_pending_once writes and flushes but does not close or reopen the file.
  • enter_recovery_mode drops the writer only after an I/O error. Writing an unlinked Unix inode remains valid, so pathname replacement does not trigger it.
  • The background rollout_writer task owns this state until shutdown.

The source comments explain the background task as a way to keep writes asynchronous and ordered, but I could not find a documented requirement to retain the same descriptor across successful write batches. Is that descriptor lifetime intentional? If so, what invariant requires it?

There is already a reopen-per-call precedent for unloaded threads: append_rollout_item_to_path opens the current path, derives its ordinal state, appends, and then drops the local writer.

A focused regression test could persist item A, replace the active rollout with byte-identical contents on a new inode, persist and flush item B, and assert that the currently named rollout contains B with valid ordinals.

For comparison, a controlled single-session probe of Claude Code 2.1.220 on Linux found no transcript JSONL descriptor held open between turns. After a byte-identical path replacement, its next turn appended to the replacement inode. That does not make Claude immune to a short write-time race, but it avoids this persistent active-writer split.

ckarabulut avatar Aug 12 '26 07:08 ckarabulut

Potential duplicates detected. Please review them and close your issue if it is a duplicate.

  • #37419

Powered by Codex Action

github-actions[bot] avatar Aug 12 '26 07:08 github-actions[bot]

Confirmed structure on main @ 1f41cc5d92: the recorder opens the rollout for append once and holds the File across the writer task's lifetime (rollout/src/recorder.rs — open_rollout_for_append at #L896, plain OpenOptions append at #L1634-L1638). Nothing re-checks that the fd still corresponds to the pathname, so unlink-and-copy / rename-over by any sync tool silently forks the history exactly as your sentinel repro shows.

Cheap fix that keeps the long-lived-fd performance: on each append batch (or a periodic tick), fstat the held fd and compare (st_dev, st_ino) against stat of the path — or simpler, check st_nlink == 0 on the fd. On mismatch, either re-open the path and replay/append (if the new file is a prefix, your byte-identical case) or fail the turn loudly with "rollout file was replaced externally" — silent success into an unlinked inode is the only unacceptable outcome. One syscall pair per batch is noise next to a JSONL write.

Also worth a docs line: exclude $CODEX_HOME/sessions (and the state DBs) from live sync/backup tooling — the same guidance every database ships with. That plus your #38150 lock-configurability ask covers the shared-home story from both ends.

jdcodes1 avatar Aug 18 '26 13:08 jdcodes1

Additional note for this issue: the same unlinked-inode failure can arise whenever an active rollout pathname is replaced while RolloutRecorder retains an append descriptor. Subsequent writes can succeed on the old inode while the named rollout remains stale, so the missing activity only becomes apparent after resume.

The robust fix should compare the held descriptor identity with the current pathname before each durable batch, then reopen the current path and re-derive its ordinal state while preserving pending items. If the old descriptor has already accepted data that is no longer reachable, Codex should surface that conflict rather than report a silently durable write. A focused regression should replace the pathname between two writes and verify that the second write is present in the currently named rollout.

rebroad avatar Sep 17 '26 10:09 rebroad

Still reproducible by inspection on rust-v0.163.0: codex-rs/rollout/src/recorder.rs holds the append descriptor for the life of the writer and its retry path only reopens after a write error. Writes into an unlinked or replaced inode do not error, so that path never triggers.

We hit this on Linux in a setup where archive/cleanup tooling moves session rollouts, and have been running a patched build since late September. Since this repo doesn't take PRs, here is the fix as a reference implementation in case it's useful to whoever picks this up:

Branch (one commit on top of rust-v0.163.0): https://github.com/jcrben/codex/commits/fix/rollout-unlink-recovery-0.163

Approach. Before draining a batch, the serialized writer compares the held descriptor with the canonical path (st_dev/st_ino on Unix):

  • Same file: no change.
  • Path missing (unlinked): flush, copy the still-open inode to a synced sibling temp file, publish it at the canonical path with a no-overwrite hard link, fsync the directory, reopen for append, and log once. Nothing written after the unlink is lost.
  • Path replaced by a byte-identical file (the sentinel repro in this issue): the hard link reports AlreadyExists, the contents are compared, and the writer adopts the new inode and keeps appending there.
  • Path replaced by different content (for example an older backup restored over it): nothing is overwritten. The old descriptor is kept and the error is returned to the item acknowledgement instead of the warning-only flush path, so the turn fails loudly rather than reporting a silently durable write.

Ordinary write errors keep the existing flush-barrier and reopen contract. Windows has no stable inode identity here, so only the missing-path case is handled there.

Tests. The commit adds three regressions: unlink, then recover history and the durable-history projection; a concurrently recreated path is not replaced; a recovery failure is reported and can be retried. Results on rust-v0.163.0:

  • With the fix: cargo test -p codex-rollout -p codex-thread-store: 150 + 273 passed, 0 failed (includes the three new tests).
  • Without the fix (source reverted to rust-v0.163.0, new tests kept): all three new tests fail (0 passed; 3 failed).

Commit: https://github.com/jcrben/codex/commit/57389c6e1e92bd841901039ab79720f9d1f18eee

Happy to adjust or test variants if the team prefers a different policy, for example failing the turn on any identity mismatch instead of recovering.

jcrben avatar Oct 23 '26 05:10 jcrben

Update: I ported the fix from my earlier comment onto current main (2fb728da7) and re-ran the tests.

Still reproduces on current main. If a live session's rollout JSONL is unlinked (by a cleanup tool or the user), the writer keeps appending to the unlinked inode through its open descriptor, the history projection logs ENOENT on every lookup, and every turn after the unlink is gone once the process exits.

Candidate fix (branch: https://github.com/jcrben/codex/tree/fix/rollout-unlinked-recovery-upstream, one commit on top of main): before draining queued items, the writer checks that the canonical path still names its open file (device + inode on Unix). If the path is missing or replaced, it syncs the live file, stages a copy beside the canonical path, publishes it with a no-overwrite hard link (so a concurrently recreated file is left alone), syncs the directory and reopens for append. If recovery fails, the error reaches the append caller and the queued items stay queued for retry, instead of a logged warning and silent loss.

Tests: three regression tests (recovery after unlink, a concurrently recreated path left untouched, recovery failure surfaced and retried) all fail on current main and pass with the fix. Full suites: codex-rollout 170/170, codex-thread-store 305/305; just fix and just fmt clean.

I understand external PRs aren't accepted; the branch is here as a reference for whoever picks this up. I've run a patched build with this fix daily since September.

jcrben avatar Nov 20 '26 08:11 jcrben