"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(swarm): stop concurrent SwarmStore writers from clobbering run state
Lanre Shittub5b075bac9ab
diff --git a/agent/src/swarm/store.py b/agent/src/swarm/store.pyindex 20e7a429c..8289e64c1 100644--- a/agent/src/swarm/store.py+++ b/agent/src/swarm/store.py@@ -15,6 +15,7 @@ import jsonimport osimport threadingimport time+import uuidfrom datetime import datetime, timezonefrom pathlib import Path@@ -559,7 +560,15 @@ class SwarmStore:path: Target file path.content: File content."""- tmp_path = path.with_suffix(".tmp")+ # self._write_lock only serializes callers on this SwarmStore+ # instance; mcp_server._get_swarm_store() builds a fresh instance+ # per tool call, so two concurrent pollers of the same run each get+ # their own lock. A shared ".tmp" name let one writer's rename+ # consume the other's still-unwritten temp file, silently losing an+ # update or raising FileNotFoundError. A per-write unique name keeps+ # each writer's temp file private regardless of how many SwarmStore+ # instances are racing.+ tmp_path = path.with_suffix(f".{uuid.uuid4().hex}.tmp")with self._write_lock:tmp_path.write_text(content, encoding="utf-8")_replace_with_retry(tmp_path, path)diff --git a/agent/tests/test_swarm_store_atomic_write.py b/agent/tests/test_swarm_store_atomic_write.pyindex ced02187e..2c0a4dc52 100644--- a/agent/tests/test_swarm_store_atomic_write.py+++ b/agent/tests/test_swarm_store_atomic_write.py@@ -16,6 +16,7 @@ is bounded, and POSIX behaviour is unchanged (a plain OSError withoutfrom __future__ import annotationsimport os+import threadingimport pytest@@ -124,6 +125,44 @@ def test_load_run_missing_is_fast_none(tmp_path, monkeypatch):assert store.load_run("does-not-exist") is None+def test_concurrent_stores_writing_same_run_do_not_crash_or_clobber(tmp_path):+ """mcp_server._get_swarm_store() builds a fresh SwarmStore per tool call,+ so two pollers of the same run each hold their own _write_lock. A shared+ ".tmp" name let one writer's rename consume the other's unwritten temp+ file, raising FileNotFoundError for the loser (or silently discarding+ the winner's own content). Neither writer should ever raise here, and+ the surviving content must be one writer's whole payload, never a mix.+ """+ store_a = SwarmStore(base_dir=tmp_path)+ store_b = SwarmStore(base_dir=tmp_path)+ store_a.create_run(_run())++ run_a = _run()+ run_a.final_report = "FROM-A"+ run_b = _run()+ run_b.final_report = "FROM-B"++ start_gate = threading.Barrier(2)+ errors: list[Exception] = []++ def write(store: SwarmStore, run: SwarmRun) -> None:+ start_gate.wait()+ try:+ store.update_run(run)+ except Exception as exc: # noqa: BLE001 - captured for the assertion below+ errors.append(exc)++ t_a = threading.Thread(target=write, args=(store_a, run_a))+ t_b = threading.Thread(target=write, args=(store_b, run_b))+ t_a.start()+ t_b.start()+ t_a.join()+ t_b.join()++ assert not errors, f"concurrent update_run raised: {errors!r}"+ assert store_a.load_run("r").final_report in {"FROM-A", "FROM-B"}++def test_posix_oserror_is_not_treated_transient():"""POSIX no-op guard: a plain OSError (no winerror) is never transient,so off-Windows the retry loop runs exactly once — no behavior change."""