feat(rel-007): dcy-025/024 + BAT-035/036 — slots.req 즉시 교체 + safety_sell_enabled

BAT-035 (dcy-025): trex.snapshot.req → trex.slots.req 즉시 교체
- topology: SNAPSHOT_REQ_QUEUE 제거, SLOTS_REQ_QUEUE = "trex.slots.req" 추가
- portfolio.py: View/build_snapshot_envelope/SnapshotEnvelope/_asset_to_dict 제거;
  slot_to_dict 시그니처 확장(snapshot_store/watchdog_store/pause_store/watchdog_timeout_sec)
  — asset_quantity(hub)/cash_balance/cash_estimated/warned/watchdog{}/paused 병합 (REQ-074)
- messaging_handlers.py: make_snapshot_rpc_handler 제거, make_slots_rpc_handler 추가
  — filter(all/inactive/pending/holding/error) + spy(bool) 처리; strategy 필드 제외 (REQ-073/074)
- daemon.py: _snapshot_rpc_loop → _slots_rpc_loop, make_slots_rpc_handler 연결
- cli.py: universe/slots → slots_queue + spy=True + server-side filter; buyable→inactive 매핑 (REQ-063)
- rabbitmq.py: snapshot_queue → slots_queue
- docs: interface-contract.md + runtime-flows.md slots.req 계약으로 업데이트 (REQ-075)
- REQ-028: Implemented → Deprecated (코드 삭제 완료)
- 테스트: test_snapshot_handler/selection/rpc_watchdog/messaging_snapshot_consumer 삭제;
  test_slots_handler.py(신규, 13 cases), test_killswitch_masking_resume 재작성,
  test_ledger_option_d._apply_cash_estimate → slots handler 경유, test_topology/cli_operator 갱신

BAT-036 (dcy-024): per-instance safety_sell_enabled 플래그
- config.py: DaemonInstanceConfig + DaemonConfig 에 safety_sell_enabled: bool = True 추가;
  from_toml 파싱, from_config 전파
- daemon.py: start() workers 조건부 — safety_sell_enabled=false 시 trex-safety-sell 미기동 + WARNING
- tests: test_instance_config.py 에 safety_sell_enabled 파싱 3개 케이스 추가

