Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(live): inter-process sweep claim, durable-write audit, nested broker errors

cgycoreyf81cb723dd8d
diff --git a/agent/src/live/runtime/flatten.py b/agent/src/live/runtime/flatten.py
index 0329aec45..4780e5c04 100644
--- a/agent/src/live/runtime/flatten.py
+++ b/agent/src/live/runtime/flatten.py
@@ -403,9 +403,27 @@ def _error_envelope_message(response: Any) -> str | None:
dict is not proof the broker accepted the request. Treating that
envelope as success would audit a resting order as cancelled while it
stays live, which is the failure the sweep exists to prevent.
+
+ A *nested* broker-level failure is just as dangerous: the MCP transport
+ succeeded, but the connector/broker rejected the order inside its own
+ payload (``{"status": "ok", "data": {"status": "error", ...}}`` or
+ ``{"status": "ok", "data": {"ok": False, ...}}``). Only the top level was
+ checked before, so such a rejection was recorded as accepted and the
+ sweep latched with a live order still resting.
"""
- if isinstance(response, dict) and response.get("status") == "error":
- return str(response.get("error") or "broker returned an error envelope")
+ if isinstance(response, dict):
+ if response.get("status") == "error":
+ return str(response.get("error") or "broker returned an error envelope")
+ data = response.get("data")
+ if isinstance(data, dict):
+ if data.get("status") == "error":
+ return str(data.get("error") or "broker returned an error envelope")
+ if data.get("ok") is False:
+ return str(
+ data.get("error")
+ or data.get("message")
+ or "broker rejected the request"
+ )
return None
diff --git a/agent/src/live/runtime/runner.py b/agent/src/live/runtime/runner.py
index aa0afddb5..7ef8decaa 100644
--- a/agent/src/live/runtime/runner.py
+++ b/agent/src/live/runtime/runner.py
@@ -46,7 +46,12 @@ from src.live.mandate.model import Mandate
from src.live.mandate.store import load_mandate
from src.live.runtime.flatten import flatten_and_cancel
from src.live.runtime.jobstore import JobStore
-from src.live.runtime.sweep_latch import mark_sweep_fired, sweep_already_fired
+from src.live.runtime.sweep_latch import (
+ claim_sweep,
+ mark_sweep_fired,
+ release_claim,
+ sweep_already_fired,
+)
from src.live.runtime.liveness import write_heartbeat
from src.live.runtime.scheduler import Job
from src.live.runtime.triggers import Trigger
@@ -586,65 +591,114 @@ class LiveRunner:
write — even one that errors, and even when a later read phase fails —
latches: those are the non-idempotent cases SPEC §8.5 protects. A
sweep that raises outright latches too (side effects may have begun).
+
+ Inter-process safety: the whole check -> sweep -> durable-record
+ window runs under an exclusive disk claim (``FLATTEN_CLAIM``,
+ :func:`sweep_latch.claim_sweep`). A second runner process for the
+ same broker cannot sweep concurrently — both would see
+ ``sweep_already_fired`` false (check-then-act) and duplicate closes.
+ When a claim is already held (another runner active, or a prior
+ process crashed mid-sweep), the episode is treated as *unknowable*:
+ never re-sweep, audit for operator resolution, and leave the HALT
+ tripped. The claim is released in ``finally`` on every path. A failed
+ durable latch write (fs error after side effects) is audited
+ explicitly — the in-process flag still protects this process, but the
+ operator is told a restart may replay.
"""
if self._flatten_fired or self._submit_fn is None:
return
if sweep_already_fired(self.broker):
self._flatten_fired = True
return
- try:
- report = self._flatten_fn(
- self.broker,
- self._submit_fn,
- self._read_positions,
- self._read_open_orders,
- )
- except Exception as exc: # noqa: BLE001 — surfaced via audit, never retried
- # Unknown failure: cancel/flatten side effects may have begun and
- # are not retryable — latch so a restart does not replay closes.
+ if not claim_sweep(self.broker):
+ # Another process holds the claim (or a crash left it behind):
+ # the outcome is unknowable — re-sweeping could duplicate a close.
self._flatten_fired = True
- mark_sweep_fired(self.broker)
- logger.exception("preemptive flatten failed for %s", self.broker)
- self._audit(
- kind="breach",
- outcome="error",
- intent="preemptive halt sweep failed — not retried (no-retry §8.5)",
- error=str(exc),
- )
- return
- report = report or {}
- read_errors = [
- entry
- for entry in report.get("errors", [])
- if isinstance(entry, dict)
- and entry.get("phase") in ("read_open_orders", "read_positions")
- ]
- if read_errors:
- detail = "; ".join(str(entry.get("error")) for entry in read_errors)
logger.warning(
- "preemptive sweep read failure for %s during execution: %s",
+ "preemptive sweep already claimed for %s — skipping (another "
+ "runner active, or a crash left FLATTEN_CLAIM behind); operator "
+ "resolution required",
self.broker,
- detail,
)
- if not report.get("side_effects_attempted"):
- # No cancel or close was attempted → nothing happened that a
- # later tick (or a restart) must not repeat. Do NOT latch: the
- # sweep retries for this episode.
- if read_errors:
- detail = "; ".join(str(e.get("error")) for e in read_errors)
- intent = "preemptive halt sweep read failed — retrying on next tick"
- else:
- detail = "no open orders or positions to act on"
- intent = "preemptive halt sweep found nothing to act on — re-checking on next tick"
self._audit(
kind="breach",
outcome="error",
- intent=intent,
- error=detail,
+ intent="preemptive halt sweep skipped — claim held by another process; operator resolution required",
+ error="FLATTEN_CLAIM present for this episode",
)
return
- self._flatten_fired = True
- mark_sweep_fired(self.broker)
+ try:
+ try:
+ report = self._flatten_fn(
+ self.broker,
+ self._submit_fn,
+ self._read_positions,
+ self._read_open_orders,
+ )
+ except Exception as exc: # noqa: BLE001 — surfaced via audit, never retried
+ # Unknown failure: cancel/flatten side effects may have begun
+ # and are not retryable — latch so a restart does not replay.
+ self._flatten_fired = True
+ mark_sweep_fired(self.broker)
+ logger.exception("preemptive flatten failed for %s", self.broker)
+ self._audit(
+ kind="breach",
+ outcome="error",
+ intent="preemptive halt sweep failed — not retried (no-retry §8.5)",
+ error=str(exc),
+ )
+ return
+ report = report or {}
+ read_errors = [
+ entry
+ for entry in report.get("errors", [])
+ if isinstance(entry, dict)
+ and entry.get("phase") in ("read_open_orders", "read_positions")
+ ]
+ if read_errors:
+ detail = "; ".join(str(entry.get("error")) for entry in read_errors)
+ logger.warning(
+ "preemptive sweep read failure for %s during execution: %s",
+ self.broker,
+ detail,
+ )
+ if not report.get("side_effects_attempted"):
+ # No cancel or close was attempted → nothing happened that a
+ # later tick (or a restart) must not repeat. Do NOT latch: the
+ # sweep retries for this episode.
+ if read_errors:
+ detail = "; ".join(str(e.get("error")) for e in read_errors)
+ intent = "preemptive halt sweep read failed — retrying on next tick"
+ else:
+ detail = "no open orders or positions to act on"
+ intent = "preemptive halt sweep found nothing to act on — re-checking on next tick"
+ self._audit(
+ kind="breach",
+ outcome="error",
+ intent=intent,
+ error=detail,
+ )
+ return
+ self._flatten_fired = True
+ try:
+ mark_sweep_fired(self.broker)
+ except Exception as exc: # noqa: BLE001 — persistence must not be silent
+ # Durability failure AFTER a broker write: the in-memory flag
+ # protects this process, but a restart sees no latch and could
+ # replay the close. Say so — recovery is operator's.
+ logger.exception(
+ "durable sweep latch write failed for %s — restart may "
+ "replay the sweep; verify broker state",
+ self.broker,
+ )
+ self._audit(
+ kind="breach",
+ outcome="error",
+ intent="durable sweep latch write failed — restart may replay; verify broker state",
+ error=str(exc),
+ )
+ finally:
+ release_claim(self.broker)
def _no_mandate_result(self) -> dict[str, Any]:
"""Audit + return the result when no valid mandate is on file."""
diff --git a/agent/src/live/runtime/sweep_latch.py b/agent/src/live/runtime/sweep_latch.py
index 12d3a760f..7d937c33f 100644
--- a/agent/src/live/runtime/sweep_latch.py
+++ b/agent/src/live/runtime/sweep_latch.py
@@ -32,6 +32,7 @@ from src.live.halt import broker_halt_path, halt_path, read_halt
from src.live.paths import broker_dir
_LATCH_FILENAME = "FLATTEN_FIRED"
+_CLAIM_FILENAME = "FLATTEN_CLAIM"
def latch_path(broker: str) -> Path:
@@ -39,6 +40,58 @@ def latch_path(broker: str) -> Path:
return broker_dir(broker) / _LATCH_FILENAME
+def claim_path(broker: str) -> Path:
+ """Return the per-broker sweep-claim path (holds the inter-process claim)."""
+ return broker_dir(broker) / _CLAIM_FILENAME
+
+
+def claim_sweep(broker: str) -> bool:
+ """Atomically claim the sweep for ``broker`` — exclusive between processes.
+
+ ``O_CREAT | O_EXCL`` guarantees a single winner even when two runner
+ processes start simultaneously: the loser of the race sees the claim file
+ and must NOT sweep (the duplicate-close hazard the latch exists to
+ prevent). The claim covers the whole check -> sweep -> durable-record
+ window. A claim left behind by a crash means the episode's outcome is
+ *unknowable*: re-sweeping could duplicate a close, so the runner skips and
+ surfaces the claim for operator resolution (documented recovery).
+
+ Returns:
+ ``True`` if this process now owns the sweep; ``False`` when a claim
+ already exists (another runner active, or a crashed prior run).
+ """
+ path = claim_path(broker)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
+ except FileExistsError:
+ return False
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
+ json.dump(
+ {
+ "claimed_at": datetime.now(timezone.utc).isoformat(),
+ "pid": os.getpid(),
+ },
+ f,
+ )
+ except Exception:
+ try:
+ os.unlink(path)
+ except OSError:
+ pass
+ raise # claim could not be recorded; caller decides (fail-closed)
+ return True
+
+
+def release_claim(broker: str) -> None:
+ """Drop this process's sweep claim (no-op when the file is absent)."""
+ try:
+ claim_path(broker).unlink()
+ except OSError:
+ pass
+
+
def _halt_episode(broker: str) -> str | None:
"""Return the identity of the *newest* tripped halt episode, if any.
diff --git a/agent/tests/test_runtime_flatten.py b/agent/tests/test_runtime_flatten.py
index e67c5f4a2..b61d404be 100644
--- a/agent/tests/test_runtime_flatten.py
+++ b/agent/tests/test_runtime_flatten.py
@@ -437,3 +437,58 @@ def test_error_envelope_flatten_is_not_a_success(live_runtime: Path) -> None:
"error": "connection reset while cancelling NVDA",
}
]
+
+
+def test_nested_broker_error_cancel_is_not_a_success(live_runtime: Path) -> None:
+ # MCP transport succeeded but the broker rejected inside its own payload
+ # ({"status": "ok", "data": {"status": "error", ...}}): the order stays
+ # live, so it must NOT be recorded as cancelled.
+ broker = _Broker(open_orders=[{"order_id": "o1"}, {"order_id": "o2"}], positions=[])
+ real_submit = broker.submit
+
+ def submit(request: dict[str, Any]) -> dict[str, Any]:
+ if request.get("order_id") == "o1":
+ return {
+ "status": "ok",
+ "data": {"status": "error", "error": "broker rejected o1"},
+ }
+ return real_submit(request)
+
+ report = flatten.flatten_and_cancel(
+ "robinhood", submit, broker.read_positions, broker.read_open_orders
+ )
+ assert report["cancelled_order_ids"] == ["o2"] # only the accepted one
+ assert {
+ "phase": "cancel",
+ "order_id": "o1",
+ "error": "broker rejected o1",
+ } in report["errors"]
+ assert report["side_effects_attempted"] is True # submitted, just rejected
+
+
+def test_nested_broker_error_flatten_is_not_a_success(live_runtime: Path) -> None:
+ broker = _Broker(open_orders=[], positions=[{"symbol": "NVDA", "qty": 3}])
+ real_submit = broker.submit
+
+ def submit(request: dict[str, Any]) -> dict[str, Any]:
+ if request.get("symbol") == "NVDA":
+ return {
+ "status": "ok",
+ "data": {"ok": False, "message": "insufficient buying power"},
+ }
+ return real_submit(request)
+
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ submit,
+ broker.read_positions,
+ broker.read_open_orders,
+ allow_flatten=True,
+ )
+ assert report["flatten_orders_submitted"] == []
+ assert {
+ "phase": "flatten",
+ "symbol": "NVDA",
+ "error": "insufficient buying power",
+ } in report["errors"]
+ assert report["side_effects_attempted"] is True
diff --git a/agent/tests/test_sweep_latch.py b/agent/tests/test_sweep_latch.py
index 0853d08ad..873dac072 100644
--- a/agent/tests/test_sweep_latch.py
+++ b/agent/tests/test_sweep_latch.py
@@ -245,3 +245,53 @@ def test_side_effect_attempted_latches_even_with_read_error(
# Restart: the on-disk latch suppresses the duplicate close.
asyncio.run(_build_runner(live_root, fired, _flatten).run_once())
assert fired == [BROKER]
+
+
+# ---------------------------------------------------------------------------
+# Inter-process claim protocol (#1244 hardening)
+# ---------------------------------------------------------------------------
+
+
+def test_claim_is_exclusive_and_releasable(live_root: Path) -> None:
+ assert sweep_latch.claim_sweep(BROKER) is True # first wins
+ assert sweep_latch.claim_sweep(BROKER) is False # second cannot claim
+ sweep_latch.release_claim(BROKER)
+ assert sweep_latch.claim_sweep(BROKER) is True # claimable again
+ sweep_latch.release_claim(BROKER)
+
+
+def test_runner_skips_when_claim_held_by_other_process(live_root: Path) -> None:
+ # A second runner for the same broker must not sweep concurrently
+ # (check-then-act would let both pass sweep_already_fired and duplicate
+ # market closes). The held claim forces this process to skip + audit.
+ _trip_with_timestamp(BROKER, "2026-08-27T01:00:00+00:00")
+ assert sweep_latch.claim_sweep(BROKER) is True # "other" process holds it
+ fired: list[str] = []
+ asyncio.run(_build_runner(live_root, fired).run_once())
+ assert fired == [] # never swept
+ assert not sweep_latch.latch_path(BROKER).exists()
+ sweep_latch.release_claim(BROKER)
+
+
+def test_runner_claims_and_releases_around_sweep(live_root: Path) -> None:
+ _trip_with_timestamp(BROKER, "2026-08-27T01:00:00+00:00")
+ fired: list[str] = []
+ asyncio.run(_build_runner(live_root, fired).run_once())
+ assert fired == [BROKER]
+ # The claim must be released after the sweep (crash-free path), so a
+ # later re-check can claim again.
+ assert not sweep_latch.claim_path(BROKER).exists()
+
+
+def test_runner_claim_released_after_read_failure(live_root: Path) -> None:
+ _trip_with_timestamp(BROKER, "2026-08-27T01:00:00+00:00")
+ fired: list[str] = []
+
+ def _flatten(broker, submit, read_positions, read_open_orders):
+ fired.append(broker)
+ return {"errors": [{"phase": "read_positions", "error": "read failed"}]}
+
+ asyncio.run(_build_runner(live_root, fired, _flatten).run_once())
+ assert fired == [BROKER]
+ assert not sweep_latch.claim_path(BROKER).exists()
+ assert not sweep_latch.latch_path(BROKER).exists()