매도(sell) 주문이 현재가가 아닌 매수가(entry_price) 지정가로 나가던 버그(issue #10) 정정. 슬롯의 매수 전용 entry_price 를 side 무관 "현재 pending 주문 지정가" limit_price 로 내부 rename 하고, pending 이탈(→holding/→closed) 시 clear 해 매수 지정가가 매도로 누수되는 경로를 구조적으로 제거. 거버넌스: 전부 change-req (신규 REQ 없음, dcy-012 OQ-3). - REQ-002: Slot entry_price→limit_price rename + clear-on-exit 생애주기 - REQ-006: daily_slot 컬럼 rename 마이그레이션 006 (idempotent) + persistence 매핑 - REQ-013: _dispatch 가 slot.limit_price 단일 필드로 가격/주문유형 결정 - REQ-007: SellIntent/sell payload optional limit_price + _admit_sell 운반 - REQ-036: SlotService.sell optional 가격 → 자율 매도(safety-sell/kill-switch) 시장가 - REQ-003: 컬럼 계약/드리프트 가드 limit_price 반영 - REQ-015: runtime-flows/interface-contract/data-model 정합 매도 정책(OQ-1 하이브리드): 가격 지정→지정가("00"), 미지정→시장가("01"). 자율 매도는 가격 미전달 → 항상 시장가 (손절 미체결 pending_sell 갇힘 방지, issue #9 연계). 검증: 단위 286 passed/32 skipped, 인프라 게이트(PG+RabbitMQ) 318 passed, ruff clean. 신규 test_sell_pricing(recording broker)로 지정가 매수 슬롯의 매도가 매수가 재사용 안 함을 직접 검증. BAT-016 release-candidate. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
378 lines
15 KiB
Python
378 lines
15 KiB
Python
"""SlotService unit tests — pre-allocation, transitions, atomic counter, capacity.
|
|
|
|
Ported from trex-orbit (dcy-001 FR-3). Covers REQ-002 AC-1 ~ AC-6.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import threading
|
|
import time
|
|
from datetime import date
|
|
from uuid import uuid4
|
|
|
|
import pytest
|
|
|
|
from trex_core.domain.slot import (
|
|
SlotNotFoundError,
|
|
SlotService,
|
|
SlotState,
|
|
SlotStateMismatchError,
|
|
SlotTransitionError,
|
|
)
|
|
from trex_core.domain.slot.in_memory_repository import InMemorySlotRepository
|
|
|
|
|
|
@pytest.fixture
|
|
def trading_day():
|
|
return date(2026, 5, 24)
|
|
|
|
|
|
@pytest.fixture
|
|
def repo():
|
|
return InMemorySlotRepository()
|
|
|
|
|
|
@pytest.fixture
|
|
def service(repo):
|
|
return SlotService(repo)
|
|
|
|
|
|
def _one_idle(repo, trading_day):
|
|
return repo.find_idle_slot(trading_day)
|
|
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# preallocate
|
|
# ----------------------------------------------------------------------------
|
|
class TestPreallocate:
|
|
def test_creates_idle_slots(self, service, repo, trading_day):
|
|
inserted = service.preallocate_daily_slots(trading_day, 10)
|
|
assert inserted == 10
|
|
assert len(repo.list_slots(trading_day)) == 10
|
|
assert all(s.status is SlotState.IDLE for s in repo.list_slots(trading_day))
|
|
|
|
def test_idempotent_second_call_returns_zero(self, service, repo, trading_day):
|
|
"""REQ-002 AC-4: same trading_date → 0 inserted on repeat."""
|
|
service.preallocate_daily_slots(trading_day, 5)
|
|
inserted = service.preallocate_daily_slots(trading_day, 5)
|
|
assert inserted == 0
|
|
assert len(repo.list_slots(trading_day)) == 5
|
|
|
|
def test_zero_or_negative_count_rejected(self, service, trading_day):
|
|
with pytest.raises(ValueError):
|
|
service.preallocate_daily_slots(trading_day, 0)
|
|
with pytest.raises(ValueError):
|
|
service.preallocate_daily_slots(trading_day, -1)
|
|
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# transit_slot — happy paths
|
|
# ----------------------------------------------------------------------------
|
|
class TestTransitHappyPath:
|
|
def test_idle_to_pending_buy_records_fields(self, service, repo, trading_day):
|
|
service.preallocate_daily_slots(trading_day, 1)
|
|
slot = _one_idle(repo, trading_day)
|
|
updated = service.transit_slot(
|
|
slot.slot_id,
|
|
SlotState.IDLE,
|
|
SlotState.PENDING_BUY,
|
|
reason="orb_breakout",
|
|
actor="buy_decision_thread",
|
|
symbol="005930",
|
|
qty=10,
|
|
allocated_capital=1_000_000,
|
|
strategy_id="orb_v1",
|
|
)
|
|
assert updated.status is SlotState.PENDING_BUY
|
|
assert updated.symbol == "005930"
|
|
assert updated.qty == 10
|
|
assert updated.strategy_id == "orb_v1"
|
|
# log appended
|
|
log = repo.transition_log_for(slot.slot_id)
|
|
assert len(log) == 1
|
|
assert log[0].from_state is SlotState.IDLE
|
|
assert log[0].to_state is SlotState.PENDING_BUY
|
|
assert log[0].reason == "orb_breakout"
|
|
assert log[0].actor == "buy_decision_thread"
|
|
|
|
def test_pending_buy_to_holding(self, service, repo, trading_day):
|
|
service.preallocate_daily_slots(trading_day, 1)
|
|
slot = _one_idle(repo, trading_day)
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
|
|
reason="orb_breakout", actor="buy", symbol="005930",
|
|
)
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
|
|
reason="filled", actor="order_exec",
|
|
avg_price=70_000,
|
|
)
|
|
cur = repo.fetch_slot(slot.slot_id)
|
|
assert cur.status is SlotState.HOLDING
|
|
assert cur.avg_price == 70_000
|
|
# dcy-012: limit_price (pending order limit) is cleared on entering holding.
|
|
assert cur.limit_price is None
|
|
|
|
def test_pending_buy_to_idle_rollback_preserves_symbol_until_recovery(
|
|
self, service, repo, trading_day,
|
|
):
|
|
"""pending_buy -> idle (rejection rollback) is allowed by state machine.
|
|
|
|
Note: this rollback does NOT bump daily_symbol_entries (only closed→idle does).
|
|
"""
|
|
service.preallocate_daily_slots(trading_day, 1)
|
|
slot = _one_idle(repo, trading_day)
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
|
|
reason="orb_breakout", actor="buy", symbol="005930",
|
|
)
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.PENDING_BUY, SlotState.IDLE,
|
|
reason="broker_reject:001", actor="order_exec",
|
|
)
|
|
assert repo.get_symbol_entry_count(trading_day, "005930") == 0
|
|
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# transit_slot — closed → idle atomic counter (REQ-002 AC-3)
|
|
# ----------------------------------------------------------------------------
|
|
class TestClosedToIdleRecovery:
|
|
def test_closed_to_idle_resets_fields_and_bumps_counter(
|
|
self, service, repo, trading_day,
|
|
):
|
|
service.preallocate_daily_slots(trading_day, 1)
|
|
slot = _one_idle(repo, trading_day)
|
|
# full lifecycle: idle -> pending_buy -> holding -> pending_sell -> closed -> idle
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
|
|
reason="orb_breakout", actor="buy", symbol="005930", qty=10,
|
|
)
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
|
|
reason="filled", actor="oe", avg_price=70_000,
|
|
)
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.HOLDING, SlotState.PENDING_SELL,
|
|
reason="stop_loss", actor="sell",
|
|
)
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.PENDING_SELL, SlotState.CLOSED,
|
|
reason="filled", actor="oe",
|
|
)
|
|
# before recovery: count = 0
|
|
assert repo.get_symbol_entry_count(trading_day, "005930") == 0
|
|
result = service.transit_slot(
|
|
slot.slot_id, SlotState.CLOSED, SlotState.IDLE,
|
|
reason="recovery", actor="oe",
|
|
)
|
|
# fields cleared
|
|
assert result.status is SlotState.IDLE
|
|
assert result.symbol is None
|
|
assert result.qty is None
|
|
assert result.avg_price is None
|
|
assert result.allocated_capital is None
|
|
# counter incremented atomically (REQ-002 AC-3)
|
|
assert repo.get_symbol_entry_count(trading_day, "005930") == 1
|
|
# transition log retains symbol audit
|
|
log = repo.transition_log_for(slot.slot_id)
|
|
assert log[-1].from_state is SlotState.CLOSED
|
|
assert log[-1].to_state is SlotState.IDLE
|
|
|
|
def test_repeated_lifecycle_accumulates_entry_count(
|
|
self, service, repo, trading_day,
|
|
):
|
|
"""Two full lifecycles of same symbol → entry_count = 2."""
|
|
service.preallocate_daily_slots(trading_day, 2)
|
|
for _ in range(2):
|
|
slot = _one_idle(repo, trading_day)
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
|
|
reason="r", actor="a", symbol="005930",
|
|
)
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
|
|
reason="r", actor="a",
|
|
)
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.HOLDING, SlotState.PENDING_SELL,
|
|
reason="r", actor="a",
|
|
)
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.PENDING_SELL, SlotState.CLOSED,
|
|
reason="r", actor="a",
|
|
)
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.CLOSED, SlotState.IDLE,
|
|
reason="r", actor="a",
|
|
)
|
|
assert service.get_today_entry_count(trading_day, "005930") == 2
|
|
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# transit_slot — rejections
|
|
# ----------------------------------------------------------------------------
|
|
class TestTransitRejections:
|
|
def test_disallowed_transition_raises(self, service, repo, trading_day):
|
|
service.preallocate_daily_slots(trading_day, 1)
|
|
slot = _one_idle(repo, trading_day)
|
|
with pytest.raises(SlotTransitionError):
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.IDLE, SlotState.HOLDING,
|
|
reason="x", actor="a",
|
|
)
|
|
|
|
def test_state_mismatch_raises_when_current_state_drifted(
|
|
self, service, repo, trading_day,
|
|
):
|
|
"""Race detection — if slot already advanced, transit_slot from old state fails."""
|
|
service.preallocate_daily_slots(trading_day, 1)
|
|
slot = _one_idle(repo, trading_day)
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
|
|
reason="r", actor="a",
|
|
)
|
|
with pytest.raises(SlotStateMismatchError):
|
|
# caller still thinks status=idle but it's pending_buy
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
|
|
reason="r", actor="a",
|
|
)
|
|
|
|
def test_unknown_slot_raises(self, service):
|
|
with pytest.raises(SlotNotFoundError):
|
|
service.transit_slot(
|
|
uuid4(), SlotState.IDLE, SlotState.PENDING_BUY,
|
|
reason="r", actor="a",
|
|
)
|
|
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# operator error → idle/holding (REQ-004)
|
|
# ----------------------------------------------------------------------------
|
|
class TestOperatorResolve:
|
|
def test_error_to_idle_via_operator(self, service, repo, trading_day):
|
|
service.preallocate_daily_slots(trading_day, 1)
|
|
slot = _one_idle(repo, trading_day)
|
|
# force into error
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.IDLE, SlotState.ERROR,
|
|
reason="reconcile_mismatch", actor="system",
|
|
)
|
|
result = service.transit_slot(
|
|
slot.slot_id, SlotState.ERROR, SlotState.IDLE,
|
|
reason="broker confirmed no position", actor="operator:alice",
|
|
)
|
|
assert result.status is SlotState.IDLE
|
|
log = repo.transition_log_for(slot.slot_id)
|
|
assert log[-1].actor == "operator:alice"
|
|
assert "broker confirmed" in log[-1].reason
|
|
|
|
def test_error_to_pending_buy_rejected(self, service, repo, trading_day):
|
|
service.preallocate_daily_slots(trading_day, 1)
|
|
slot = _one_idle(repo, trading_day)
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.IDLE, SlotState.ERROR,
|
|
reason="r", actor="s",
|
|
)
|
|
with pytest.raises(SlotTransitionError):
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.ERROR, SlotState.PENDING_BUY,
|
|
reason="r", actor="operator:alice",
|
|
)
|
|
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# compute_slot_capacity (REQ-002 AC-6)
|
|
# ----------------------------------------------------------------------------
|
|
class TestCapacity:
|
|
def test_all_idle(self, service, trading_day):
|
|
service.preallocate_daily_slots(trading_day, 10)
|
|
cap = service.compute_slot_capacity(trading_day, 10)
|
|
assert cap.idle_count == 10
|
|
assert cap.holding_count == 0
|
|
assert cap.pending_count == 0
|
|
assert cap.total_slots == 10
|
|
assert cap.scarcity_ratio == 0.0
|
|
|
|
def test_mixed_states(self, service, repo, trading_day):
|
|
service.preallocate_daily_slots(trading_day, 10)
|
|
# move 3 to pending_buy + 2 to holding
|
|
slots = repo.list_slots(trading_day)
|
|
for s in slots[:3]:
|
|
service.transit_slot(
|
|
s.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
|
|
reason="r", actor="a",
|
|
)
|
|
for s in slots[3:5]:
|
|
service.transit_slot(
|
|
s.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
|
|
reason="r", actor="a",
|
|
)
|
|
service.transit_slot(
|
|
s.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
|
|
reason="r", actor="a",
|
|
)
|
|
cap = service.compute_slot_capacity(trading_day, 10)
|
|
assert cap.idle_count == 5
|
|
assert cap.pending_count == 3
|
|
assert cap.holding_count == 2
|
|
assert cap.scarcity_ratio == pytest.approx(0.5)
|
|
|
|
def test_zero_total_rejected(self, service, trading_day):
|
|
with pytest.raises(ValueError):
|
|
service.compute_slot_capacity(trading_day, 0)
|
|
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# advisory lock serialization (REQ-002 AC-5)
|
|
# ----------------------------------------------------------------------------
|
|
class TestAdvisoryLockSerialization:
|
|
def test_concurrent_transitions_are_serialized(self, service, repo, trading_day):
|
|
"""Two threads competing for the same slot — one must observe state mismatch."""
|
|
service.preallocate_daily_slots(trading_day, 1)
|
|
slot = _one_idle(repo, trading_day)
|
|
|
|
results: dict[str, Exception | None] = {}
|
|
|
|
def worker(name: str):
|
|
try:
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
|
|
reason=f"r-{name}", actor=name,
|
|
)
|
|
results[name] = None
|
|
except Exception as exc: # noqa: BLE001
|
|
results[name] = exc
|
|
|
|
t1 = threading.Thread(target=worker, args=("buy_thread",))
|
|
t2 = threading.Thread(target=worker, args=("sell_thread",))
|
|
t1.start()
|
|
t2.start()
|
|
t1.join()
|
|
t2.join()
|
|
|
|
# exactly one succeeded; the other observed state mismatch
|
|
successes = [k for k, v in results.items() if v is None]
|
|
failures = [k for k, v in results.items() if v is not None]
|
|
assert len(successes) == 1
|
|
assert len(failures) == 1
|
|
assert isinstance(failures[0] and results[failures[0]], SlotStateMismatchError)
|
|
|
|
def test_lock_hold_time_under_50ms(self, service, trading_day):
|
|
"""REQ-002 AC-5 numeric: transition under the in-memory repo finishes < 50 ms."""
|
|
service.preallocate_daily_slots(trading_day, 1)
|
|
slot = list(service.compute_slot_capacity.__self__._repo.list_slots(trading_day))[0] # type: ignore[attr-defined]
|
|
t0 = time.perf_counter()
|
|
service.transit_slot(
|
|
slot.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
|
|
reason="r", actor="a",
|
|
)
|
|
elapsed_ms = (time.perf_counter() - t0) * 1000
|
|
assert elapsed_ms < 50.0, f"transition took {elapsed_ms:.2f} ms"
|
|
|
|
|
|
# ----------------------------------------------------------------------------
|
|
# get_today_entry_count (REQ-001 + REQ-002 boundary)
|
|
# ----------------------------------------------------------------------------
|
|
def test_get_today_entry_count_for_unseen_symbol_is_zero(service, trading_day):
|
|
assert service.get_today_entry_count(trading_day, "999999") == 0
|