"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(live): record all active halt episodes; wrap latch write in double-failure branch
cgycoreyf1f1b6ccb34b
diff --git a/agent/src/live/runtime/runner.py b/agent/src/live/runtime/runner.pyindex 6fa4a2c79..8739e358b 100644--- a/agent/src/live/runtime/runner.py+++ b/agent/src/live/runtime/runner.py@@ -642,14 +642,31 @@ class LiveRunner:# 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),- )+ try:+ mark_sweep_fired(self.broker)+ except Exception as persist_exc: # noqa: BLE001 — double failure+ # Both the sweep AND the durable latch write failed: the+ # in-memory flag still shields this process, and the+ # operator must know a restart may replay.+ logger.exception(+ "durable sweep latch write failed for %s while the sweep "+ "itself failed — restart may replay; verify broker state",+ self.broker,+ )+ self._audit(+ kind="breach",+ outcome="error",+ intent="durable sweep latch write failed during sweep failure — restart may replay; verify broker state",+ error=f"sweep: {exc}; latch: {persist_exc}",+ )+ else:+ 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),+ )returnreport = report or {}read_errors = [diff --git a/agent/src/live/runtime/sweep_latch.py b/agent/src/live/runtime/sweep_latch.pyindex b69aebc08..3b16df5c1 100644--- a/agent/src/live/runtime/sweep_latch.py+++ b/agent/src/live/runtime/sweep_latch.py@@ -111,6 +111,54 @@ def release_claim(broker: str, episode: str) -> None:pass+def _sentinel_identity(path: Path, payload: dict[str, Any]) -> tuple[int, str] | None:+ """Return ``(instant_ns, identity)`` for one halt sentinel, or ``None``.++ ``tripped_at`` is the identity when the sentinel carries a parseable one;+ a hand-touched/malformed sentinel falls back to its file mtime (which+ still changes on every fresh ``touch``). Ranking by mtime alone is not+ safe — two sentinels written within one filesystem timestamp quantum+ share an mtime — so ``tripped_at`` wins whenever present.+ """+ try:+ mtime_ns = path.stat().st_mtime_ns+ except OSError:+ return None+ tripped_at = payload.get("tripped_at")+ if tripped_at:+ try:+ trip = datetime.fromisoformat(str(tripped_at))+ if trip.tzinfo is None:+ trip = trip.replace(tzinfo=timezone.utc)+ return int(trip.timestamp() * 1_000_000_000), str(tripped_at)+ except ValueError:+ pass+ return mtime_ns, f"mtime:{mtime_ns}"+++def _active_episodes(broker: str) -> list[str]:+ """Return the identity of EVERY currently tripped halt episode.++ Both the per-broker and the global sentinel can be tripped at the same+ time, and both are live until their sentinel is cleared. Recording the+ sweep as fired only for its *newest* episode leaves the other active one+ unrecorded: clearing the recorded halt would re-fire the sweep while the+ other halt is still tripped. Both identities must therefore be latched+ together.+ """+ identities: list[str] = []+ for path, payload in (+ (broker_halt_path(broker), read_halt(broker)),+ (halt_path(), read_halt()),+ ):+ if payload is None:+ continue+ resolved = _sentinel_identity(path, payload)+ if resolved is not None:+ identities.append(resolved[1])+ return identities++def _halt_episode(broker: str) -> str | None:"""Return the identity of the *newest* tripped halt episode, if any.@@ -118,13 +166,7 @@ def _halt_episode(broker: str) -> str | None:times. The global HALT is authoritative (``halt_flag_set`` halts everychannel), but a stale per-broker episode must not suppress the sweep fora newer global trip — nor an older global trip override a newer- per-broker one. The newest sentinel therefore wins, ranked by its- explicit ``tripped_at`` payload when it carries one; the file mtime is- used only as the fallback for hand-touched/malformed sentinels without- a parseable ``tripped_at``. Ranking by mtime alone is not safe: two- sentinels written within one filesystem timestamp quantum share an- mtime, and the order would silently follow directory iteration instead- of trip time.+ per-broker one. The newest sentinel therefore wins."""candidates: list[tuple[int, str]] = []for path, payload in (@@ -133,25 +175,9 @@ def _halt_episode(broker: str) -> str | None:):if payload is None:continue- try:- mtime_ns = path.stat().st_mtime_ns- except OSError:- continue- tripped_at = payload.get("tripped_at")- if tripped_at:- try:- trip = datetime.fromisoformat(str(tripped_at))- if trip.tzinfo is None:- trip = trip.replace(tzinfo=timezone.utc)- instant_ns = int(trip.timestamp() * 1_000_000_000)- identity = str(tripped_at)- except ValueError:- instant_ns = mtime_ns- identity = f"mtime:{mtime_ns}"- else:- instant_ns = mtime_ns- identity = f"mtime:{mtime_ns}"- candidates.append((instant_ns, identity))+ resolved = _sentinel_identity(path, payload)+ if resolved is not None:+ candidates.append(resolved)if not candidates:return Nonereturn max(candidates, key=lambda item: item[0])[1]@@ -175,16 +201,23 @@ def sweep_already_fired(broker: str) -> bool:def mark_sweep_fired(broker: str) -> None:- """Record that the sweep fired for the current halt episode.+ """Record that the sweep fired for the currently tripped halt episodes.Atomic write (same-directory temp file + ``os.replace``), same contractas the HALT sentinel. A no-op when no halt is tripped, since there is noepisode to bind the record to. The record accumulates every episode thesweep has fired for on this broker (``episodes``), so clearing one haltnever re-fires the sweep for an older episode that was already swept.++ Both the per-broker and the global sentinel may be tripped at the same+ time: the sweep covers the halt state as a whole, so EVERY currently+ active episode identity is recorded together. Recording only the newest+ would leave the older still-active halt unrecorded — clearing the newer+ would then re-fire the sweep while the other halt remains tripped+ (redundant no-op re-sweep and audit noise)."""- episode = _halt_episode(broker)- if episode is None:+ active = _active_episodes(broker)+ if not active:returnpath = latch_path(broker)path.parent.mkdir(parents=True, exist_ok=True)@@ -198,9 +231,13 @@ def mark_sweep_fired(broker: str) -> None:except (OSError, json.JSONDecodeError):passepisodes = record.setdefault("episodes", [])- if episode not in episodes:- episodes.append(episode)- record["episode"] = episode # legacy field kept pointing at the latest+ to_write = bool(episodes)+ for episode in active:+ if episode not in episodes:+ episodes.append(episode)+ to_write = True+ if to_write:+ record["episode"] = _halt_episode(broker) # legacy field = newestrecord["fired_at"] = datetime.now(timezone.utc).isoformat()fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".flatten-fired-")try:diff --git a/agent/tests/test_sweep_latch.py b/agent/tests/test_sweep_latch.pyindex 022b90ae8..6be6e2342 100644--- a/agent/tests/test_sweep_latch.py+++ b/agent/tests/test_sweep_latch.py@@ -317,3 +317,44 @@ def test_runner_claim_released_after_read_failure(live_root: Path) -> None:ep = sweep_latch.halt_episode(BROKER)assert not sweep_latch.claim_path(BROKER, ep).exists()assert not sweep_latch.latch_path(BROKER).exists()+++def test_mark_records_both_active_episodes_older_global_newer_broker(+ live_root: Path,+) -> None:+ # Reviewer residual A: the sweep covers the halt state as a whole — with+ # an older global AND a newer broker halt both active, clearing the+ # broker halt must NOT re-fire the sweep while the (still active, older)+ # global halt remains tripped. mark_sweep_fired must record BOTH+ # episodes.+ _trip_with_timestamp(None, "2026-08-27T01:00:00+00:00") # global, older+ _trip_with_timestamp(BROKER, "2026-08-27T10:00:00+00:00") # broker, newer+ sweep_latch.mark_sweep_fired(BROKER)+ assert sweep_latch.sweep_already_fired(BROKER) is True++ clear_halt(BROKER) # newer (broker) halt cleared+ assert sweep_latch.sweep_already_fired(BROKER) is True # global still recorded+++def test_double_failure_latch_write_does_not_escape_run_once(+ live_root: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ # Reviewer residual B: sweep raises AND the durable latch write raises.+ # Neither exception may escape run_once — the tick must still complete+ # with the halted outcome and an audit trail.+ from src.live.runtime import runner as runner_mod++ _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)+ raise RuntimeError("sweep exploded")++ def _broken_mark(broker):+ raise RuntimeError("disk exploded")++ monkeypatch.setattr(runner_mod, "mark_sweep_fired", _broken_mark)+ result = asyncio.run(_build_runner(live_root, fired, _flatten).run_once())+ assert result["outcome"] == "halted" # did not escape+ assert fired == [BROKER]