feat(slot): slot entry_count + closed-slot reallocation (dcy-019, BAT-025) + REL-005

dcy-019/issue #18: slot 자원을 진입 횟수 기준으로 고르게 재사용하고 idle 소진 시
closed 슬롯을 직접 재할당한다. 거버넌스는 전부 change-req(신규 REQ 없음).

- 도메인(REQ-002): Slot.entry_count(기본 0) + EXPECTED_SLOT_FIELDS, 상태 머신
  closed→pending_buy 신규 전이(base 8→9, ALLOWED_TRANSITIONS 14→15),
  _apply_transition_fields closed→pending_buy clean-slate + →pending_buy 시 +1
- 영속화(REQ-006): 멱등 마이그레이션 008(entry_count), flat 매핑,
  find_allocatable_slot(idle∪closed, entry_count→updated_at→slot_id) + in-memory 동등
- admission(REQ-007): _admit_buy find_idle_slot→find_allocatable_slot + from_state=slot.status
- 테스트(REQ-003): 전이 카운트/계약 가드 정합 + test_slot_entry_count.py / test_buy_admission_reallocation.py
- 문서(REQ-009): data-model.md / runtime-flows.md 정합
- 기존 daily_symbol_entries(symbol-scoped) 분리·미변경

BAT-025(release-candidate) delivery + change-req REQ-002/003/006/007/009(CHG-20260609-01).
REL-005(confirmed, app-service): BAT-024+BAT-025 묶음. operator-facing run-the-app
스모크로 enter --forced-close-at(BAT-024)·closed 재할당(BAT-025) 실 데몬 검증
(실 PG 마이그레이션 008 round-trip 포함).

