전략 이탈로 슬롯이 내부 청산 루틴(워치독) 소유로 넘어간 상태가 무성이라 운영자가 인지할 수 없던 문제(issue #12)를 가시화한다. 거버넌스: 전부 change-req (신규 REQ 없음, dcy-017 OQ-3; Redis 미채택). - REQ-034/021: WatchdogStore.last_seen + snapshot RPC 응답에 holding 슬롯 워치독 상태(expired/last_seen) read-only 동봉(best-effort) - REQ-032: trex-core slots 가 expired 슬롯을 WATCHDOG-OWNED(전략 이탈) 표시 - REQ-037/038/039: safety-sell 워치독 소유 진입(WARN)/이탈(INFO) + 발동 (forced_close·stop_loss=WARN, take_profit·market_close=INFO) 로그 + in-process 카운터(SafetySellService.counters), 구조화 필드(slot_id/ portfolio_id/reason/phase/instance_key). per-tick 스킵은 카운터만 - REQ-042: runtime-flows/interface-contract 정합 best-effort 격리(NFR-1): 모든 가시화는 예외 격리 — 워치독 판정·청산 불변. dcy-016 억제 읽기로 관측이 워치독을 리셋하지 않음(비침습). 검증: 단위 335 passed/34 skipped, 인프라 게이트(PG+RabbitMQ) 369 passed, ruff clean. 신규 test_safety_sell_visibility(6) + snapshot watchdog(1) + CLI(1). BAT-021 rc. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
138 lines
5.0 KiB
Python
138 lines
5.0 KiB
Python
"""Snapshot RPC handler tests (REQ-021 AC-2, BAT-007 stub-shape)."""
|
|
from __future__ import annotations
|
|
|
|
from datetime import date
|
|
|
|
from trex_core.adapters.persistence.in_memory_intent_store import InMemoryIntentStore
|
|
from trex_core.application.intents import BuyIntent, IntentService
|
|
from trex_core.application.messaging import RpcRequest
|
|
from trex_core.application.messaging_handlers import make_snapshot_rpc_handler
|
|
from trex_core.domain.slot import SlotService
|
|
from trex_core.domain.slot.in_memory_repository import InMemorySlotRepository
|
|
|
|
DAY = date(2026, 6, 5)
|
|
|
|
|
|
def _wire():
|
|
repo = InMemorySlotRepository()
|
|
svc = SlotService(repo)
|
|
intents = IntentService(svc, repo, InMemoryIntentStore())
|
|
svc.preallocate_daily_slots(DAY, 3)
|
|
return repo, svc, intents
|
|
|
|
|
|
def _req(view="all", strategy_id=None):
|
|
return RpcRequest(
|
|
payload={
|
|
"view": view,
|
|
"strategy_id": strategy_id,
|
|
"trading_date": DAY.isoformat(),
|
|
},
|
|
correlation_id="snap-cid",
|
|
)
|
|
|
|
|
|
def test_snapshot_returns_all_slots_and_capacity():
|
|
repo, svc, intents = _wire()
|
|
intents.submit_buy(BuyIntent(
|
|
intent_id="b1", trading_date=DAY, symbol="005930", qty=10,
|
|
strategy_id="A", portfolio_id="PF-1",
|
|
))
|
|
handler = make_snapshot_rpc_handler(repo, svc)
|
|
resp = handler(_req())
|
|
assert resp.payload["trading_date"] == DAY.isoformat()
|
|
assert resp.payload["view"] == "all"
|
|
assert len(resp.payload["slots"]) == 3 # all 3 slots returned
|
|
cap = resp.payload["capacity"]
|
|
assert cap["pending_count"] == 1 and cap["idle_count"] == 2
|
|
|
|
|
|
def test_snapshot_open_view_filters_to_active_slots():
|
|
repo, svc, intents = _wire()
|
|
intents.submit_buy(BuyIntent(
|
|
intent_id="b1", trading_date=DAY, symbol="005930", qty=10, strategy_id="A",
|
|
portfolio_id="PF-1",
|
|
))
|
|
handler = make_snapshot_rpc_handler(repo, svc)
|
|
resp = handler(_req(view="open"))
|
|
statuses = {s["status"] for s in resp.payload["slots"]}
|
|
assert "idle" not in statuses
|
|
assert statuses == {"pending_buy"}
|
|
|
|
|
|
def test_snapshot_strategy_id_filter():
|
|
repo, svc, intents = _wire()
|
|
intents.submit_buy(BuyIntent(
|
|
intent_id="b1", trading_date=DAY, symbol="005930", qty=10, strategy_id="A",
|
|
portfolio_id="PF-1",
|
|
))
|
|
intents.submit_buy(BuyIntent(
|
|
intent_id="b2", trading_date=DAY, symbol="000660", qty=5, strategy_id="B",
|
|
portfolio_id="PF-2",
|
|
))
|
|
handler = make_snapshot_rpc_handler(repo, svc)
|
|
resp = handler(_req(view="open", strategy_id="A"))
|
|
assert len(resp.payload["slots"]) == 1
|
|
assert resp.payload["slots"][0]["strategy_id"] == "A"
|
|
assert resp.payload["slots"][0]["symbol"] == "005930"
|
|
|
|
|
|
# --- dcy-016 / REQ-021/034: operator query watchdog suppression -------------
|
|
class _RecWatchdog:
|
|
def __init__(self):
|
|
self.updated = []
|
|
|
|
def update(self, slot_id):
|
|
self.updated.append(str(slot_id))
|
|
|
|
|
|
def _holding_slot(repo, svc):
|
|
from trex_core.domain.slot import SlotState
|
|
slot = next(s for s in repo.list_slots(DAY) if s.status is SlotState.IDLE)
|
|
svc.transit_slot(slot.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
|
|
reason="t", actor="t", symbol="005930", portfolio_id="PF-1", qty=10)
|
|
svc.transit_slot(slot.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
|
|
reason="t", actor="t", avg_price=1000)
|
|
return str(slot.slot_id)
|
|
|
|
|
|
def test_strategy_poll_touches_watchdog_by_default():
|
|
repo, svc, intents = _wire()
|
|
sid = _holding_slot(repo, svc)
|
|
wd = _RecWatchdog()
|
|
handler = make_snapshot_rpc_handler(repo, svc, watchdog_store=wd)
|
|
handler(_req()) # no actor flag => legacy liveness touch (REQ-034)
|
|
assert sid in wd.updated
|
|
|
|
|
|
def test_operator_query_suppresses_watchdog_touch():
|
|
repo, svc, intents = _wire()
|
|
_holding_slot(repo, svc)
|
|
wd = _RecWatchdog()
|
|
handler = make_snapshot_rpc_handler(repo, svc, watchdog_store=wd)
|
|
req = RpcRequest(
|
|
payload={"view": "all", "trading_date": DAY.isoformat(),
|
|
"actor": "operator", "touch_watchdog": False},
|
|
correlation_id="op",
|
|
)
|
|
handler(req)
|
|
assert wd.updated == [] # dcy-016 R-4: operator query is not a liveness signal
|
|
|
|
|
|
def test_snapshot_exposes_watchdog_state_for_holding_slots():
|
|
"""dcy-017 / REQ-034: snapshot response carries holding-slot watchdog state."""
|
|
from trex_core.application.watchdog import WatchdogStore
|
|
repo, svc, intents = _wire()
|
|
sid = _holding_slot(repo, svc)
|
|
wd = WatchdogStore() # never updated => expired (strategy absent)
|
|
handler = make_snapshot_rpc_handler(repo, svc, watchdog_store=wd, watchdog_timeout_sec=120)
|
|
# operator query so the response does not touch the watchdog before we read it
|
|
req = RpcRequest(
|
|
payload={"view": "all", "trading_date": DAY.isoformat(), "actor": "operator"},
|
|
correlation_id="op",
|
|
)
|
|
states = handler(req).payload["watchdog"]
|
|
assert len(states) == 1
|
|
assert states[0]["slot_id"] == sid and states[0]["expired"] is True
|
|
assert states[0]["last_seen"] is None
|