Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(live): reject broker read-error envelopes in the halt sweep

cgycoreyc0dba4f2492d
diff --git a/agent/src/live/runtime/flatten.py b/agent/src/live/runtime/flatten.py
index 2dfa3c796..0329aec45 100644
--- a/agent/src/live/runtime/flatten.py
+++ b/agent/src/live/runtime/flatten.py
@@ -99,16 +99,23 @@ def flatten_and_cancel(
{"symbol": "NVDA", "qty": 3, "side": "sell", "response": {...}},
],
"flatten_skipped_reason": "mandate forbids flatten" | None,
+ "side_effects_attempted": bool, # any cancel/close submit tried
"errors": [ # one per failed broker call
{"phase": "cancel", "order_id": "o2", "error": "..."},
],
}
+
+ ``side_effects_attempted`` is set the moment a cancel or close order
+ submit is attempted (not merely read). The runner uses it to decide
+ whether the sweep's side effects made replay after a restart unsafe
+ (see ``LiveRunner._run_preemptive_sweep``).
"""
report: dict[str, Any] = {
"broker": broker,
"cancelled_order_ids": [],
"flatten_orders_submitted": [],
"flatten_skipped_reason": None,
+ "side_effects_attempted": False,
"errors": [],
}
@@ -151,6 +158,76 @@ def _resolve_allow_flatten(broker: str, allow_flatten: bool | None) -> bool:
return bool(getattr(mandate, "flatten_on_halt", False))
+def _read_broker_state(
+ phase: str,
+ expected_key: str,
+ read_fn: Callable[[], Any],
+ report: dict[str, Any],
+) -> list[Any] | None:
+ """Read broker state for the sweep, or record a structured read error.
+
+ Broker reads are wired to ``MCPServerAdapter.call_tool``, whose contract
+ is: a failed call returns an error envelope (``{"status": "error",
+ "error": ...}``) instead of raising; a successful call returns
+ ``{"status": "ok", "data": <value>}``. ``data`` is either the records
+ list itself or a wrapper dict carrying the pinned per-tool key
+ (``positions`` for a positions read, ``orders`` for an open-orders
+ read). Anything else — an exception, a non-list, a non-``ok`` status, or
+ a wrapper without the expected key — is rejected into
+ ``report["errors"]`` under ``phase`` and the sweep phase aborts without
+ attempting side effects. Wrapper dicts are never accepted generically:
+ that would turn unrelated metadata into fake broker records.
+
+ Returns:
+ The broker record list, or ``None`` (after recording the error).
+ """
+ try:
+ response = read_fn()
+ except Exception as exc: # noqa: BLE001 — broker read must not abort the sweep
+ report["errors"].append({"phase": phase, "error": str(exc)})
+ return None
+ envelope_error = _error_envelope_message(response)
+ if envelope_error is not None:
+ report["errors"].append({"phase": phase, "error": envelope_error})
+ return None
+ records = _unwrap_ok_payload(response, expected_key)
+ if records is None:
+ report["errors"].append(
+ {
+ "phase": phase,
+ "error": (
+ f"unexpected broker response: expected a records list or an "
+ f"adapter {{status: ok, data: ...}} payload carrying "
+ f"{expected_key!r}, got {type(response).__name__}"
+ ),
+ }
+ )
+ return None
+ return records
+
+
+def _unwrap_ok_payload(response: Any, expected_key: str) -> list[Any] | None:
+ """Decode a successful adapter read payload into a records list.
+
+ Accepts a bare list (injected/legacy read stubs) or the adapter's
+ ``{"status": "ok", "data": <value>}`` shape, where ``data`` is either the
+ records list or a wrapper dict carrying the pinned ``expected_key``.
+ Returns ``None`` for anything else — never a generic dict.
+ """
+ if isinstance(response, list):
+ return response
+ if not isinstance(response, dict) or response.get("status") != "ok":
+ return None
+ payload = response.get("data")
+ if isinstance(payload, list):
+ return payload
+ if isinstance(payload, dict):
+ records = payload.get(expected_key)
+ if isinstance(records, list):
+ return records
+ return None
+
+
def _cancel_resting_orders(
broker: str,
submit: SubmitFn,
@@ -166,15 +243,24 @@ def _cancel_resting_orders(
report: Mutated in place — successful ids appended to
``cancelled_order_ids``, failures to ``errors``.
"""
- try:
- open_orders = read_open_orders()
- except Exception as exc: # noqa: BLE001 — broker read must not abort the sweep
- report["errors"].append({"phase": "read_open_orders", "error": str(exc)})
+ open_orders = _read_broker_state(
+ "read_open_orders", "orders", read_open_orders, report
+ )
+ if open_orders is None:
return
for order in open_orders:
+ if not isinstance(order, dict):
+ report["errors"].append(
+ {
+ "phase": "read_open_orders",
+ "error": f"invalid entry: {type(order).__name__}",
+ }
+ )
+ continue
order_id = order.get("order_id")
request = {"action": "cancel", "order_id": order_id}
+ report["side_effects_attempted"] = True
try:
response = submit(request)
except Exception as exc: # noqa: BLE001 — record + move on, never retry
@@ -236,13 +322,19 @@ def _flatten_open_positions(
report: Mutated in place — accepted closes appended to
``flatten_orders_submitted``, failures to ``errors``.
"""
- try:
- positions = read_positions()
- except Exception as exc: # noqa: BLE001 — broker read must not abort the sweep
- report["errors"].append({"phase": "read_positions", "error": str(exc)})
+ positions = _read_broker_state("read_positions", "positions", read_positions, report)
+ if positions is None:
return
for position in positions:
+ if not isinstance(position, dict):
+ report["errors"].append(
+ {
+ "phase": "read_positions",
+ "error": f"invalid entry: {type(position).__name__}",
+ }
+ )
+ continue
symbol = position.get("symbol")
qty = float(position.get("qty", 0) or 0)
if qty == 0:
@@ -257,6 +349,7 @@ def _flatten_open_positions(
"type": "market",
}
intent = f"flatten {symbol}: {side} {close_qty} @ market"
+ report["side_effects_attempted"] = True
try:
response = submit(request)
except Exception as exc: # noqa: BLE001 — record + move on, never retry
diff --git a/agent/tests/test_runtime_flatten.py b/agent/tests/test_runtime_flatten.py
index 65a3ccce6..e67c5f4a2 100644
--- a/agent/tests/test_runtime_flatten.py
+++ b/agent/tests/test_runtime_flatten.py
@@ -208,6 +208,165 @@ def test_mandate_flatten_flag_honored(
assert report["flatten_skipped_reason"] is None
+def test_error_envelope_read_open_orders_recorded_not_raised(
+ live_runtime: Path,
+) -> None:
+ # MCPServerAdapter.call_tool returns an error envelope instead of raising;
+ # the sweep must reject it as a structured read error, not crash while
+ # iterating the mapping's string keys.
+ broker = _Broker(open_orders=[{"order_id": "o1"}], positions=[])
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ broker.read_positions,
+ lambda: _error_envelope("open orders"),
+ )
+ assert {
+ "phase": "read_open_orders",
+ "error": "connection reset while cancelling open orders",
+ } in report["errors"]
+ assert broker.calls == [] # nothing was cancelled
+
+
+def test_error_envelope_read_positions_recorded_not_raised(
+ live_runtime: Path,
+) -> None:
+ broker = _Broker(open_orders=[], positions=[{"symbol": "NVDA", "qty": 1}])
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ lambda: _error_envelope("positions"),
+ broker.read_open_orders,
+ allow_flatten=True,
+ )
+ assert {
+ "phase": "read_positions",
+ "error": "connection reset while cancelling positions",
+ } in report["errors"]
+ assert broker.calls == [] # no close order was submitted
+
+
+def test_non_list_read_rejected_without_iterating(live_runtime: Path) -> None:
+ # A dict-shaped read result (e.g. a wrapped payload) must be rejected
+ # safely rather than iterated as a mapping.
+ broker = _Broker(open_orders=[], positions=[])
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ broker.read_positions,
+ lambda: {"orders": [{"order_id": "o1"}]},
+ )
+ read_errors = [e for e in report["errors"] if e["phase"] == "read_open_orders"]
+ assert read_errors and "got dict" in read_errors[0]["error"]
+ assert broker.calls == []
+
+
+def test_invalid_read_entries_skipped_safely(live_runtime: Path) -> None:
+ broker = _Broker(open_orders=[{"order_id": "o1"}], positions=[])
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ broker.read_positions,
+ lambda: ["o1", {"order_id": "o2"}, 42],
+ )
+ assert report["cancelled_order_ids"] == ["o2"] # only the dict entry
+ assert any(
+ e["phase"] == "read_open_orders" and "invalid entry" in e["error"]
+ for e in report["errors"]
+ )
+
+
+def test_adapter_ok_envelope_open_orders_unwrapped(live_runtime: Path) -> None:
+ # A REAL successful MCPServerAdapter response is {"status": "ok",
+ # "data": ...} — the sweep must decode it, not treat it as a failure
+ # ("expected a list of records, got dict"), or the halt action never runs.
+ broker = _Broker(open_orders=[{"order_id": "o1"}], positions=[])
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ broker.read_positions,
+ lambda: {"status": "ok", "data": {"orders": [{"order_id": "o1"}]}},
+ )
+ assert report["cancelled_order_ids"] == ["o1"]
+ assert report["errors"] == []
+ assert report["side_effects_attempted"] is True
+
+
+def test_adapter_ok_envelope_positions_unwrapped(live_runtime: Path) -> None:
+ broker = _Broker(open_orders=[], positions=[])
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ lambda: {"status": "ok", "data": {"positions": [{"symbol": "NVDA", "qty": 3}]}},
+ broker.read_open_orders,
+ allow_flatten=True,
+ )
+ assert [s["symbol"] for s in report["flatten_orders_submitted"]] == ["NVDA"]
+ assert report["errors"] == []
+ assert report["side_effects_attempted"] is True
+
+
+def test_adapter_ok_envelope_bare_list_data_unwrapped(live_runtime: Path) -> None:
+ broker = _Broker(open_orders=[], positions=[])
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ broker.read_positions,
+ lambda: {"status": "ok", "data": [{"order_id": "o1"}]},
+ )
+ assert report["cancelled_order_ids"] == ["o1"]
+
+
+def test_adapter_ok_envelope_missing_pinned_key_rejected(live_runtime: Path) -> None:
+ # A wrapper dict without the pinned key must NOT be accepted generically
+ # (metadata would become fake broker records).
+ broker = _Broker(open_orders=[], positions=[])
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ broker.read_positions,
+ lambda: {"status": "ok", "data": {"foo": [{"order_id": "o1"}]}},
+ )
+ assert any(
+ e["phase"] == "read_open_orders" and "unexpected broker response" in e["error"]
+ for e in report["errors"]
+ )
+ assert broker.calls == []
+ assert report["side_effects_attempted"] is False
+
+
+def test_read_failure_but_flatten_attempted_sets_side_effects_flag(
+ live_runtime: Path,
+) -> None:
+ # The reviewer's sequence: order read fails, position read succeeds, a
+ # close is submitted. side_effects_attempted must be True so the runner
+ # latches — replaying that close after restart would be a duplicate.
+ broker = _Broker(open_orders=[], positions=[])
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ lambda: {"status": "ok", "data": {"positions": [{"symbol": "NVDA", "qty": 3}]}},
+ lambda: _error_envelope("open orders"),
+ allow_flatten=True,
+ )
+ assert {"phase": "read_open_orders", "error": "connection reset while cancelling open orders"} in report["errors"]
+ assert [s["symbol"] for s in report["flatten_orders_submitted"]] == ["NVDA"]
+ assert report["side_effects_attempted"] is True
+
+
+def test_all_reads_failed_no_side_effects_flag(live_runtime: Path) -> None:
+ broker = _Broker(open_orders=[], positions=[])
+ report = flatten.flatten_and_cancel(
+ "robinhood",
+ broker.submit,
+ lambda: _error_envelope("positions"),
+ lambda: _error_envelope("open orders"),
+ allow_flatten=True,
+ )
+ assert report["side_effects_attempted"] is False
+ assert broker.calls == []
+
+
def _error_envelope(key: str) -> dict[str, Any]:
"""The shape MCPServerAdapter.call_tool returns instead of raising."""
return {