검증: 단위 366 passed / 35 skipped(KIS sandbox 1건 deselect — live .env 환경 의존), ruff clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-09 14:49:22 +09:00
co-authored by Claude Opus 4.8
parent 941d324899
commit 6e8e79660c
28 changed files with 912 additions and 26 deletions
@@ -0,0 +1,85 @@
"""dcy-019 / BAT-025: buy admission reallocates closed slots (REQ-007).
When no idle slot remains, _admit_buy must admit into a CLOSED slot via the new
closed→pending_buy transition, ordered by entry_count (least-entered first).
"""
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 BuyIntent, IntentService
from trex_core.domain.slot import SlotService, SlotState
from trex_core.domain.slot.in_memory_repository import InMemorySlotRepository
DAY = date(2026, 6, 9)
def _cycle_to_closed(svc, slot_id):
svc.transit_slot(slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
reason="r", actor="a", symbol="005930")
svc.transit_slot(slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
reason="r", actor="a", avg_price=70_000)
svc.transit_slot(slot_id, SlotState.HOLDING, SlotState.PENDING_SELL,
reason="r", actor="a")
svc.transit_slot(slot_id, SlotState.PENDING_SELL, SlotState.CLOSED,
reason="r", actor="a")
def test_admits_into_closed_slot_when_no_idle_remains():
repo = InMemorySlotRepository()
svc = SlotService(repo)
intents = IntentService(svc, repo, InMemoryIntentStore())
svc.preallocate_daily_slots(DAY, 1)
slot = repo.find_idle_slot(DAY)
_cycle_to_closed(svc, slot.slot_id)
assert repo.find_idle_slot(DAY) is None # nothing idle
d = intents.submit_buy(BuyIntent(
intent_id="buy-realloc", trading_date=DAY,
symbol="000660", qty=3, portfolio_id="PF-1",
))
assert d.status == "admitted"
realloc = repo.fetch_slot(d.slot_id)
assert realloc.status is SlotState.PENDING_BUY
assert realloc.symbol == "000660"
# second entry into the same physical slot
assert realloc.entry_count == 2
def test_rejects_when_no_idle_and_no_closed():
repo = InMemorySlotRepository()
svc = SlotService(repo)
intents = IntentService(svc, repo, InMemoryIntentStore())
svc.preallocate_daily_slots(DAY, 1)
slot = repo.find_idle_slot(DAY)
# take it to holding (not closed, not idle → not allocatable)
svc.transit_slot(slot.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
reason="r", actor="a", symbol="005930")
svc.transit_slot(slot.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
reason="r", actor="a", avg_price=70_000)
d = intents.submit_buy(BuyIntent(
intent_id="buy-none", trading_date=DAY,
symbol="000660", portfolio_id="PF-1",
))
assert d.status == "rejected"
assert d.reason == "no_idle_slot"
def test_prefers_idle_over_closed():
repo = InMemorySlotRepository()
svc = SlotService(repo)
intents = IntentService(svc, repo, InMemoryIntentStore())
svc.preallocate_daily_slots(DAY, 2)
slots = repo.list_slots(DAY)
_cycle_to_closed(svc, slots[0].slot_id) # one closed (entry_count=1)
d = intents.submit_buy(BuyIntent(
intent_id="buy-prefer-idle", trading_date=DAY,
symbol="000660", portfolio_id="PF-1",
))
assert d.status == "admitted"
chosen = repo.fetch_slot(d.slot_id)
# the fresh idle slot (entry_count 0→1) is preferred over the closed one
assert chosen.entry_count == 1
+165
View File
@@ -0,0 +1,165 @@
"""dcy-019 / BAT-025: slot-scoped entry_count + closed-slot reallocation.
Covers REQ-002 (entry_count field + closed→pending_buy clean-slate transition)
and REQ-006 (find_allocatable_slot selector ordering over idle ∪ closed).
"""
from __future__ import annotations
from datetime import date
import pytest
from trex_core.domain.slot import SlotService, SlotState
from trex_core.domain.slot.in_memory_repository import InMemorySlotRepository
@pytest.fixture
def trading_day():
return date(2026, 6, 9)
@pytest.fixture
def repo():
return InMemorySlotRepository()
@pytest.fixture
def service(repo):
return SlotService(repo)
def _cycle_to_closed(service, slot_id, symbol="005930"):
"""Drive a slot idle→pending_buy→holding→pending_sell→closed."""
service.transit_slot(slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
reason="r", actor="a", symbol=symbol)
service.transit_slot(slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
reason="r", actor="a", avg_price=70_000)
service.transit_slot(slot_id, SlotState.HOLDING, SlotState.PENDING_SELL,
reason="r", actor="a")
service.transit_slot(slot_id, SlotState.PENDING_SELL, SlotState.CLOSED,
reason="r", actor="a")
# ----------------------------------------------------------------------------
# entry_count increment (REQ-002 FR-4)
# ----------------------------------------------------------------------------
class TestEntryCount:
def test_new_slot_starts_at_zero(self, service, repo, trading_day):
service.preallocate_daily_slots(trading_day, 1)
slot = repo.find_idle_slot(trading_day)
assert slot.entry_count == 0
def test_increments_on_each_pending_buy(self, service, repo, trading_day):
service.preallocate_daily_slots(trading_day, 1)
slot = repo.find_idle_slot(trading_day)
updated = service.transit_slot(
slot.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
reason="r", actor="a", symbol="005930",
)
assert updated.entry_count == 1
def test_not_incremented_on_non_buy_transitions(self, service, repo, trading_day):
service.preallocate_daily_slots(trading_day, 1)
slot = repo.find_idle_slot(trading_day)
service.transit_slot(slot.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
reason="r", actor="a", symbol="005930")
held = service.transit_slot(slot.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
reason="r", actor="a")
# holding entry does not bump the per-slot entry counter
assert held.entry_count == 1
def test_preserved_across_closed_to_idle_recovery(self, service, repo, trading_day):
service.preallocate_daily_slots(trading_day, 1)
slot = repo.find_idle_slot(trading_day)
_cycle_to_closed(service, slot.slot_id)
recovered = service.transit_slot(slot.slot_id, SlotState.CLOSED, SlotState.IDLE,
reason="recovery", actor="a")
# entry_count is slot-scoped cumulative; recovery preserves it
assert recovered.entry_count == 1
# ----------------------------------------------------------------------------
# closed → pending_buy direct reallocation (REQ-002 FR / state machine #9)
# ----------------------------------------------------------------------------
class TestClosedReallocation:
def test_closed_to_pending_buy_clean_slate_and_bumps_count(
self, service, repo, trading_day,
):
service.preallocate_daily_slots(trading_day, 1)
slot = repo.find_idle_slot(trading_day)
_cycle_to_closed(service, slot.slot_id, symbol="005930")
closed = repo.fetch_slot(slot.slot_id)
assert closed.status is SlotState.CLOSED
assert closed.entry_count == 1
realloc = service.transit_slot(
slot.slot_id, SlotState.CLOSED, SlotState.PENDING_BUY,
reason="reallocate", actor="a",
symbol="000660", qty=5, allocated_capital=500_000,
limit_price=120_000, strategy_id="orb_v2",
)
# new entry's fields applied
assert realloc.status is SlotState.PENDING_BUY
assert realloc.symbol == "000660"
assert realloc.qty == 5
assert realloc.limit_price == 120_000
assert realloc.strategy_id == "orb_v2"
# entry_count cumulative across reallocation (1 → 2)
assert realloc.entry_count == 2
def test_closed_to_pending_buy_clears_prior_position_when_not_supplied(
self, service, repo, trading_day,
):
"""A reallocation that omits a field must not leak the prior cycle's value."""
service.preallocate_daily_slots(trading_day, 1)
slot = repo.find_idle_slot(trading_day)
# first cycle sets stop_loss/take_profit, then closes
service.transit_slot(slot.slot_id, SlotState.IDLE, SlotState.PENDING_BUY,
reason="r", actor="a", symbol="005930",
stop_loss_price=60_000, take_profit_price=80_000)
service.transit_slot(slot.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
reason="r", actor="a", avg_price=70_000)
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")
# reallocate WITHOUT thresholds → must be cleared, not inherited
realloc = service.transit_slot(
slot.slot_id, SlotState.CLOSED, SlotState.PENDING_BUY,
reason="reallocate", actor="a", symbol="000660",
)
assert realloc.symbol == "000660"
assert realloc.stop_loss_price is None
assert realloc.take_profit_price is None
assert realloc.avg_price is None
# ----------------------------------------------------------------------------
# find_allocatable_slot selector ordering (REQ-006, OQ-2)
# ----------------------------------------------------------------------------
class TestAllocatableSelector:
def test_returns_none_when_no_idle_or_closed(self, service, repo, trading_day):
assert repo.find_allocatable_slot(trading_day) is None
def test_prefers_idle_when_only_idle_present(self, service, repo, trading_day):
service.preallocate_daily_slots(trading_day, 3)
cand = repo.find_allocatable_slot(trading_day)
assert cand is not None and cand.status is SlotState.IDLE
def test_includes_closed_when_no_idle_remains(self, service, repo, trading_day):
service.preallocate_daily_slots(trading_day, 1)
slot = repo.find_idle_slot(trading_day)
_cycle_to_closed(service, slot.slot_id)
# no idle left, but the closed slot is allocatable
cand = repo.find_allocatable_slot(trading_day)
assert cand is not None and cand.status is SlotState.CLOSED
def test_orders_by_entry_count_ascending(self, service, repo, trading_day):
"""A closed slot (entry_count=1) loses to a fresh idle slot (entry_count=0)."""
service.preallocate_daily_slots(trading_day, 2)
slots = repo.list_slots(trading_day)
_cycle_to_closed(service, slots[0].slot_id) # this one now entry_count=1, closed
# the still-idle slot has entry_count 0 and must be chosen first
cand = repo.find_allocatable_slot(trading_day)
assert cand.entry_count == 0
assert cand.status is SlotState.IDLE
+4 -3
View File
@@ -43,6 +43,8 @@ def test_advisory_lock_id_is_stable_constant():
(SlotState.PENDING_SELL, SlotState.CLOSED),
(SlotState.PENDING_SELL, SlotState.HOLDING),
(SlotState.CLOSED, SlotState.IDLE),
# 9. closed-slot direct reallocation (dcy-019 / BAT-025)
(SlotState.CLOSED, SlotState.PENDING_BUY),
# 8. * -> error
(SlotState.IDLE, SlotState.ERROR),
(SlotState.PENDING_BUY, SlotState.ERROR),
@@ -72,7 +74,6 @@ def test_allowed_transition(from_state: SlotState, to_state: SlotState):
(SlotState.PENDING_SELL, SlotState.IDLE),
(SlotState.PENDING_SELL, SlotState.PENDING_BUY),
(SlotState.CLOSED, SlotState.HOLDING),
(SlotState.CLOSED, SlotState.PENDING_BUY),
(SlotState.CLOSED, SlotState.PENDING_SELL),
# error has restricted exits — only idle and holding allowed (REQ-004)
(SlotState.ERROR, SlotState.PENDING_BUY),
@@ -92,5 +93,5 @@ def test_self_loops_are_not_allowed():
def test_allowed_transitions_set_size():
"""7 base + 5 to-error + 2 operator-resolve = 14 transitions."""
assert len(ALLOWED_TRANSITIONS) == 14
"""8 base (incl. dcy-019 closed->pending_buy) + 5 to-error + 2 operator-resolve = 15."""
assert len(ALLOWED_TRANSITIONS) == 15