Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(live): halt on corrupt runtime state

xkam7ar0142f0d4f7bd
diff --git a/agent/src/live/runtime/reconcile.py b/agent/src/live/runtime/reconcile.py
index 0bc341246..b6fb827bc 100644
--- a/agent/src/live/runtime/reconcile.py
+++ b/agent/src/live/runtime/reconcile.py
@@ -71,6 +71,10 @@ ReadList = Callable[[], Sequence[Mapping[str, Any]]]
ReadDict = Callable[[], Mapping[str, Any]]
+class CorruptRuntimeState(RuntimeError):
+ """Raised when an existing durable runtime state cannot be trusted."""
+
+
class DeltaKind:
"""Classification labels for a single reconciliation delta.
@@ -512,16 +516,19 @@ def _state_path(broker: str) -> Path:
def _load_state(broker: str) -> dict[str, Any] | None:
"""Load the durable last-known runtime state for ``broker``.
- Loading is fail-open-to-cold-start: a missing file means a first/cold start
- (``None``). A *corrupt* file is NOT silently treated as cold start — that
- would hide a partial write — it is renamed aside and surfaced as a fresh
- start so the diff can never run against a half-truth.
+ A missing file means a first/cold start (``None``). An existing unreadable
+ or malformed file raises :class:`CorruptRuntimeState` and remains untouched
+ so the runner blocks until an operator repairs the safety baseline.
Args:
broker: Broker key.
Returns:
- The decoded state dict, or ``None`` on cold start / unreadable state.
+ The decoded state dict, or ``None`` on a genuine first start.
+
+ Raises:
+ CorruptRuntimeState: If the existing state cannot be read or decoded as
+ a JSON object.
"""
path = _state_path(broker)
if not path.is_file():
@@ -529,21 +536,13 @@ def _load_state(broker: str) -> dict[str, Any] | None:
try:
raw = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
- corrupt = path.with_name(f"{path.name}.corrupt-{int(datetime.now().timestamp())}")
- try:
- os.replace(path, corrupt)
- except OSError:
- pass
- logger.warning(
- "reconcile(%s): runtime_state.json unreadable (%s); renamed to %s, cold start",
- broker,
- exc,
- corrupt.name,
- )
- return None
+ raise CorruptRuntimeState(
+ f"reconcile({broker}): runtime_state.json is unreadable; repair is required"
+ ) from exc
if not isinstance(raw, dict):
- logger.warning("reconcile(%s): runtime_state.json is not an object; cold start", broker)
- return None
+ raise CorruptRuntimeState(
+ f"reconcile({broker}): runtime_state.json is not an object; repair is required"
+ )
return raw
diff --git a/agent/tests/test_runtime_reconcile.py b/agent/tests/test_runtime_reconcile.py
index b402fbb63..1d7a5eed3 100644
--- a/agent/tests/test_runtime_reconcile.py
+++ b/agent/tests/test_runtime_reconcile.py
@@ -20,6 +20,7 @@ import pytest
import src.live.paths as paths
from src.live.runtime.reconcile import (
+ CorruptRuntimeState,
DeltaKind,
ReconcileReport,
reconcile,
@@ -293,21 +294,37 @@ def test_unsafe_reconcile_does_not_advance_state(live_runtime: Path) -> None:
# ---------------------------------------------------------------------------
-# corrupt state is renamed aside, treated as cold start
+# corrupt state blocks until an operator repairs it
# ---------------------------------------------------------------------------
-def test_corrupt_state_renamed_and_cold_starts(live_runtime: Path) -> None:
- """A truncated/corrupt state file is renamed .corrupt-* and treated as cold."""
[email protected]("contents", ["{not json", "[]"])
+def test_corrupt_state_fails_closed_and_preserves_evidence(
+ live_runtime: Path,
+ contents: str,
+) -> None:
+ """Malformed safety state blocks every reconcile and remains untouched."""
path = paths.broker_dir("robinhood") / "runtime_state.json"
path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text("{not json", encoding="utf-8")
+ path.write_text(contents, encoding="utf-8")
+ read_calls: list[str] = []
- rp, rb, ro = _readers(positions=[{"symbol": "NVDA", "qty": 1}])
- report = reconcile("robinhood", rp, rb, ro)
+ def read_positions() -> list[dict[str, Any]]:
+ read_calls.append("positions")
+ return [{"symbol": "NVDA", "qty": 1}]
- assert report.had_prior_state is False # corrupt -> cold start
- assert report.is_safe is True
- corrupt = list(path.parent.glob("runtime_state.json.corrupt-*"))
- assert corrupt, "corrupt state file should be renamed aside"
- assert path.is_file() # a fresh clean state was written
+ def read_balance() -> dict[str, Any]:
+ read_calls.append("balance")
+ return {"cash_usd": 10_000.0}
+
+ def read_orders() -> list[dict[str, Any]]:
+ read_calls.append("orders")
+ return []
+
+ for _ in range(2):
+ with pytest.raises(CorruptRuntimeState, match="runtime_state.json"):
+ reconcile("robinhood", read_positions, read_balance, read_orders)
+
+ assert read_calls == []
+ assert path.read_text(encoding="utf-8") == contents
+ assert list(path.parent.glob("runtime_state.json.corrupt-*")) == []