"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(state): fsync persisted run state
tyj147454413-cmd2962790a433b
diff --git a/agent/src/core/state.py b/agent/src/core/state.pyindex 112cab1f5..83813a40f 100644--- a/agent/src/core/state.py+++ b/agent/src/core/state.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+import osimport uuidfrom datetime import datetimefrom pathlib import Path@@ -64,4 +65,9 @@ class RunStateStore:@staticmethoddef _write_json(path: Path, data: Any) -> None:- path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")+ # Write + fsync so a crash can't leave a truncated/empty state.json.+ payload = json.dumps(data, ensure_ascii=False, indent=2).encode("utf-8")+ with open(path, "wb") as f:+ f.write(payload)+ f.flush()+ os.fsync(f.fileno())diff --git a/agent/tests/test_state_fsync.py b/agent/tests/test_state_fsync.pynew file mode 100644index 000000000..4c7a68ba3--- /dev/null+++ b/agent/tests/test_state_fsync.py@@ -0,0 +1,39 @@+"""Durability regression: RunStateStore._write_json must fsync.++A crash between write() and the kernel flushing its page cache can leave+state.json truncated or empty. _write_json now writes in binary mode and+fsyncs the file descriptor before closing.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++import src.core.state as state_mod+from src.core.state import RunStateStore+++def test_write_json_calls_fsync(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ fsynced: list[int] = []+ real_fsync = state_mod.os.fsync++ def spy(fd: int) -> None:+ fsynced.append(fd)+ real_fsync(fd)++ monkeypatch.setattr(state_mod.os, "fsync", spy)++ target = tmp_path / "state.json"+ RunStateStore._write_json(target, {"status": "success"})++ assert fsynced, "fsync was not called on _write_json"+ assert json.loads(target.read_text(encoding="utf-8")) == {"status": "success"}+++def test_write_json_roundtrips_unicode(tmp_path: Path) -> None:+ target = tmp_path / "req.json"+ RunStateStore._write_json(target, {"prompt": "买入 A 股"})+ assert json.loads(target.read_text(encoding="utf-8"))["prompt"] == "买入 A 股"