Files
trex-core/tests/application/test_messaging_intent_consumer.py
T
genichinandClaude Opus 4.8 aee3512383 feat(intents): dcy-011 buy intent portfolio_id 필수 계약 + ledger skip 가시화 (BAT-015)
dcy-011 전 주기 delivery. issue #6(buy 식별자 정정) + issue #11(ledger silent skip) 흡수.
거버넌스: 기존 Implemented REQ는 change-req, 신규 기능만 신규 REQ(OQ-3).

- REQ-007 (change-req): buy admission portfolio_id 필수화 + SnapshotStore symbol
  resolve + unknown_portfolio 거부 (hard cutover, OQ-1/OQ-2)
- REQ-021 (change-req): buy 메시지 payload symbol 제거
- REQ-018 (change-req): _record_ledger skip 가시화 (WARN + ledger_skipped 카운터)
- REQ-055 (신규): closed↔ledger_outbox anti-join 운영 점검 find_ledger_gap_slots

코드: intents.py(BuyIntent portfolio_id 필수 + resolve_symbol 주입 + _admit_buy
reject 분기), messaging_handlers.py, runtime/daemon.py(_resolve_symbol 배선),
execution.py(skip WARN 로그), adapters/persistence/ops_checks.py(신규 anti-join).

검증: 단위 282 passed/32 skipped, 인프라 게이트(PG+RabbitMQ) 314 passed, ruff clean.
BAT-015(standard) release-candidate. srs/index Next ID → REQ-056.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 12:57:51 +09:00

176 lines
6.4 KiB
Python

