Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(live): harden the preemptive halt sweep against ledger failures and malformed broker records

Romzhouc312d5cb01f2
diff --git a/agent/src/live/runtime/flatten.py b/agent/src/live/runtime/flatten.py
index 4780e5c04..303d5c4a2 100644
--- a/agent/src/live/runtime/flatten.py
+++ b/agent/src/live/runtime/flatten.py
@@ -37,6 +37,7 @@ BEFORE the report is returned, so the preemptive sweep is fully reconstructable.
from __future__ import annotations
import logging
+import math
from typing import Any, Callable
from src.live.audit import LiveActionEvent, write_live_action
@@ -259,6 +260,19 @@ def _cancel_resting_orders(
)
continue
order_id = order.get("order_id")
+ if not isinstance(order_id, str) or not order_id.strip():
+ # A cancel request is keyed entirely by order_id. Without a usable
+ # one the broker call is meaningless, yet a non-error envelope would
+ # be recorded as a cancellation of a real order that is still
+ # resting. Record it and move on — no side effect is attempted, so
+ # side_effects_attempted must stay as-is.
+ report["errors"].append(
+ {
+ "phase": "cancel",
+ "error": f"missing or invalid order_id: {order_id!r}",
+ }
+ )
+ continue
request = {"action": "cancel", "order_id": order_id}
report["side_effects_attempted"] = True
try:
@@ -336,8 +350,17 @@ def _flatten_open_positions(
)
continue
symbol = position.get("symbol")
- qty = float(position.get("qty", 0) or 0)
- if qty == 0:
+ qty = _coerce_position_qty(position.get("qty"))
+ if qty is None:
+ report["errors"].append(
+ {
+ "phase": "flatten",
+ "symbol": symbol,
+ "error": f"invalid or missing position qty: {position.get('qty')!r}",
+ }
+ )
+ continue
+ if qty == 0.0:
continue
side = "sell" if qty > 0 else "buy"
close_qty = abs(qty)
@@ -395,6 +418,31 @@ def _flatten_open_positions(
)
+def _coerce_position_qty(raw: Any) -> float | None:
+ """Parse a broker position ``qty`` into a finite float, or ``None``.
+
+ The signed quantity decides the close side and size, so it must be a real
+ finite number. A bare ``float()`` cannot be trusted here: a non-numeric or
+ non-finite value (``"n/a"``, a dict, ``nan``, ``inf``) either raises out of
+ the sweep loop — aborting every remaining position on this trip — or, worse,
+ slips past ``qty == 0`` / ``qty > 0`` with ``nan`` and submits a real market
+ order of NaN shares. Booleans are rejected too: ``float(True)`` is ``1.0``,
+ which would close one share off a malformed record.
+
+ Returns:
+ The signed quantity as a float, ``0.0`` for a genuine zero position, or
+ ``None`` when the value is absent, malformed, or non-finite (the caller
+ records it in ``report["errors"]`` and moves on to the next position).
+ """
+ if raw is None or isinstance(raw, bool):
+ return None
+ try:
+ qty = float(raw)
+ except (TypeError, ValueError):
+ return None
+ return qty if math.isfinite(qty) else None
+
+
def _error_envelope_message(response: Any) -> str | None:
"""Return the error string when a broker call failed via envelope.
@@ -448,6 +496,16 @@ def _audit(
) -> None:
"""Append one redacted live-action record for a sweep broker call.
+ Fail-safe: an audit write must never abort the sweep. The ledger write does
+ real I/O (``mkdir`` / ``json.dumps`` / ``open`` / ``write``), any of which can
+ raise on a bad record or a failing disk — and an exception escaping here
+ propagates out of ``flatten_and_cancel`` into the runner, which then latches
+ the sweep permanently (``mark_sweep_fired``) so no further cancel or flatten
+ ever runs, for this process or any restart. A dropped audit line is a
+ detectable gap; a permanently disabled kill-switch is not. This mirrors the
+ chain-ledger branch of :func:`src.live.audit.write_live_action`, which states
+ the same policy for the same reason.
+
Args:
broker: Broker key (stamped as ``server``).
remote_tool: Broker remote tool invoked (``cancel_order`` | ``place_order``).
@@ -457,16 +515,26 @@ def _audit(
outcome: ``"accepted"`` on success, ``"error"`` on failure.
error: Error string when ``outcome == "error"``, else ``None``.
"""
- write_live_action(
- LiveActionEvent(
- kind="order_placed" if outcome == "accepted" else "order_rejected",
- session_id=_RUNTIME_SESSION_ID,
- outcome=outcome, # type: ignore[arg-type]
- server=broker,
- remote_tool=remote_tool,
- intent_normalized=intent,
- broker_request=request,
- broker_response=response,
- error=error,
+ try:
+ write_live_action(
+ LiveActionEvent(
+ kind="order_placed" if outcome == "accepted" else "order_rejected",
+ session_id=_RUNTIME_SESSION_ID,
+ outcome=outcome, # type: ignore[arg-type]
+ server=broker,
+ remote_tool=remote_tool,
+ intent_normalized=intent,
+ broker_request=request,
+ broker_response=response,
+ error=error,
+ )
+ )
+ except Exception as exc: # noqa: BLE001 — a logging fault must not stop the sweep
+ logger.exception(
+ "live preemptive sweep audit write failed (%s: %s) for %s/%s; the "
+ "broker call itself is unaffected and the sweep continues",
+ type(exc).__name__,
+ exc,
+ broker,
+ remote_tool,
)
- )
diff --git a/agent/tests/test_runtime_flatten.py b/agent/tests/test_runtime_flatten.py
index b61d404be..8dc728023 100644
--- a/agent/tests/test_runtime_flatten.py
+++ b/agent/tests/test_runtime_flatten.py
@@ -492,3 +492,136 @@ def test_nested_broker_error_flatten_is_not_a_success(live_runtime: Path) -> Non
"error": "insufficient buying power",
} in report["errors"]
assert report["side_effects_attempted"] is True
+
+
+# --- fail-open hardening on the kill-switch path ---------------------------
+# A failure that only concerns the audit file must not abort the sweep: the
+# runner latches a failed sweep permanently (runner.py:697-726), so an escaping
+# exception here disables the kill-switch for this process and every restart.
+
+
+def test_audit_write_failure_does_not_abort_sweep(
+ live_runtime: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # write_live_action does real I/O (mkdir/json.dumps/open/write); a disk
+ # fault must cost us an audit line, not the sweep.
+ def boom(*args: Any, **kwargs: Any) -> None:
+ raise OSError("no space left on device")
+
+ monkeypatch.setattr(flatten, "write_live_action", boom)
+ broker = _Broker(
+ open_orders=[{"order_id": "o1"}, {"order_id": "o2"}],
+ positions=[{"symbol": "NVDA", "qty": 3}, {"symbol": "AAPL", "qty": -2}],
+ )
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ broker.read_positions,
+ broker.read_open_orders,
+ allow_flatten=True,
+ )
+ # Every order and every position was still acted on despite the audit fault.
+ assert [action for action, _ in broker.calls] == [
+ "cancel",
+ "cancel",
+ "close",
+ "close",
+ ]
+ assert report["cancelled_order_ids"] == ["o1", "o2"]
+ assert [s["symbol"] for s in report["flatten_orders_submitted"]] == [
+ "NVDA",
+ "AAPL",
+ ]
+ assert report["errors"] == []
+ assert report["side_effects_attempted"] is True
+
+
[email protected]("bad_order", [{"order_id": None}, {"order_id": ""}, {"order_id": " "}, {}])
+def test_missing_or_blank_order_id_is_not_submitted(
+ live_runtime: Path, bad_order: dict[str, Any]
+) -> None:
+ # A cancel keyed on a missing/blank id would be recorded as a successful
+ # cancellation of an order that is still resting.
+ broker = _Broker(open_orders=[bad_order, {"order_id": "o2"}], positions=[])
+ report = flatten.flatten_and_cancel(
+ "robinhood", broker.submit, broker.read_positions, broker.read_open_orders
+ )
+ assert broker.calls == [("cancel", {"action": "cancel", "order_id": "o2"})]
+ assert report["cancelled_order_ids"] == ["o2"]
+ assert any(
+ e["phase"] == "cancel" and "missing or invalid order_id" in e["error"]
+ for e in report["errors"]
+ )
+
+
+ "dirty_qty",
+ ["n/a", "", None, float("nan"), float("inf"), {"a": 1}, True],
+ ids=["str", "blank", "none", "nan", "inf", "dict", "bool"],
+)
+def test_dirty_position_qty_is_recorded_and_sweep_continues(
+ live_runtime: Path, dirty_qty: Any
+) -> None:
+ # ValueError/TypeError from a bare float() escaped the loop and left every
+ # later position unflattened; NaN slipped past the zero/sign checks and
+ # reached the broker as a real market order size.
+ broker = _Broker(
+ open_orders=[],
+ positions=[{"symbol": "DIRTY", "qty": dirty_qty}, {"symbol": "NVDA", "qty": 3}],
+ )
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ broker.read_positions,
+ broker.read_open_orders,
+ allow_flatten=True,
+ )
+ assert [
+ r[1]["symbol"] for r in broker.calls if r[0] == "close"
+ ] == ["NVDA"]
+ for request in (r[1] for r in broker.calls):
+ qty = request.get("qty")
+ assert qty is not None and qty > 0
+ assert report["flatten_orders_submitted"] == [
+ {"symbol": "NVDA", "qty": 3.0, "side": "sell", "response": {"state": "accepted", "echo": "NVDA"}}
+ ]
+ assert any(
+ e["phase"] == "flatten"
+ and e["symbol"] == "DIRTY"
+ and "invalid or missing position qty" in e["error"]
+ for e in report["errors"]
+ )
+
+
+def test_missing_qty_field_is_an_error_not_a_silent_zero(
+ live_runtime: Path,
+) -> None:
+ # `float(position.get("qty", 0) or 0)` folded an absent field into a genuine
+ # zero position, so the report looked clean while exposure stayed open.
+ broker = _Broker(open_orders=[], positions=[{"symbol": "NVDA"}])
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ broker.read_positions,
+ broker.read_open_orders,
+ allow_flatten=True,
+ )
+ assert report["flatten_orders_submitted"] == []
+ assert any(
+ e["phase"] == "flatten" and "invalid or missing position qty" in e["error"]
+ for e in report["errors"]
+ )
+
+
+def test_zero_qty_still_skipped_without_error(live_runtime: Path) -> None:
+ # The genuine zero position stays a clean skip — distinct from bad data.
+ broker = _Broker(open_orders=[], positions=[{"symbol": "GME", "qty": 0}])
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ broker.read_positions,
+ broker.read_open_orders,
+ allow_flatten=True,
+ )
+ assert report["flatten_orders_submitted"] == []
+ assert report["errors"] == []