feat(cli): dcy-016 운영자 CLI 확장 (universe/slots/enter/exit) + 워치독 억제 (BAT-020)
운영자가 조회·매수·매도를 CLI 로 수행하되 데몬 RabbitMQ RPC 로 통일해 단일 writer admission·불변식을 보존(DB 직접 쓰기 없음)하고, 운영자 조회가 전략 생존 신호로 오인되지 않게 워치독을 억제한다. 거버넌스: 전부 change-req (신규 REQ 없음, dcy-016 OQ-3). - REQ-032: CLI universe/slots(snapshot RPC) + enter(buy)/exit(sell) intent RPC + 인스턴스 라우팅(--config/--instance/default) + enter/exit 안전장치 (확인 프롬프트 기본 ON / --yes(paper) / --yes --live(이중 ack) / --dry-run) + 전 명령 --json. pause/resume 는 direct-DB 유지 - REQ-022: CLI request-reply RPC 클라이언트(call_rpc) 재사용 - REQ-021/034: snapshot 요청 워치독 억제 플래그(touch_watchdog/actor=operator) → 핸들러가 last_seen_at 갱신 스킵. 기본값 현행 유지(하위호환). 운영자 조회가 죽은 전략의 safety-sell 을 무력화하던 결함(R-4) 제거 - REQ-026: interface-contract/runtime-flows 정합 CLI 는 rpc/confirm 주입 가능(테스트 broker/DB-free). snapshot envelope 은 asset-centric 이라 exit 은 운영자 제공 slot_id 사용(slot_id 노출은 본 주기 밖). 검증: 단위 327 passed/34 skipped, 인프라 게이트(PG+RabbitMQ) 361 passed, ruff clean. 신규 test_cli_operator(14) + snapshot 워치독 억제(2). BAT-020 release-candidate. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -75,3 +75,45 @@ def test_snapshot_strategy_id_filter():
|
||||
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
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Operator CLI tests (dcy-016 / REQ-032) — RPC injected, no broker/DB needed."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from trex_core.runtime import cli
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _env(monkeypatch):
|
||||
monkeypatch.setenv("TREX_POSTGRESQL_DSN", "postgresql://x/y")
|
||||
monkeypatch.setenv("TREX_BROKER", "paper")
|
||||
monkeypatch.delenv("TREX_KIS_ALLOW_LIVE", raising=False)
|
||||
|
||||
|
||||
class _RpcRecorder:
|
||||
def __init__(self, response):
|
||||
self.response = response
|
||||
self.calls = []
|
||||
|
||||
def __call__(self, queue, payload, *, correlation_id, timeout):
|
||||
self.calls.append({"queue": queue, "payload": payload, "cid": correlation_id})
|
||||
return self.response
|
||||
|
||||
|
||||
_SNAPSHOT = {
|
||||
"assets": [{"asset_id": "PF-1", "symbol": "005930", "asset_quantity": 0,
|
||||
"active_strategy_id": "orb"}],
|
||||
"view": "all", "available_slots": 9, "degraded": False, "reason": None,
|
||||
}
|
||||
_ADMITTED = {"intent_id": "i", "status": "admitted", "slot_id": "S-1", "reason": None}
|
||||
_REJECTED = {"intent_id": "i", "status": "rejected", "slot_id": None,
|
||||
"reason": "unknown_portfolio"}
|
||||
|
||||
|
||||
# --- universe / slots (snapshot RPC + watchdog suppression) ------------------
|
||||
def test_universe_uses_snapshot_queue_with_operator_suppression(capsys):
|
||||
rpc = _RpcRecorder(_SNAPSHOT)
|
||||
rc = cli.main(["universe"], rpc=rpc)
|
||||
assert rc == 0
|
||||
call = rpc.calls[0]
|
||||
assert call["queue"] == "trex.snapshot.req" # default instance
|
||||
assert call["payload"]["actor"] == "operator"
|
||||
assert call["payload"]["touch_watchdog"] is False # FR-2a / R-4
|
||||
assert "PF-1" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_slots_status_holding_maps_to_held_view():
|
||||
rpc = _RpcRecorder(_SNAPSHOT)
|
||||
cli.main(["slots", "--status", "holding"], rpc=rpc)
|
||||
assert rpc.calls[0]["payload"]["view"] == "held"
|
||||
|
||||
|
||||
def test_instance_shortcut_routes_to_instance_queue():
|
||||
rpc = _RpcRecorder(_SNAPSHOT)
|
||||
cli.main(["universe", "--instance", "inst-2"], rpc=rpc)
|
||||
assert rpc.calls[0]["queue"] == "trex.snapshot.req.inst-2"
|
||||
|
||||
|
||||
def test_json_output_is_valid_json(capsys):
|
||||
rpc = _RpcRecorder(_SNAPSHOT)
|
||||
cli.main(["universe", "--json"], rpc=rpc)
|
||||
parsed = json.loads(capsys.readouterr().out)
|
||||
assert parsed["assets"][0]["asset_id"] == "PF-1"
|
||||
|
||||
|
||||
# --- enter (buy intent RPC) + safeguards ------------------------------------
|
||||
def test_enter_aborts_without_confirmation_no_rpc():
|
||||
rpc = _RpcRecorder(_ADMITTED)
|
||||
rc = cli.main(["enter", "PF-1", "--capital", "100000"],
|
||||
rpc=rpc, confirm=lambda _p: False)
|
||||
assert rc == 1 and rpc.calls == [] # aborted -> no order
|
||||
|
||||
|
||||
def test_enter_with_yes_submits_buy_intent():
|
||||
rpc = _RpcRecorder(_ADMITTED)
|
||||
rc = cli.main(["enter", "PF-1", "--capital", "100000", "--yes"], rpc=rpc)
|
||||
assert rc == 0
|
||||
p = rpc.calls[0]["payload"]
|
||||
assert rpc.calls[0]["queue"] == "trex.intent.req"
|
||||
assert p["intent_type"] == "buy" and p["portfolio_id"] == "PF-1"
|
||||
assert p["allocated_capital"] == 100000
|
||||
assert "symbol" not in p # server-resolved (dcy-011)
|
||||
|
||||
|
||||
def test_enter_rejected_returns_nonzero():
|
||||
rpc = _RpcRecorder(_REJECTED)
|
||||
rc = cli.main(["enter", "PF-x", "--yes"], rpc=rpc)
|
||||
assert rc == 1
|
||||
|
||||
|
||||
def test_enter_dry_run_does_not_submit(capsys):
|
||||
rpc = _RpcRecorder(_ADMITTED)
|
||||
rc = cli.main(["enter", "PF-1", "--capital", "5", "--dry-run"], rpc=rpc)
|
||||
assert rc == 0 and rpc.calls == []
|
||||
assert "dry-run" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_enter_json_requires_yes():
|
||||
rpc = _RpcRecorder(_ADMITTED)
|
||||
rc = cli.main(["enter", "PF-1", "--json"], rpc=rpc)
|
||||
assert rc == 2 and rpc.calls == [] # no auto-submit (FR-7)
|
||||
|
||||
|
||||
# --- exit (sell intent RPC) -------------------------------------------------
|
||||
def test_exit_with_yes_submits_sell_with_limit_price():
|
||||
rpc = _RpcRecorder(_ADMITTED)
|
||||
cli.main(["exit", "S-1", "--price", "70000", "--yes"], rpc=rpc)
|
||||
p = rpc.calls[0]["payload"]
|
||||
assert p["intent_type"] == "sell" and p["slot_id"] == "S-1"
|
||||
assert p["limit_price"] == 70000
|
||||
|
||||
|
||||
def test_exit_market_when_no_price():
|
||||
rpc = _RpcRecorder(_ADMITTED)
|
||||
cli.main(["exit", "S-1", "--yes"], rpc=rpc)
|
||||
assert rpc.calls[0]["payload"]["limit_price"] is None
|
||||
|
||||
|
||||
# --- live guard (OQ-2 double ack) -------------------------------------------
|
||||
def test_live_requires_live_flag(monkeypatch):
|
||||
monkeypatch.setattr(cli, "_broker_mode", lambda cfg: ("kis", True))
|
||||
rpc = _RpcRecorder(_ADMITTED)
|
||||
rc = cli.main(["enter", "PF-1", "--yes"], rpc=rpc) # --yes but no --live
|
||||
assert rc == 2 and rpc.calls == []
|
||||
|
||||
|
||||
def test_live_proceeds_with_yes_live(monkeypatch):
|
||||
monkeypatch.setattr(cli, "_broker_mode", lambda cfg: ("kis", True))
|
||||
rpc = _RpcRecorder(_ADMITTED)
|
||||
rc = cli.main(["enter", "PF-1", "--yes", "--live"], rpc=rpc)
|
||||
assert rc == 0 and len(rpc.calls) == 1
|
||||
|
||||
|
||||
# --- transport failure surfaces as a clear error ----------------------------
|
||||
def test_rpc_failure_surfaces_error(capsys):
|
||||
def boom(*a, **k):
|
||||
raise RuntimeError("daemon unreachable")
|
||||
rc = cli.main(["universe"], rpc=boom)
|
||||
assert rc == 3
|
||||
assert "daemon unreachable" in capsys.readouterr().err
|
||||
Reference in New Issue
Block a user