Skip to content

fix(storage): a fork+exec in another thread makes a reopen after drop fail with Locked #552

Closed

Description

@ajianaz

What happens

Reopening a session file right after dropping its writer handle can fail with StorageError::Locked { holder: Some(<our own pid>) } when another thread of the same process is spawning a child process at that moment.

It showed up twice as an intermittent failure in tole-core tests that drop a JsonlStorage and reopen the same file:

  • storage::poison_tests::failed_append_poisons_until_reopen
  • turn_loop::turn_survives_reopen_between_steps

Both panicked with Locked { holder: Some(<pid>) }, where the holder pid is the test process itself, and both pass on a re-run.

Likely cause (reproduced)

lock_writer takes an flock on <id>.jsonl.lock. An flock belongs to the open file description, not to the process. When another thread forks a child (std::process::Command, run_command, a job, a hook), the child briefly holds a duplicate of every inherited descriptor until it execs, even with O_CLOEXEC (which only closes the descriptor at exec). If our drop(storage) closed its descriptor inside that window, the child's duplicate keeps the lock alive for a moment, and a reopen on the main thread sees WouldBlock.

Throwaway probe (not committed): create a session, drop it, JsonlStorage::open the same file, 3000 times, while 3 other threads loop on Command::new("true").status():

  • with the spawner threads: 207 / 3000 reopens failed with Locked, holder = our own pid
  • control, same loop with no spawner threads: 0 / 3000

Why it matters beyond tests

Anything that reopens a session while another thread may spawn a command can hit it: POST /sessions {"resume": id} (a spurious 409 ... open for writing by pid <our pid>), the TUI /resume and /new, approvals-resume after an eviction, a mission re-open. The message is misleading too: it names our own pid.

Proposed fix (for discussion)

A short bounded retry in lock_writer (or JsonlStorage::open) when the lock is WouldBlock and the recorded holder pid is our own pid: such a hold is either this transient or a genuine second open in the same process (the self-lock case of #475), and a retry of about 100 ms (a few sleeps of a few ms) costs the genuine case almost nothing while removing the transient. A different holder pid keeps failing immediately, as today.

Alternatives considered:

Acceptance criteria

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions