Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(agentic-ide): stop two snapshot writes from clobbering each other

Ruben Lütke2d2b2c55c71b
diff --git a/jarvis/agentic_ide/resume_store.py b/jarvis/agentic_ide/resume_store.py
index d879e83a23..2ac743fb1d 100644
--- a/jarvis/agentic_ide/resume_store.py
+++ b/jarvis/agentic_ide/resume_store.py
@@ -31,15 +31,22 @@ from __future__ import annotations
import json
import os
+import threading
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
+from uuid import uuid4
from loguru import logger
from .agent_sessions import ResumeHandle
+# Saves arrive from more than one thread (see `save`), and the last one has to
+# be the one that lands rather than the one that happened to finish its rename
+# first.
+_WRITE_LOCK = threading.Lock()
+
# Bumped whenever the stored shape changes incompatibly. An unknown version
# reads as "nothing to resume": half-understanding a newer build's file would
# reopen a workspace with pieces missing, which is worse than offering nothing.
@@ -158,6 +165,14 @@ def save(snapshot: Snapshot) -> None:
workspace that is otherwise running perfectly. Failures are logged and
swallowed, and the previous snapshot survives untouched — the temp file is
written first and only then replaces the real one.
+
+ **Two writes really do collide here.** A pane connecting saves the workspace,
+ and a moment later the background lookup that finds a Codex conversation id
+ saves it again — from a different thread. Sharing one temp filename made
+ those two clobber each other's file, and on Windows the second ``os.replace``
+ then failed outright with a sharing violation, silently losing exactly the
+ conversation id this feature exists to keep. So each write gets its own temp
+ name, and the lock keeps the last writer's file the one that lands.
"""
if not snapshot.terminals:
# Nothing to come back to. Clearing beats storing an empty offer that
@@ -165,13 +180,21 @@ def save(snapshot: Snapshot) -> None:
clear()
return
target = _store_path()
- try:
- target.parent.mkdir(parents=True, exist_ok=True)
- tmp = target.with_suffix(".json.tmp")
- tmp.write_text(json.dumps(snapshot.to_dict(), indent=2), encoding="utf-8")
- os.replace(tmp, target)
- except OSError as exc:
- logger.warning("Agentic IDE: could not persist the resume snapshot: {}", exc)
+ tmp = target.with_name(f"{target.name}.tmp-{os.getpid()}-{uuid4().hex[:8]}")
+ with _WRITE_LOCK:
+ try:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ tmp.write_text(json.dumps(snapshot.to_dict(), indent=2), encoding="utf-8")
+ os.replace(tmp, target)
+ except OSError as exc:
+ logger.warning(
+ "Agentic IDE: could not persist the resume snapshot: {}", exc
+ )
+ # Never leave a half-written temp file behind to be found later.
+ try:
+ tmp.unlink(missing_ok=True)
+ except OSError: # noqa: S110 - cleanup is best-effort
+ pass
def load() -> Snapshot | None:
diff --git a/tests/unit/agentic_ide/test_resume_store.py b/tests/unit/agentic_ide/test_resume_store.py
index ad12f41237..194bc7c1f4 100644
--- a/tests/unit/agentic_ide/test_resume_store.py
+++ b/tests/unit/agentic_ide/test_resume_store.py
@@ -11,6 +11,8 @@ from __future__ import annotations
from pathlib import Path
+import pytest
+
from jarvis.agentic_ide import resume_store
from jarvis.agentic_ide.agent_sessions import ResumeHandle
@@ -116,14 +118,17 @@ def test_clear_removes_the_offer(tmp_path: Path) -> None:
def test_a_failed_write_leaves_the_previous_snapshot_readable(
- tmp_path: Path,
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A bad write must not turn a good offer into a stub."""
resume_store.save(_snapshot(str(tmp_path)))
target = resume_store._store_path()
before = target.read_text(encoding="utf-8")
- # A directory sitting exactly where the temp file wants to go.
- target.with_suffix(".json.tmp").mkdir(parents=True, exist_ok=True)
+
+ def _fail(*_args: object) -> None:
+ raise OSError("the disk went away mid-write")
+
+ monkeypatch.setattr(resume_store.os, "replace", _fail)
resume_store.save(
resume_store.Snapshot(
session_id="ide_other",
@@ -135,6 +140,54 @@ def test_a_failed_write_leaves_the_previous_snapshot_readable(
)
)
assert target.read_text(encoding="utf-8") == before
+ # ...and no debris is left lying around to confuse the next read.
+ assert list(target.parent.glob("*.tmp-*")) == []
+
+
+def test_two_threads_saving_at_once_do_not_lose_the_write(tmp_path: Path) -> None:
+ """The collision that actually happens, and cost a conversation id.
+
+ A pane connecting saves the workspace; a moment later the background lookup
+ that found a Codex conversation saves it again, from another thread. With
+ one shared temp filename the two clobbered each other — and on Windows the
+ second rename failed outright, dropping exactly the id this feature exists
+ to keep.
+ """
+ import threading
+
+ start = threading.Barrier(6)
+ errors: list[BaseException] = []
+
+ def _save(index: int) -> None:
+ try:
+ start.wait(timeout=5)
+ for _ in range(10):
+ resume_store.save(
+ resume_store.Snapshot(
+ session_id=f"ide_{index}",
+ folder=str(tmp_path),
+ saved_at=float(index),
+ terminals=[
+ resume_store.SnapshotTerminal(
+ key=f"t{index}", name=f"T{index}", agent="claude"
+ )
+ ],
+ )
+ )
+ except BaseException as exc: # noqa: BLE001 - reported to the assertion
+ errors.append(exc)
+
+ threads = [threading.Thread(target=_save, args=(i,)) for i in range(6)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(timeout=10)
+
+ assert errors == []
+ # Whoever won, the file is a COMPLETE snapshot and not a torn one.
+ loaded = resume_store.load()
+ assert loaded is not None and len(loaded.terminals) == 1
+ assert list(resume_store._store_path().parent.glob("*.tmp-*")) == []
# ------------------------------------------------------------------- offer