Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(live): episode-key the sweep claim — orphan claims never block future trips

cgycoreybf0895e7a937
diff --git a/agent/src/live/runtime/runner.py b/agent/src/live/runtime/runner.py
index 7ef8decaa..6fa4a2c79 100644
--- a/agent/src/live/runtime/runner.py
+++ b/agent/src/live/runtime/runner.py
@@ -48,6 +48,7 @@ from src.live.runtime.flatten import flatten_and_cancel
from src.live.runtime.jobstore import JobStore
from src.live.runtime.sweep_latch import (
claim_sweep,
+ halt_episode,
mark_sweep_fired,
release_claim,
sweep_already_fired,
@@ -610,9 +611,11 @@ class LiveRunner:
if sweep_already_fired(self.broker):
self._flatten_fired = True
return
- 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.
+ if not claim_sweep(self.broker, halt_episode(self.broker) or "unknown"):
+ # Another process holds this episode's claim (or a crash left it
+ # behind): the outcome is unknowable — re-sweeping could duplicate
+ # a close. Claims are episode-keyed, so this never blocks a future
+ # trip of the same broker.
self._flatten_fired = True
logger.warning(
"preemptive sweep already claimed for %s — skipping (another "
@@ -698,7 +701,7 @@ class LiveRunner:
error=str(exc),
)
finally:
- release_claim(self.broker)
+ release_claim(self.broker, halt_episode(self.broker) or "unknown")
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 7d937c33f..b69aebc08 100644
--- a/agent/src/live/runtime/sweep_latch.py
+++ b/agent/src/live/runtime/sweep_latch.py
@@ -21,6 +21,7 @@ the current-episode lookup — the global HALT is authoritative
from __future__ import annotations
+import hashlib
import json
import os
import tempfile
@@ -40,27 +41,44 @@ 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 halt_episode(broker: str) -> str | None:
+ """Return the identity of the newest tripped halt episode (public alias)."""
+ return _halt_episode(broker)
-def claim_sweep(broker: str) -> bool:
- """Atomically claim the sweep for ``broker`` — exclusive between processes.
+def _claim_filename(episode: str) -> str:
+ digest = hashlib.sha256(episode.encode("utf-8")).hexdigest()[:16]
+ return f"{_CLAIM_FILENAME}-{digest}"
- ``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
+
+def claim_path(broker: str, episode: str) -> Path:
+ """Return the per-broker, per-episode sweep-claim path.
+
+ Claims are keyed by halt episode, so an orphaned claim from a crash can
+ only ever block its OWN episode — never a future trip of the same broker
+ (each new halt episode gets its own claim namespace).
+ """
+ return broker_dir(broker) / _claim_filename(episode)
+
+
+def claim_sweep(broker: str, episode: str) -> bool:
+ """Atomically claim the sweep for ``broker``'s ``episode`` — exclusive between processes.
+
+ ``O_CREAT | O_EXCL`` guarantees a single winner even when two runners
+ start simultaneously for the same episode: 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 that episode's outcome is
*unknowable*: re-sweeping could duplicate a close, so the runner skips and
- surfaces the claim for operator resolution (documented recovery).
+ surfaces the claim for operator resolution. Because the claim is bound to
+ the episode, a stale claim never blocks a later episode.
Returns:
``True`` if this process now owns the sweep; ``False`` when a claim
- already exists (another runner active, or a crashed prior run).
+ already exists for the same episode (another runner active, or a
+ crashed prior run).
"""
- path = claim_path(broker)
+ path = claim_path(broker, episode)
path.parent.mkdir(parents=True, exist_ok=True)
try:
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
@@ -71,6 +89,7 @@ def claim_sweep(broker: str) -> bool:
json.dump(
{
"claimed_at": datetime.now(timezone.utc).isoformat(),
+ "episode": episode,
"pid": os.getpid(),
},
f,
@@ -84,10 +103,10 @@ def claim_sweep(broker: str) -> bool:
return True
-def release_claim(broker: str) -> None:
- """Drop this process's sweep claim (no-op when the file is absent)."""
+def release_claim(broker: str, episode: str) -> None:
+ """Drop this process's sweep claim for ``episode`` (no-op when absent)."""
try:
- claim_path(broker).unlink()
+ claim_path(broker, episode).unlink()
except OSError:
pass
diff --git a/agent/tests/test_sweep_latch.py b/agent/tests/test_sweep_latch.py
index 873dac072..022b90ae8 100644
--- a/agent/tests/test_sweep_latch.py
+++ b/agent/tests/test_sweep_latch.py
@@ -253,11 +253,27 @@ def test_side_effect_attempted_latches_even_with_read_error(
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)
+ ep = "2026-08-27T01:00:00+00:00"
+ assert sweep_latch.claim_sweep(BROKER, ep) is True # first wins
+ assert sweep_latch.claim_sweep(BROKER, ep) is False # second cannot claim
+ sweep_latch.release_claim(BROKER, ep)
+ assert sweep_latch.claim_sweep(BROKER, ep) is True # claimable again
+ sweep_latch.release_claim(BROKER, ep)
+
+
+def test_orphan_claim_does_not_block_future_episode(live_root: Path) -> None:
+ # Crash mid-sweep leaves a claim for episode 1 (never released). An
+ # episode-keyed claim must NOT block episode 2: each trip gets its own
+ # claim namespace, so a new halt still sweeps.
+ _trip_with_timestamp(BROKER, "2026-08-27T01:00:00+00:00")
+ ep1 = sweep_latch.halt_episode(BROKER)
+ assert sweep_latch.claim_sweep(BROKER, ep1) is True # crashed: never released
+ clear_halt(BROKER)
+ _trip_with_timestamp(BROKER, "2026-08-27T10:00:00+00:00")
+ ep2 = sweep_latch.halt_episode(BROKER)
+ assert ep2 != ep1
+ assert sweep_latch.claim_sweep(BROKER, ep2) is True # new episode claimable
+ sweep_latch.release_claim(BROKER, ep2)
def test_runner_skips_when_claim_held_by_other_process(live_root: Path) -> None:
@@ -265,12 +281,16 @@ def test_runner_skips_when_claim_held_by_other_process(live_root: Path) -> None:
# (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
+ ep = sweep_latch.halt_episode(BROKER)
+ assert sweep_latch.claim_sweep(BROKER, ep) 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)
+ # The other process's claim must remain untouched (the runner must never
+ # release a claim it does not own).
+ assert sweep_latch.claim_path(BROKER, "2026-08-27T01:00:00+00:00").exists()
+ sweep_latch.release_claim(BROKER, ep)
def test_runner_claims_and_releases_around_sweep(live_root: Path) -> None:
@@ -280,7 +300,8 @@ def test_runner_claims_and_releases_around_sweep(live_root: Path) -> None:
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()
+ ep = sweep_latch.halt_episode(BROKER)
+ assert not sweep_latch.claim_path(BROKER, ep).exists()
def test_runner_claim_released_after_read_failure(live_root: Path) -> None:
@@ -293,5 +314,6 @@ def test_runner_claim_released_after_read_failure(live_root: Path) -> None:
asyncio.run(_build_runner(live_root, fired, _flatten).run_once())
assert fired == [BROKER]
- assert not sweep_latch.claim_path(BROKER).exists()
+ ep = sweep_latch.halt_episode(BROKER)
+ assert not sweep_latch.claim_path(BROKER, ep).exists()
assert not sweep_latch.latch_path(BROKER).exists()