M1 literal inactive 전면화: SlotState 5-state(idle/closed 별칭 제거), 마이그레이션 010(CHECK 교체+행 rewrite), ops_checks 를 transition_log 기반 재작성. M2 집행 매도 수량 브로커 정본(D3): dispatch 매도 qty=broker hldg_qty, 미러 fallback 없음, 브로커 0 → skip+WARN, 리스트 기반 dispatch(head-block 방지). M3 컬럼 drop + legacy pool 제거: 마이그레이션 011(trading_date·entry_count DROP), repo 계약 instance 스코프 개편(집행 큐 포함), preallocation 폐기(데몬 7스레드), admission 자산 중심 단일 경로(slot_id 정본), capacity 재정의(available=M−active), daily_symbol_entries 코드 경로 제거. M4 cutover 도구(D1·D4): trex-core-cutover(전체 rebuild, preflight/브로커 carry-over/ --allow-unmapped/--promote-unique/dry-run) + PG 리허설 테스트 8건. M5 baseline 마감: data-model/runtime-flows/project-structure/interface-contract 자산 중심 최종 갱신 + run-trex-core-daemon 스킬 정합. 검증: 단위 367 passed + ruff clean; PG-gated 29 passed(010/011 round-trip·드리프트 가드·cutover 리허설); RabbitMQ 21 passed; run-the-app e2e(test DB+실 MQ, M=1): reconcile 슬롯 생성→slot_id 매수→dedup→capacity_full→fill→already_active→ 매도→inactive(자산 바인딩 보존)→영구 슬롯 재활성 전 구간 green. 실 cutover 는 운영자 실행(REL 단계, D4). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
118 lines
4.7 KiB
Python
118 lines
4.7 KiB
Python
"""Safety-sell watchdog-ownership + fire visibility tests (dcy-017 / REQ-037, issue #12)."""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from datetime import datetime, timedelta, timezone
|
|
from decimal import Decimal
|
|
|
|
from trex_core.application.safety_sell import SafetySellService
|
|
from trex_core.application.watchdog import WatchdogStore
|
|
from trex_core.domain.slot import SlotService, SlotState
|
|
from trex_core.domain.slot.in_memory_repository import InMemorySlotRepository
|
|
from trex_core.runtime.config import SafetySellConfig
|
|
|
|
_NOW = datetime(2026, 6, 7, 6, 0, 0, tzinfo=timezone.utc)
|
|
|
|
|
|
class _FakeBroker:
|
|
def __init__(self):
|
|
self.prices = {}
|
|
|
|
def name(self): return "fake"
|
|
def submit_order(self, req): ...
|
|
def poll_fill(self, *a, **k): ...
|
|
def cancel_order(self, *a, **k): ...
|
|
def get_balance(self): return []
|
|
def get_current_price(self, symbol): return self.prices.get(symbol)
|
|
|
|
|
|
def _cfg(**over):
|
|
base = dict(watchdog_timeout_sec=120, watchdog_grace_period_sec=0,
|
|
forced_close_check_interval_sec=60, stop_loss_poll_interval_sec=30,
|
|
market_close_liquidation_time=None)
|
|
base.update(over)
|
|
return SafetySellConfig(**base)
|
|
|
|
|
|
def _wire(**cfg_over):
|
|
repo = InMemorySlotRepository()
|
|
svc = SlotService(repo, instance_key="inst-1")
|
|
broker = _FakeBroker()
|
|
watchdog = WatchdogStore()
|
|
service = SafetySellService(
|
|
slot_repo=repo, slot_service=svc, broker=broker, watchdog=watchdog,
|
|
config=_cfg(**cfg_over), instance_key="inst-1",
|
|
)
|
|
return repo, svc, broker, watchdog, service
|
|
|
|
|
|
def _holding(svc, repo, *, symbol="005930", **fields):
|
|
from uuid import uuid4
|
|
pid = f"pf-{uuid4().hex[:8]}"
|
|
repo.reconcile_universe("inst-1", {pid})
|
|
slot = repo.find_slot_by_portfolio("inst-1", pid)
|
|
p = svc.transit_slot(slot.slot_id, SlotState.INACTIVE, SlotState.PENDING_BUY,
|
|
reason="buy", actor="t", symbol=symbol, **fields)
|
|
return svc.transit_slot(p.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
|
|
reason="filled", actor="t", avg_price=50000.0, qty=1.0)
|
|
|
|
|
|
def test_watchdog_ownership_entry_warns(caplog):
|
|
repo, svc, broker, watchdog, service = _wire()
|
|
slot = _holding(svc, repo) # never polled => watchdog-expired (strategy absent)
|
|
with caplog.at_level(logging.WARNING):
|
|
service._update_ownership(_NOW)
|
|
assert service.counters.get("owned:enter") == 1
|
|
rec = [r for r in caplog.records if "watchdog ownership entered" in r.message]
|
|
assert rec and str(slot.slot_id) in rec[0].message and "inst-1" in rec[0].message
|
|
|
|
|
|
def test_watchdog_ownership_exit_on_return(caplog):
|
|
repo, svc, broker, watchdog, service = _wire()
|
|
slot = _holding(svc, repo)
|
|
service._update_ownership(_NOW) # enter (expired)
|
|
watchdog.update(str(slot.slot_id)) # strategy returns (polls)
|
|
with caplog.at_level(logging.INFO):
|
|
service._update_ownership(_NOW) # exit
|
|
assert service.counters.get("owned:exit") == 1
|
|
assert any("watchdog ownership released" in r.message for r in caplog.records)
|
|
|
|
|
|
def test_no_ownership_churn_when_stable():
|
|
repo, svc, broker, watchdog, service = _wire()
|
|
_holding(svc, repo)
|
|
service._update_ownership(_NOW)
|
|
service._update_ownership(_NOW) # same set => no new enter
|
|
assert service.counters.get("owned:enter") == 1
|
|
|
|
|
|
def test_forced_close_fire_logs_warn(caplog):
|
|
repo, svc, broker, watchdog, service = _wire()
|
|
slot = _holding(svc, repo, forced_close_at=_NOW - timedelta(seconds=1))
|
|
with caplog.at_level(logging.WARNING):
|
|
fired = service.check_forced_close(_NOW)
|
|
assert slot.slot_id in fired
|
|
assert service.counters.get("fire:forced_close_at") == 1
|
|
rec = [r for r in caplog.records if "safety-sell fired" in r.message
|
|
and r.levelno == logging.WARNING]
|
|
assert rec and "forced_close_at" in rec[0].message and "inst-1" in rec[0].message
|
|
|
|
|
|
def test_take_profit_fire_logs_info(caplog):
|
|
repo, svc, broker, watchdog, service = _wire()
|
|
slot = _holding(svc, repo, take_profit_price=Decimal("60000"))
|
|
broker.prices["005930"] = Decimal("61000")
|
|
with caplog.at_level(logging.INFO):
|
|
fired = service.check_prices(_NOW)
|
|
assert slot.slot_id in fired
|
|
assert service.counters.get("fire:take_profit") == 1
|
|
rec = [r for r in caplog.records if "safety-sell fired" in r.message]
|
|
assert rec and rec[0].levelno == logging.INFO # take_profit is INFO (OQ-2)
|
|
|
|
|
|
def test_grace_period_suppresses_ownership():
|
|
repo, svc, broker, watchdog, service = _wire(watchdog_grace_period_sec=9999)
|
|
_holding(svc, repo)
|
|
service._update_ownership(_NOW)
|
|
assert service.counters.get("owned:enter") is None # grace => no judgement
|