REQ: 073/074/075/021/034/063/048/005 Approved → Implemented

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-11 14:45:45 +09:00
co-authored by Claude Opus 4.8
parent fb05a73130
commit f0ad37747b
44 changed files with 1963 additions and 1189 deletions
+39 -50
View File
@@ -102,101 +102,90 @@ def _today_iso(cfg: DaemonConfig) -> str:
def _cmd_universe(args, cfg, rpc) -> int:
# Universe = admittable slots (filter=inactive, spy=true — operator view)
instance = _resolve_instance(args)
payload = {"view": "all", "actor": "operator", "touch_watchdog": False,
"trading_date": _today_iso(cfg)}
resp = rpc(topology.snapshot_queue(instance), payload,
payload = {"filter": "inactive", "spy": True}
resp = rpc(topology.slots_queue(instance), payload,
correlation_id=str(uuid.uuid4()), timeout=args.timeout)
assets = resp.get("assets", [])
slots = resp.get("slots", [])
if args.json:
# Scope to universe data — `slots[]`/`watchdog[]` belong to `slots`.
_emit({"instance": instance, "view": resp.get("view"), "assets": assets,
"available_slots": resp.get("available_slots"),
_emit({"instance": instance, "filter": "inactive", "slots": slots,
"degraded": resp.get("degraded"), "reason": resp.get("reason")},
as_json=True)
else:
print(f"instance={instance} view=all assets={len(assets)} "
print(f"instance={instance} filter=inactive count={len(slots)} "
f"degraded={resp.get('degraded')}")
for a in assets:
print(f" {a.get('asset_id')}\t{a.get('symbol')}\tqty={a.get('asset_quantity')}")
for s in slots:
print(f" {s.get('portfolio_id')}\t{s.get('symbol')}\t"
f"qty(hub)={s.get('asset_quantity')}\tqty(slot)={s.get('qty')}")
return 0
def _cmd_slots(args, cfg, rpc) -> int:
instance = _resolve_instance(args)
payload = {"view": "all", "actor": "operator", "touch_watchdog": False,
"trading_date": _today_iso(cfg)}
resp = rpc(topology.snapshot_queue(instance), payload,
correlation_id=str(uuid.uuid4()), timeout=args.timeout)
# REQ-032 CHG-20260608-03 (BAT-022): show the real daemon slot table
# (envelope `slots[]`), not the universe `assets[]`. `--status` filters by
# slot status; `universe` keeps showing `assets[]`.
slots = resp.get("slots", [])
status = (args.status or "all").lower()
if status in ("holding", "held"):
slots = [s for s in slots if s.get("status") == "holding"]
elif status == "buyable":
# dcy-020 (BAT-030): admittable = inactive, not universe-detached.
slots = [s for s in slots
if s.get("status") == "inactive" and not s.get("universe_detached")]
elif status == "pending":
slots = [s for s in slots if s.get("status") in ("pending_buy", "pending_sell")]
# --symbol / --slot-id: client-side filters (composable with --status).
# REQ-063 CHG-20260611-01: map --status to filter; buyable → inactive
filter_val = "inactive" if status == "buyable" else status
payload = {"filter": filter_val, "spy": True}
resp = rpc(topology.slots_queue(instance), payload,
correlation_id=str(uuid.uuid4()), timeout=args.timeout)
slots = resp.get("slots", [])
# --symbol / --slot-id: client-side filters (composable with server-side filter)
if args.symbol:
slots = [s for s in slots if s.get("symbol") == args.symbol]
if args.slot_id:
slots = [s for s in slots if s.get("slot_id") == args.slot_id]
# dcy-017: holding-slot watchdog state (strategy-absent ownership).
owned = {w.get("portfolio_id") for w in resp.get("watchdog", []) if w.get("expired")}
wd_by_slot = {w.get("slot_id"): w for w in resp.get("watchdog", [])}
# watchdog-expired ownership: slots with watchdog.expired=True
owned = {s.get("portfolio_id") for s in slots
if (s.get("watchdog") or {}).get("expired")}
if args.json:
_emit({"instance": instance, "status": status, "slots": slots}, as_json=True)
_emit({"instance": instance, "filter": filter_val, "slots": slots}, as_json=True)
else:
header = f"instance={instance} status={status}"
header = f"instance={instance} filter={filter_val}"
if args.symbol:
header += f" symbol={args.symbol}"
if args.slot_id:
header += f" slot_id={args.slot_id}"
print(f"{header} count={len(slots)} "
f"watchdog_owned={len([s for s in slots if s.get('portfolio_id') in owned])}")
# When filtered (--symbol / --slot-id), print a detailed per-slot block;
# otherwise the terse one-line table.
f"watchdog_expired={len([s for s in slots if s.get('portfolio_id') in owned])}")
if args.symbol or args.slot_id:
for s in slots:
_print_slot_detail(s, wd_by_slot.get(s.get("slot_id")))
_print_slot_detail(s)
else:
for s in slots:
pid = s.get("portfolio_id")
tag = " [WATCHDOG-OWNED: strategy absent]" if pid in owned else ""
wd = s.get("watchdog") or {}
tag = " [WATCHDOG: strategy absent]" if wd.get("expired") else ""
print(f" {s.get('slot_id')}\t{s.get('status')}\t{s.get('symbol')}\t"
f"qty={s.get('qty')}\tlimit={s.get('entry_price')}\t"
f"avg={s.get('avg_price')}\tpid={s.get('portfolio_id')}{tag}")
f"qty={s.get('qty')}\taqty={s.get('asset_quantity')}\t"
f"limit={s.get('entry_price')}\tavg={s.get('avg_price')}\t"
f"pid={pid}\tpaused={s.get('paused')}\twarned={s.get('warned')}{tag}")
return 0
def _print_slot_detail(s: dict, wd: dict | None) -> None:
def _print_slot_detail(s: dict) -> None:
"""Verbose per-slot block used when `slots` is filtered (e.g. --symbol)."""
wd = s.get("watchdog") or {}
fields = [
("status", s.get("status")),
("symbol", s.get("symbol")),
("portfolio_id", s.get("portfolio_id")),
("qty", s.get("qty")),
("qty (slot mirror)", s.get("qty")),
("asset_quantity (hub)", s.get("asset_quantity")),
("warned", s.get("warned")),
("avg_price", s.get("avg_price")),
("entry_price (limit)", s.get("entry_price")),
("strategy_id", s.get("strategy_id")),
("sell_strategy_id", s.get("sell_strategy_id")),
("cash_balance", s.get("cash_balance")),
("cash_estimated", s.get("cash_estimated")),
("paused", s.get("paused")),
("forced_close_at", s.get("forced_close_at")),
("universe_detached", s.get("universe_detached")),
("watchdog.expired", wd.get("expired")),
("watchdog.last_seen", wd.get("last_seen")),
]
if wd is not None:
fields.append((
"watchdog",
f"expired={wd.get('expired')} last_seen={wd.get('last_seen')}",
))
print(f"slot {s.get('slot_id')}")
for label, value in fields:
print(f" {label:<20}: {value}")
return 0
print(f" {label:<24}: {value}")
def _intent_guard(args, cfg, summary: dict, action: str, confirm) -> int | None:
+8
View File
@@ -148,6 +148,9 @@ class DaemonInstanceConfig:
# dcy-022 / REQ-068: default order timeout in seconds (opt-in per instance).
# None = OFF = indefinite wait (legacy behavior). Per-intent timeout_sec overrides.
default_order_timeout_sec: Optional[int] = None
# dcy-024 / REQ-048 CHG-20260611-01: disable autonomous safety-sell worker.
# Absent = True (safe default). False → trex-safety-sell thread not started.
safety_sell_enabled: bool = True
@staticmethod
def from_toml(path: str) -> "DaemonInstanceConfig":
@@ -178,6 +181,7 @@ class DaemonInstanceConfig:
trading_timezone=str(data.get("trading_timezone") or "Asia/Seoul"),
max_active_slots=max_active,
default_order_timeout_sec=default_timeout,
safety_sell_enabled=bool(data.get("safety_sell_enabled", True)),
)
@@ -216,6 +220,9 @@ class DaemonConfig:
# dcy-014 / REQ-048: operator-local timezone (CLI date display etc.). The
# daily preallocation trigger was removed with the pool model (BAT-030).
trading_timezone: str = "Asia/Seoul"
# dcy-024 / REQ-005 CHG-20260611-01: disable autonomous safety-sell worker.
# False → trex-safety-sell thread not started in daemon.start().
safety_sell_enabled: bool = True
# dcy-015 / REQ-019 (BAT-019): ledger outbox retry backoff. base*2^(n-1)
# capped at cap (+jitter); after max_attempts a retryable row dead-letters.
ledger_retry_base_sec: float = 1.0
@@ -335,4 +342,5 @@ class DaemonConfig:
portfolio_hub=pf,
trading_timezone=inst.trading_timezone,
max_active_slots=inst.max_active_slots,
safety_sell_enabled=inst.safety_sell_enabled,
)
+14 -10
View File
@@ -53,7 +53,7 @@ from trex_core.application.killswitch import KillSwitchService
from trex_core.application.messaging_handlers import (
make_control_rpc_handler,
make_intent_rpc_handler,
make_snapshot_rpc_handler,
make_slots_rpc_handler,
slot_transition_event_payload,
)
from trex_core.application.portfolio import (
@@ -259,26 +259,24 @@ class Daemon:
transport.consume_rpc_forever(
topology.intent_queue(self.config.instance_key), handler, self.stop)
def _snapshot_rpc_loop(self) -> None:
def _slots_rpc_loop(self) -> None:
transport = _build_transport(self.config)
self._transports.append(transport)
try:
transport.declare_topology(self.config.instance_key)
except Exception: # noqa: BLE001
pass
handler = make_snapshot_rpc_handler(
self.slot_repo, self.slot_service,
handler = make_slots_rpc_handler(
self.slot_repo,
instance_key=self.config.instance_key,
snapshot_store=self.snapshot_store,
pause_store=self.pause_store,
max_active_slots=self.config.max_active_slots,
watchdog_store=self.watchdog,
watchdog_timeout_sec=self.config.safety_sell.watchdog_timeout_sec,
killswitch_store=self.killswitch_store,
ledger_outbox=self.outbox, # dcy-018 / REQ-029: estimated-cash overlay
ledger_outbox=self.outbox,
)
transport.consume_rpc_forever(
topology.snapshot_queue(self.config.instance_key), handler, self.stop)
topology.slots_queue(self.config.instance_key), handler, self.stop)
def _control_rpc_loop(self) -> None:
# REQ-043: operator control channel (pause/resume/list + kill_switch/resume_kill_switch).
@@ -329,11 +327,17 @@ class Daemon:
("trex-execution", self._execution_loop),
("trex-ledger", self._ledger_loop),
("trex-intent-rpc", self._intent_rpc_loop),
("trex-snapshot-rpc", self._snapshot_rpc_loop),
("trex-slots-rpc", self._slots_rpc_loop),
("trex-control-rpc", self._control_rpc_loop),
("trex-snapshot-scheduler", self._snapshot_scheduler_loop),
("trex-safety-sell", self._safety_sell_loop),
]
if self.config.safety_sell_enabled:
workers.append(("trex-safety-sell", self._safety_sell_loop))
else:
_log.warning(
"safety_sell_enabled=false — trex-safety-sell worker not started. "
"Autonomous safety-sell will NOT run."
)
for name, target in workers:
t = threading.Thread(target=target, name=name, daemon=True)
t.start()