iai-personal-memory-engine icon indicating copy to clipboard operation
iai-personal-memory-engine copied to clipboard

Concurrent turn-capture invocations race on a shared tmp path, raising FileNotFoundError

Open tom-shields-stitch opened this issue 3 months ago • 1 comments

What happens

UserPromptSubmit's turn-capture hook and Stop's session-capture hook (which calls capture-turn-deferred) both maintain the same {session_id}.offset file, and can fire close together for one exchange — confirmed live on Cursor, which fires the turn-capture hook twice per prompt. Both writers build their rename-source tmp path from the session id alone, with no per-process uniqueness:

tmp_path = offset_path.parent / (offset_path.name + ".tmp")

Whichever process calls os.replace() second finds its tmp file already consumed by the first, raising FileNotFoundError. The exception is caught and logged, never fatal — but the write it belonged to is lost. On a session's first turn (no prior offset baseline yet) this can drop the write entirely until the Stop-hook safety net catches up.

Same pattern exists at three call sites sharing this shape: the offset write, and the watermark/live-fingerprint tmp writes used by the per-turn freshness gate.

Reproduced empirically

A 20-process concurrency stress test against capture-turn-deferred (10 pairs of iai-mcp-turn-capture.sh + iai-mcp capture-turn-deferred, launched simultaneously against the same session) failed 9/20 calls with this exact FileNotFoundError.

Fix

PR incoming: suffix every tmp path with os.getpid(), so concurrent writers never share a rename source. Same stress test passes 20/20 after the fix, with no leftover tmp files and the correct final offset.

tom-shields-stitch avatar Aug 11 '26 09:08 tom-shields-stitch

Fixed in the engine ahead of this report, across four write seams (offset, watermark, live-fingerprint, turnstate). Shipping publicly in the next release.

CodeAbra avatar Aug 11 '26 19:08 CodeAbra