"""Intent admission RPC handler + dedup tests (REQ-021/022/023, dcy-006).
The handler calls IntentService.submit_*, so dedup uses the IntentStore
(intent_log) gate (REQ-007). Two messages with the same correlation_id
trigger exactly ONE slot transition (REQ-023 AC-1).
"""
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 IntentService
from trex_core.application.messaging import RpcRequest
from trex_core.application.messaging_handlers import make_intent_rpc_handler
from trex_core.domain.slot import SlotService, SlotState
from trex_core.domain.slot.in_memory_repository import InMemorySlotRepository
DAY = date(2026, 6, 5)
def _wire():
repo = InMemorySlotRepository()
svc = SlotService(repo)
# dcy-011 / REQ-007: buy resolves symbol from the universe via resolver.
intents = IntentService(svc, repo, InMemoryIntentStore(),
resolve_symbol=lambda pid: "005930")
svc.preallocate_daily_slots(DAY, 3)
return repo, svc, intents
def _buy_req(intent_id: str, portfolio_id: str = "PF-1") -> RpcRequest:
# dcy-011 / REQ-021: buy payload carries portfolio_id (required); no symbol.
return RpcRequest(
payload={
"intent_type": "buy",
"intent_id": intent_id,
"trading_date": DAY.isoformat(),
"portfolio_id": portfolio_id,
"qty": 10,
},
correlation_id=intent_id,
)
def test_buy_admission_returns_admitted_and_transitions_slot():
repo, _, intents = _wire()
handler = make_intent_rpc_handler(intents)
resp = handler(_buy_req("buy-1"))
assert resp.payload["status"] == "admitted"
assert resp.payload["slot_id"]
from uuid import UUID
slot = repo.fetch_slot(UUID(resp.payload["slot_id"]))
assert slot.status is SlotState.PENDING_BUY and slot.symbol == "005930"
def test_duplicate_correlation_id_dedups_via_intent_log():
"""REQ-023 AC-1: same intent_id ⇒ slot transition exactly once."""
repo, _, intents = _wire()
handler = make_intent_rpc_handler(intents)
r1 = handler(_buy_req("buy-dup"))
r2 = handler(_buy_req("buy-dup"))
assert r1.payload == r2.payload
pending = [s for s in repo.list_slots(DAY) if s.status is SlotState.PENDING_BUY]
assert len(pending) == 1
def test_buy_rejected_when_no_idle_slot():
repo, _, intents = _wire()
handler = make_intent_rpc_handler(intents)
for i in range(3):
assert handler(_buy_req(f"buy-{i}")).payload["status"] == "admitted"
resp = handler(_buy_req("overflow"))
assert resp.payload["status"] == "rejected"
assert resp.payload["reason"] == "no_idle_slot"
def test_sell_admission_from_holding():
repo, svc, intents = _wire()
handler = make_intent_rpc_handler(intents)
sid = handler(_buy_req("buy-h")).payload["slot_id"]
from uuid import UUID
svc.transit_slot(UUID(sid), SlotState.PENDING_BUY, SlotState.HOLDING,
reason="filled", actor="t")
resp = handler(RpcRequest(
payload={"intent_type": "sell", "intent_id": "sell-h", "slot_id": sid},
correlation_id="sell-h",
))
assert resp.payload["status"] == "admitted"
assert repo.fetch_slot(UUID(sid)).status is SlotState.PENDING_SELL
def test_bad_payload_returns_rejected_not_exception():
"""Handler must not raise — bad input ⇒ structured rejection."""
_, _, intents = _wire()
handler = make_intent_rpc_handler(intents)
# missing slot_id for sell
resp = handler(RpcRequest(
payload={"intent_type": "sell", "intent_id": "bad"},
correlation_id="bad",
))
assert resp.payload["status"] == "rejected"
assert resp.payload["reason"].startswith("bad_request:")
def test_unknown_intent_type_rejected():
_, _, intents = _wire()
handler = make_intent_rpc_handler(intents)
resp = handler(RpcRequest(
payload={"intent_type": "ping", "intent_id": "x"},
correlation_id="x",
))
assert resp.payload["status"] == "rejected"
assert "unknown_intent_type" in resp.payload["reason"]
def test_correlation_id_is_used_as_intent_id_when_missing_in_payload():
"""The transport's correlation_id is the canonical idempotency key."""
repo, _, intents = _wire()
handler = make_intent_rpc_handler(intents)
req = RpcRequest(
payload={
"intent_type": "buy",
"trading_date": DAY.isoformat(),
"portfolio_id": "PF-1",
"qty": 5,
},
correlation_id="cid-only",
)
r1 = handler(req)
r2 = handler(req)
assert r1.payload["status"] == "admitted"
assert r1.payload == r2.payload
pending = [s for s in repo.list_slots(DAY) if s.status is SlotState.PENDING_BUY]
assert len(pending) == 1
# ---- dcy-011 / REQ-007/021: portfolio_id required + symbol resolve ----------
def test_buy_without_portfolio_id_rejected():
"""FR-1 / S-1: missing portfolio_id → portfolio_id_required reject."""
repo, _, intents = _wire()
handler = make_intent_rpc_handler(intents)
req = RpcRequest(
payload={"intent_type": "buy", "intent_id": "no-pf",
"trading_date": DAY.isoformat(), "qty": 5},
correlation_id="no-pf",
)
resp = handler(req)
assert resp.payload["status"] == "rejected"
assert resp.payload["reason"] == "portfolio_id_required"
def test_buy_unknown_portfolio_rejected():
"""FR-3 / S-1: portfolio_id absent from universe → unknown_portfolio reject."""
repo = InMemorySlotRepository()
svc = SlotService(repo)
intents = IntentService(svc, repo, InMemoryIntentStore(),
resolve_symbol=lambda pid: None) # universe empty
svc.preallocate_daily_slots(DAY, 3)
handler = make_intent_rpc_handler(intents)
resp = handler(_buy_req("u1", portfolio_id="PF-X"))
assert resp.payload["status"] == "rejected"
assert resp.payload["reason"] == "unknown_portfolio"
def test_buy_symbol_resolved_from_universe():
"""FR-2 / S-1: symbol is resolved server-side from portfolio_id (no client symbol)."""
repo, _, intents = _wire() # resolver → "005930"
handler = make_intent_rpc_handler(intents)
resp = handler(_buy_req("r1", portfolio_id="PF-9"))
assert resp.payload["status"] == "admitted"
from uuid import UUID
slot = repo.fetch_slot(UUID(resp.payload["slot_id"]))
assert slot.symbol == "005930" and slot.portfolio_id == "PF-9"