Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(live): recover Alpaca submits by exact identity

Miranda1fd79443e55a
diff --git a/agent/src/live/daily_count.py b/agent/src/live/daily_count.py
index 62c09b49b..96d1222fe 100644
--- a/agent/src/live/daily_count.py
+++ b/agent/src/live/daily_count.py
@@ -35,6 +35,10 @@ class DailyOrderLockUnavailable(RuntimeError):
"""Raised when another process holds the broker's order permit lock."""
+class DailyCountError(RuntimeError):
+ """Raised when action-ID accounting cannot be trusted or persisted."""
+
+
def _counter_path(broker: str):
return broker_dir(broker) / _COUNTER_FILENAME
@@ -120,15 +124,67 @@ def read_daily_count(broker: str) -> int:
return 0
-def increment_daily_count(broker: str) -> int:
+def increment_daily_count(broker: str, action_id: str | None = None) -> int:
"""Persist ``broker``'s incremented count for today (atomic). Returns new count."""
today = _utc_today()
- count = read_daily_count(broker) + 1
+ if action_id is not None and not (1 <= len(action_id) <= 128):
+ raise DailyCountError("action_id must contain 1-128 characters")
+ try:
+ action_ids = _read_action_ids(broker)
+ except DailyCountError:
+ if action_id is not None:
+ raise
+ action_ids = []
+ count = read_daily_count(broker)
+ if action_id is not None and action_id in action_ids:
+ return count
+ count += 1
+ if action_id is not None:
+ action_ids.append(action_id)
path = _counter_path(broker)
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
tmp = path.with_name(
f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp"
)
- tmp.write_text(json.dumps({"date": today, "count": count}, ensure_ascii=False), encoding="utf-8")
- tmp.replace(path)
+ payload = json.dumps({"date": today, "count": count, "action_ids": action_ids}, ensure_ascii=False)
+ try:
+ with tmp.open("x", encoding="utf-8", newline="\n") as handle:
+ handle.write(payload + "\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+ tmp.replace(path)
+ if os.name != "nt":
+ descriptor = os.open(path.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
+ try:
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
+ except Exception as exc:
+ try:
+ tmp.unlink()
+ except OSError as cleanup_exc:
+ exc.add_note(f"temporary count cleanup also failed: {cleanup_exc}")
+ raise DailyCountError("daily order count could not be persisted") from exc
return count
+
+
+def _read_action_ids(broker: str) -> list[str]:
+ path = _counter_path(broker)
+ if not path.is_file():
+ return []
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as exc:
+ raise DailyCountError("daily order count cannot be read") from exc
+ if not isinstance(raw, dict) or raw.get("date") != _utc_today():
+ return []
+ count, values = raw.get("count"), raw.get("action_ids", [])
+ if (
+ isinstance(count, bool) or not isinstance(count, int) or count < 0
+ or not isinstance(values, list)
+ or any(not isinstance(value, str) or not value for value in values)
+ or len(set(values)) != len(values)
+ or len(values) > count
+ ):
+ raise DailyCountError("daily order count has an invalid schema")
+ return values
diff --git a/agent/src/live/pending_action.py b/agent/src/live/pending_action.py
index e56746033..d1d90ebd7 100644
--- a/agent/src/live/pending_action.py
+++ b/agent/src/live/pending_action.py
@@ -44,20 +44,38 @@ class PendingOrderRequest(BaseModel):
return self
+class RecoveredOrderEvidence(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ broker_order_id: str = Field(min_length=1)
+ client_order_id: str = Field(min_length=1, max_length=48)
+ symbol: str = Field(min_length=1)
+ side: Literal["buy", "sell"]
+ order_type: Literal["market", "limit"]
+ time_in_force: Literal["day", "gtc"]
+ quantity: float | int | None
+ notional: float | int | None
+ limit_price: float | int | None
+ filled_qty: float | int
+ order_status: str = Field(min_length=1)
+ submitted_at: str = Field(min_length=1)
+
+
class PendingAction(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
schema_version: Literal[1]
broker: Literal["alpaca"]
action_id: str = Field(pattern=r"^act_[0-9a-f]{32}$")
- phase: Literal["pending_write"]
+ phase: Literal["pending_write", "resolved_needs_revalidation"]
kind: Literal["place_order"]
created_at: datetime
client_order_id: str = Field(min_length=1, max_length=48)
- broker_order_id: None = None
+ broker_order_id: str | None = None
request: PendingOrderRequest
pre_position_qty: float | int | None
remediation_attempts: Literal[0]
+ resolution: RecoveredOrderEvidence | None = None
@model_validator(mode="after")
def validate_evidence(self) -> Self:
@@ -67,6 +85,16 @@ class PendingAction(BaseModel):
self.pre_position_qty
):
raise ValueError("pre-position quantity must be finite")
+ if self.phase == "pending_write" and (
+ self.broker_order_id is not None or self.resolution is not None
+ ):
+ raise ValueError("pending write cannot contain resolved evidence")
+ if self.phase == "resolved_needs_revalidation" and (
+ self.resolution is None
+ or self.broker_order_id != self.resolution.broker_order_id
+ or self.client_order_id != self.resolution.client_order_id
+ ):
+ raise ValueError("resolved phase requires matching exact evidence")
return self
@@ -125,6 +153,30 @@ def save_pending_action(action: PendingAction) -> None:
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
if path.exists() or path.is_symlink():
raise PendingActionError("a pending broker action already exists")
+ _write_action(path, action)
+
+
+def transition_to_revalidation(
+ action: PendingAction, evidence: Mapping[str, object]
+) -> PendingAction:
+ """Durably retain exact working-order truth for later policy revalidation."""
+ resolution = RecoveredOrderEvidence.model_validate(evidence)
+ updated = PendingAction.model_validate(
+ {
+ **action.model_dump(mode="python"),
+ "phase": "resolved_needs_revalidation",
+ "broker_order_id": resolution.broker_order_id,
+ "resolution": resolution,
+ }
+ )
+ current = load_pending_action(action.broker)
+ if current is None or current.action_id != action.action_id:
+ raise PendingActionError("pending action changed before transition")
+ _write_action(pending_action_path(action.broker), updated)
+ return updated
+
+
+def _write_action(path: Path, action: PendingAction) -> None:
payload = json.dumps(
action.model_dump(mode="json"),
allow_nan=False,
diff --git a/agent/src/live/sdk_order_gate.py b/agent/src/live/sdk_order_gate.py
index 14dd26227..328c9c1ee 100644
--- a/agent/src/live/sdk_order_gate.py
+++ b/agent/src/live/sdk_order_gate.py
@@ -25,11 +25,13 @@ from __future__ import annotations
import logging
from datetime import datetime, timezone
+from decimal import Decimal, InvalidOperation
from typing import Any
from src.live import pending_action
from src.live.audit import LiveActionEvent, write_live_action
from src.live.daily_count import (
+ DailyCountError,
DailyOrderLockUnavailable,
daily_order_lock,
increment_daily_count,
@@ -134,10 +136,14 @@ def execute_live_order(
intent=intent, reason_code="pending_action_invalid",
)
if unresolved is not None:
- return _deny(
- broker, session_id, "pending broker action requires recovery",
- ["mandate", "expiry", "halt_flag", "pending_action"], mandate,
- intent=intent, reason_code="pending_action_unresolved",
+ if unresolved.phase == "resolved_needs_revalidation":
+ return _deny(
+ broker, session_id, "recovered broker order requires policy revalidation",
+ ["mandate", "expiry", "halt_flag", "pending_action"], mandate,
+ intent=intent, reason_code="pending_action_needs_revalidation",
+ )
+ return _recover_pending_order(
+ broker, session_id, connector_module, config, mandate, unresolved
)
daily_count = read_daily_count(broker)
breach = check_mandate(
@@ -428,6 +434,7 @@ def _allow(broker, session_id, connector_module, config, intent, place_kwargs, m
result = {"status": "error", "error": str(exc)}
is_error = not isinstance(result, dict) or str(result.get("status", "")).lower() != "ok"
+ accounting_failed = False
checked = [
"mandate",
"expiry",
@@ -457,7 +464,13 @@ def _allow(broker, session_id, connector_module, config, intent, place_kwargs, m
error=_error_message(result),
)
else:
- increment_daily_count(broker)
+ try:
+ if pending is not None:
+ increment_daily_count(broker, pending.action_id)
+ else:
+ increment_daily_count(broker)
+ except DailyCountError:
+ accounting_failed = True
record = _audit(
broker,
session_id,
@@ -467,7 +480,8 @@ def _allow(broker, session_id, connector_module, config, intent, place_kwargs, m
intent=intent,
broker_request=dict(place_kwargs),
broker_response=result,
- gate_decision={"allowed": True, "decision": _DECISION_ALLOW, "checked_limits": checked},
+ gate_decision={"allowed": True, "decision": _DECISION_ALLOW, "checked_limits": checked,
+ **({"reason_code": "daily_action_accounting_failed"} if accounting_failed else {})},
)
if isinstance(result, dict) and record is not None:
result = {**result, LIVE_ACTION_RESULT_KEY: record}
@@ -478,7 +492,7 @@ def _allow(broker, session_id, connector_module, config, intent, place_kwargs, m
and result.get("client_order_id") == pending.client_order_id
and bool(result.get("order_id"))
)
- if not is_error and exact_ack and record is not None:
+ if not is_error and not accounting_failed and exact_ack and record is not None:
try:
pending_action.clear_pending_action(broker, pending.action_id)
cleared = True
@@ -494,6 +508,130 @@ def _allow(broker, session_id, connector_module, config, intent, place_kwargs, m
return result if isinstance(result, dict) else {"status": "error", "error": "non-dict broker result"}
+def _recover_pending_order(broker, session_id, connector, config, mandate, action):
+ """Resolve one Alpaca submission by exact identity, never by resubmission."""
+ checked = ["mandate", "expiry", "halt_flag", "pending_action", "exact_broker_evidence"]
+
+ def unresolved(reason):
+ return _deny(
+ broker, session_id, reason, checked, mandate,
+ intent=None, reason_code="pending_action_unresolved",
+ )
+
+ lookup = getattr(connector, "get_order_by_client_order_id", None)
+ if lookup is None:
+ return unresolved("connector lacks exact order recovery")
+ try:
+ response = lookup(config, client_order_id=action.client_order_id)
+ except Exception as exc: # noqa: BLE001 - read failure is insufficient evidence
+ response = {"status": "error", "error": str(exc)}
+ evidence = _validate_recovery_evidence(action, response)
+ if evidence is None:
+ return unresolved("exact broker evidence is missing or contradictory")
+
+ status = evidence["order_status"]
+ filled = Decimal(str(evidence["filled_qty"]))
+ working = {"accepted", "new", "open", "pending_new", "accepted_for_bidding"}
+ terminal = {"rejected", "canceled", "expired"}
+ if ((status in working or status in terminal) and filled != 0) or (
+ status in {"partially_filled", "filled"} and filled <= 0
+ ):
+ return unresolved("broker status contradicts filled quantity")
+ if status != "rejected":
+ try:
+ increment_daily_count(broker, action.action_id)
+ except DailyCountError:
+ return unresolved("recovered order could not be durably accounted")
+
+ record = _audit(
+ broker, session_id,
+ kind="order_rejected" if status == "rejected" else "order_placed",
+ outcome="rejected" if status == "rejected" else ("filled" if status == "filled" else "accepted"),
+ mandate=mandate, intent=None,
+ broker_request=action.request.model_dump(mode="json"), broker_response=evidence,
+ gate_decision={"allowed": False, "decision": _DECISION_DENY,
+ "checked_limits": checked, "reason_code": "exact_submit_recovered",
+ "action_id": action.action_id},
+ )
+ if record is None:
+ return _recovery_refusal(broker, "recovery audit was not durable")
+ if status in working:
+ try:
+ pending_action.transition_to_revalidation(action, evidence)
+ except Exception as exc: # noqa: BLE001 - retain the recovery block
+ logger.warning("pending action transition failed for %s: %s", broker, exc)
+ return _recovery_refusal(broker, "recovered order transition was not durable", record)
+ return _recovery_refusal(
+ broker, "recovered working order requires policy revalidation", record,
+ reason_code="pending_action_needs_revalidation",
+ )
+ if status in terminal:
+ try:
+ pending_action.clear_pending_action(broker, action.action_id)
+ except Exception as exc: # noqa: BLE001 - retain the recovery block
+ logger.warning("pending action clear failed for %s: %s", broker, exc)
+ return _recovery_refusal(broker, "terminal recovery could not be cleared", record)
+ return _recovery_refusal(
+ broker, "exact terminal broker outcome recovered", record,
+ reason_code="pending_action_resolved_terminal", recovery_pending=False,
+ )
+ return _recovery_refusal(broker, "exact fill requires position attribution", record)
+
+
+def _validate_recovery_evidence(action, response) -> dict[str, Any] | None:
+ order = response.get("order") if isinstance(response, dict) and response.get("status") == "ok" else None
+ if (
+ not isinstance(order, dict)
+ or not isinstance(order.get("broker_order_id"), str)
+ or not order["broker_order_id"]
+ ):
+ return None
+ request = action.request
+ expected = {"client_order_id": action.client_order_id, "symbol": request.symbol,
+ "side": request.side, "order_type": request.order_type,
+ "time_in_force": request.time_in_force}
+ if any(order.get(key) != value for key, value in expected.items()):
+ return None
+ try:
+ submitted = datetime.fromisoformat(str(order.get("submitted_at") or "").replace("Z", "+00:00"))
+ normalized = dict(order)
+ for key in ("quantity", "notional", "limit_price"):
+ actual, wanted = _exact_decimal(order.get(key)), _exact_decimal(getattr(request, key))
+ if actual != wanted:
+ return None
+ normalized[key] = float(actual) if actual is not None else None
+ filled = _exact_decimal(order.get("filled_qty"))
+ except (InvalidOperation, ValueError):
+ return None
+ status = str(order.get("order_status") or "").strip().lower()
+ supported = {"accepted", "new", "open", "pending_new", "accepted_for_bidding",
+ "rejected", "canceled", "expired", "partially_filled", "filled"}
+ if submitted.tzinfo is None or filled is None or filled < 0 or status not in supported:
+ return None
+ normalized.update(broker_order_id=str(order["broker_order_id"]), filled_qty=float(filled),
+ order_status=status, submitted_at=submitted.isoformat())
+ return normalized
+
+
+def _exact_decimal(value) -> Decimal | None:
+ if value is None:
+ return None
+ if isinstance(value, bool):
+ raise InvalidOperation
+ number = Decimal(str(value))
+ if not number.is_finite():
+ raise InvalidOperation
+ return number
+
+
+def _recovery_refusal(
+ broker, reason, record=None, *, reason_code="pending_action_unresolved", recovery_pending=True
+) -> dict[str, Any]:
+ result = _refusal(broker, decision=_DECISION_DENY, reason=reason, reauth=False, record=record)
+ result.update(reason_code=reason_code, recovery_pending=recovery_pending)
+ return result
+
+
def _deny(broker, session_id, reason, checked, mandate, *, intent, reauth=False, reason_code=None) -> dict[str, Any]:
"""Audit + return a refusal for a pre-check / structural DENY."""
record = _audit(
diff --git a/agent/src/trading/connectors/alpaca/sdk.py b/agent/src/trading/connectors/alpaca/sdk.py
index f3173bdca..5f59601cc 100644
--- a/agent/src/trading/connectors/alpaca/sdk.py
+++ b/agent/src/trading/connectors/alpaca/sdk.py
@@ -28,6 +28,7 @@ from dataclasses import asdict, dataclass
from pathlib import Path
from types import ModuleType
from typing import Any, Mapping
+from urllib.parse import urlencode
from src.config.paths import get_runtime_root
from src.trading import tap_forward
@@ -364,6 +365,33 @@ def get_open_orders(config: AlpacaConfig | None = None, *, include_executions: b
return result
+def get_order_by_client_order_id(
+ config: AlpacaConfig | None = None, *, client_order_id: str
+) -> dict[str, Any]:
+ """Read one order by the caller-owned exact Alpaca client order ID."""
+ cfg = config or load_config()
+ client_id = str(client_order_id or "").strip()
+ if not (1 <= len(client_id) <= 48):
+ return {"status": "error", "error": "client_order_id must contain 1-48 characters"}
+ try:
+ if tap_forward.tap_enabled():
+ query = urlencode({"client_order_id": client_id})
+ order = _read_via_tap(f"{cfg.host}/v2/orders:by_client_order_id?{query}")
+ else:
+ order = _trading_client(cfg).get_order_by_client_id(client_id)
+ except Exception as exc: # noqa: BLE001 - read failure is insufficient evidence
+ return {"status": "error", "error": str(exc)}
+ item = _order_to_dict(order)
+ return {"status": "ok", "profile": cfg.profile, "is_paper": cfg.is_paper, "order": {
+ "broker_order_id": item["order_id"], "client_order_id": item["client_order_id"],
+ "symbol": item["symbol"], "side": item["side"], "order_type": item["order_type"],
+ "time_in_force": item["time_in_force"], "quantity": item["quantity"],
+ "notional": item["notional"], "limit_price": item["limit_price"],
+ "filled_qty": item["filled_qty"], "order_status": item["status"],
+ "submitted_at": item["submitted_at"],
+ }}
+
+
def get_quote(symbol: str, *, config: AlpacaConfig | None = None, **_: Any) -> dict[str, Any]:
"""Fetch a latest quote snapshot for ``symbol``."""
cfg = config or load_config()
@@ -573,6 +601,7 @@ def place_order(
return {
"status": "ok",
"order_id": str(_obj_get(order, "id", "")),
+ "client_order_id": str(_obj_get(order, "client_order_id", "")),
"symbol": clean_symbol,
"side": side_token,
"profile": cfg.profile,
@@ -663,6 +692,7 @@ def _submit_via_tap(
return {
"status": "ok",
"order_id": str(payload.get("id", "")),
+ "client_order_id": str(payload.get("client_order_id", "")),
"symbol": symbol,
"side": side,
"profile": cfg.profile,
@@ -886,19 +916,25 @@ def _position_to_dict(item: Any) -> dict[str, Any]:
def _order_to_dict(item: Any) -> dict[str, Any]:
return {
"order_id": str(_obj_get(item, "id", "")),
+ "client_order_id": str(_obj_get(item, "client_order_id", "")),
"symbol": _obj_get(item, "symbol"),
- "side": str(_obj_get(item, "side", "")),
- "order_type": str(_obj_get(item, "order_type", "") or _obj_get(item, "type", "")),
+ "side": _enum_token(_obj_get(item, "side", "")),
+ "order_type": _enum_token(_obj_get(item, "order_type", "") or _obj_get(item, "type", "")),
+ "time_in_force": _enum_token(_obj_get(item, "time_in_force", "")),
"quantity": _obj_get(item, "qty"),
"notional": _obj_get(item, "notional"),
"filled_qty": _obj_get(item, "filled_qty"),
"filled_avg_price": _obj_get(item, "filled_avg_price"),
"limit_price": _obj_get(item, "limit_price"),
- "status": str(_obj_get(item, "status", "")),
+ "status": _enum_token(_obj_get(item, "status", "")),
"submitted_at": str(_obj_get(item, "submitted_at", "")),
}
+def _enum_token(value: Any) -> str:
+ return str(getattr(value, "value", value)).strip().lower()
+
+
def _bar_to_dict(item: Any) -> dict[str, Any]:
return {
"time": str(_obj_get(item, "timestamp", "")),
diff --git a/agent/tests/test_daily_count.py b/agent/tests/test_daily_count.py
index e1ca48a3c..3ed4d2689 100644
--- a/agent/tests/test_daily_count.py
+++ b/agent/tests/test_daily_count.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import os
+import json
import subprocess
import sys
from pathlib import Path
@@ -10,7 +11,7 @@ from pathlib import Path
import pytest
import src.live.paths as live_paths
-from src.live.daily_count import daily_order_lock
+from src.live.daily_count import daily_order_lock, increment_daily_count, read_daily_count
pytestmark = pytest.mark.unit
@@ -54,3 +55,15 @@ def test_daily_order_lock_is_cross_process(
assert blocked.stdout.strip() == "blocked"
assert acquired.stdout.strip() == "acquired"
+
+
+def test_action_id_increment_is_durable_and_deduplicated(tmp_path, monkeypatch) -> None:
+ runtime_root = tmp_path / ".vibe-trading"
+ monkeypatch.setattr(live_paths, "get_runtime_root", lambda: runtime_root)
+
+ assert increment_daily_count("alpaca", action_id="act_one") == 1
+ assert increment_daily_count("alpaca", action_id="act_one") == 1
+ assert increment_daily_count("alpaca", action_id="act_two") == 2
+ assert read_daily_count("alpaca") == 2
+ payload = json.loads((runtime_root / "live" / "alpaca" / "trade_counter.json").read_text())
+ assert payload["action_ids"] == ["act_one", "act_two"]
diff --git a/agent/tests/test_sdk_order_gate.py b/agent/tests/test_sdk_order_gate.py
index 8311adc36..057f6ba7e 100644
--- a/agent/tests/test_sdk_order_gate.py
+++ b/agent/tests/test_sdk_order_gate.py
@@ -58,6 +58,8 @@ class _FakeConnector:
def __init__(self, *, positions=None, balance=None, quote_last=100.0):
self.placed: list[dict] = []
+ self.lookups: list[str] = []
+ self.lookup_result: dict | BaseException = {"status": "error", "error": "not found"}
self._positions = positions if positions is not None else {"status": "ok", "positions": []}
self._balance = balance if balance is not None else {"status": "ok", "account": {}}
self._quote_last = quote_last
@@ -75,6 +77,18 @@ class _FakeConnector:
def get_quote(self, symbol, *, config=None):
return {"status": "ok", "symbol": symbol, "quote": {"last": self._quote_last}}
+ def get_order_by_client_order_id(self, config, *, client_order_id):
+ self.lookups.append(client_order_id)
+ if isinstance(self.lookup_result, BaseException):
+ raise self.lookup_result
+ return self.lookup_result
+
+
+class _LostResponseConnector(_FakeConnector):
+ def place_order(self, config, **kwargs):
+ self.placed.append(kwargs)
+ raise TimeoutError("response lost")
+
def _mandate(
*,
@@ -114,7 +128,7 @@ def _patch_gate(monkeypatch, *, mandate, halted=False):
monkeypatch.setattr(gate, "halt_flag_set", lambda broker: halted)
monkeypatch.setattr(gate, "write_live_action", lambda *a, **k: {"audited": True})
monkeypatch.setattr(gate, "read_daily_count", lambda broker: 0)
- monkeypatch.setattr(gate, "increment_daily_count", lambda broker: 1)
+ monkeypatch.setattr(gate, "increment_daily_count", lambda broker, action_id=None: 1)
monkeypatch.setattr(gate, "daily_order_lock", lambda broker: nullcontext())
@@ -176,6 +190,7 @@ def test_gate_allows_in_bounds_and_places(monkeypatch) -> None:
def test_alpaca_marker_precedes_submit_and_audit_precedes_clear(monkeypatch) -> None:
events: list[str] = []
+ action_ids: list[str] = []
class _OrderingConnector(_FakeConnector):
def place_order(self, config, **kwargs):
@@ -192,6 +207,8 @@ def test_alpaca_marker_precedes_submit_and_audit_precedes_clear(monkeypatch) ->
return record
monkeypatch.setattr(gate, "write_live_action", audited)
+ monkeypatch.setattr(gate, "increment_daily_count",
+ lambda broker, action_id=None: action_ids.append(action_id) or 1)
real_clear = pending_state.clear_pending_action
monkeypatch.setattr(pending_state, "clear_pending_action",
lambda broker, action_id: events.append("clear") or real_clear(broker, action_id))
@@ -202,6 +219,7 @@ def test_alpaca_marker_precedes_submit_and_audit_precedes_clear(monkeypatch) ->
assert first["status"] == second["status"] == "ok"
assert events == ["submit", "audit", "clear"] * 2
+ assert all(value and value.startswith("act_") for value in action_ids)
assert connector.placed[0]["client_order_id"] != connector.placed[1]["client_order_id"]
assert live_audit.audit_ledger_path().is_file()
assert load_pending_action("alpaca") is None
@@ -273,6 +291,108 @@ def test_incomplete_or_mismatched_ack_retains_marker(monkeypatch, response) -> N
assert len(connector.placed) == 1
+def _exact_order(action, *, status="new", filled_qty="0", **changes):
+ order = {
+ "broker_order_id": "broker-1", "client_order_id": action.client_order_id,
+ "symbol": action.request.symbol, "side": action.request.side,
+ "order_type": action.request.order_type, "time_in_force": action.request.time_in_force,
+ "quantity": action.request.quantity, "notional": action.request.notional,
+ "limit_price": action.request.limit_price, "filled_qty": filled_qty,
+ "order_status": status, "submitted_at": "2026-08-25T00:00:00Z",
+ }
+ order.update(changes)
+ return {"status": "ok", "order": order}
+
+
+def test_restart_recovers_exact_working_order_once_and_never_resubmits(monkeypatch) -> None:
+ counted: set[str] = set()
+ _patch_gate(monkeypatch, mandate=_mandate())
+ monkeypatch.setattr(gate, "increment_daily_count",
+ lambda broker, action_id=None: counted.add(action_id) or 1)
+ connector = _LostResponseConnector()
+ _place(connector)
+ action = load_pending_action("alpaca")
+ connector.lookup_result = _exact_order(action)
+ real_transition = pending_state.transition_to_revalidation
+ attempts = iter((False, True))
+ def crash_once(pending, evidence):
+ if not next(attempts):
+ raise OSError("crash after audit")
+ return real_transition(pending, evidence)
+ monkeypatch.setattr(pending_state, "transition_to_revalidation", crash_once)
+
+ interrupted = _place(connector)
+ recovered = _place(connector)
+ replay = _place(connector)
+ persisted = load_pending_action("alpaca")
+
+ assert interrupted["reason_code"] == "pending_action_unresolved"
+ assert recovered["reason_code"] == replay["reason_code"] == "pending_action_needs_revalidation"
+ assert persisted.phase == "resolved_needs_revalidation" and persisted.broker_order_id == "broker-1"
+ assert counted == {action.action_id}
+ assert len(connector.placed) == 1 and connector.lookups == [action.client_order_id] * 2
+
+
[email protected]("change", [None, {"symbol": "MSFT"}, {"client_order_id": "manual"},
+ {"order_status": "mystery"}])
+def test_recovery_insufficient_or_mismatched_evidence_stays_blocked(monkeypatch, change) -> None:
+ counted: list[str] = []
+ _patch_gate(monkeypatch, mandate=_mandate())
+ monkeypatch.setattr(gate, "increment_daily_count",
+ lambda broker, action_id=None: counted.append(action_id) or 1)
+ connector = _LostResponseConnector()
+ _place(connector)
+ action = load_pending_action("alpaca")
+ connector.lookup_result = ({"status": "error", "error": "not found"}
+ if change is None else _exact_order(action, **change))
+
+ result = _place(connector)
+
+ assert result["reason_code"] == "pending_action_unresolved"
+ assert load_pending_action("alpaca").phase == "pending_write"
+ assert counted == [] and len(connector.placed) == 1
+
+
[email protected](("status", "was_counted"), [("rejected", False), ("canceled", True),
+ ("expired", True)])
+def test_exact_zero_fill_terminal_is_audited_then_cleared(
+ monkeypatch, status, was_counted,
+) -> None:
+ counted: list[str] = []
+ _patch_gate(monkeypatch, mandate=_mandate())
+ monkeypatch.setattr(gate, "increment_daily_count",
+ lambda broker, action_id=None: counted.append(action_id) or 1)
+ connector = _LostResponseConnector()
+ _place(connector)
+ action = load_pending_action("alpaca")
+ connector.lookup_result = _exact_order(action, status=status)
+
+ result = _place(connector)
+
+ assert result["reason_code"] == "pending_action_resolved_terminal"
+ assert load_pending_action("alpaca") is None
+ assert counted == ([action.action_id] if was_counted else [])
+ assert len(connector.placed) == 1
+
+
[email protected]("status", ["partially_filled", "filled"])
+def test_exact_fill_is_counted_but_retained_for_position_attribution(monkeypatch, status) -> None:
+ counted: list[str] = []
+ _patch_gate(monkeypatch, mandate=_mandate())
+ monkeypatch.setattr(gate, "increment_daily_count",
+ lambda broker, action_id=None: counted.append(action_id) or 1)
+ connector = _LostResponseConnector()
+ _place(connector)
+ action = load_pending_action("alpaca")
+ connector.lookup_result = _exact_order(action, status=status, filled_qty="1")
+
+ result = _place(connector)
+
+ assert result["reason_code"] == "pending_action_unresolved"
+ assert load_pending_action("alpaca").phase == "pending_write"
+ assert counted == [action.action_id] and len(connector.placed) == 1
+
+
def test_corrupt_pending_marker_and_failed_audit_both_fail_closed(monkeypatch) -> None:
_patch_gate(monkeypatch, mandate=_mandate())
connector = _FakeConnector()
@@ -301,6 +421,21 @@ def test_audit_durability_failure_retains_pending_marker(monkeypatch) -> None:
assert len(connector.placed) == 1 and load_pending_action("alpaca") is not None
+def test_acknowledged_submit_count_failure_retains_recovery_marker(monkeypatch) -> None:
+ _patch_gate(monkeypatch, mandate=_mandate())
+ monkeypatch.setattr(
+ gate, "increment_daily_count",
+ lambda *args: (_ for _ in ()).throw(gate.DailyCountError("disk")),
+ )
+ connector = _FakeConnector()
+
+ result = _place(connector)
+
+ assert result["status"] == "ok" and result["recovery_pending"] is True
+ assert result["reason_code"] == "pending_action_unresolved"
+ assert len(connector.placed) == 1 and load_pending_action("alpaca") is not None
+
+
def test_external_client_id_reaches_direct_sdk_and_tap(monkeypatch) -> None:
captured: dict[str, object] = {}
@@ -344,6 +479,33 @@ def test_external_client_id_reaches_direct_sdk_and_tap(monkeypatch) -> None:
assert tap["status"] == "ok" and captured["tap"]["client_order_id"] == "vt-tap"
+def test_exact_lookup_normalizes_equivalent_direct_and_tap_evidence(monkeypatch) -> None:
+ payload = {"id": "oid", "client_order_id": "vt-exact", "symbol": "AAPL",
+ "side": "buy", "type": "market", "time_in_force": "day", "qty": "1",
+ "notional": None, "limit_price": None, "filled_qty": "0", "status": "new",
+ "submitted_at": "2026-08-25T00:00:00Z"}
+
+ class _Client:
+ def get_order_by_client_id(self, client_id):
+ assert client_id == "vt-exact"
+ return SimpleNamespace(**payload)
+
+ monkeypatch.setattr(alpaca_sdk, "_trading_client", lambda cfg: _Client())
+ monkeypatch.setattr(alpaca_sdk.tap_forward, "tap_enabled", lambda: False)
+ direct = alpaca_sdk.get_order_by_client_order_id(
+ alpaca_sdk.AlpacaConfig(profile="paper"), client_order_id="vt-exact")
+ captured: dict[str, str] = {}
+ monkeypatch.setattr(alpaca_sdk.tap_forward, "tap_enabled", lambda: True)
+ monkeypatch.setattr(alpaca_sdk.tap_forward, "forward",
+ lambda target, method, body, headers:
+ captured.update(target=target, method=method) or {"ok": True, "body": payload})
+ tap = alpaca_sdk.get_order_by_client_order_id(
+ alpaca_sdk.AlpacaConfig(profile="paper"), client_order_id="vt-exact")
+
+ assert direct == tap and direct["order"]["client_order_id"] == "vt-exact"
+ assert captured["method"] == "GET" and "client_order_id=vt-exact" in captured["target"]
+
+
def test_gate_blocks_oversized_order(monkeypatch) -> None:
_patch_gate(monkeypatch, mandate=_mandate(max_order=100.0))
conn = _FakeConnector()