feat(slot): BAT-027 M2/M3 — 상태머신 inactive 재정의 + 인스턴스 스코프 advisory lock (dcy-020/REQ-057)

안 B 점진의 2/3단계. runtime 무변경(idle/closed 별칭 흡수)으로 cascade 통제.

- state.py: SlotState.INACTIVE 추가 + idle/closed 별칭 normalize_state(); 전이 집합
  inactive 기준 재정의(inactive↔pending_buy↔holding↔pending_sell), closed→idle 제거;
  is_allowed_transition 양쪽 정규화; slot_advisory_lock_id(instance_key) 헬퍼
- service.py: SlotService(instance_key) + advisory lock 인스턴스 스코프(self._lock_id)
- __init__: normalize_state/slot_advisory_lock_id export; daemon: instance_key 전달
- 테스트 갱신: test_state(전이/멤버7/락/size12), test_service(closed→idle 제거→reallocation),
  test_slot_entry_count, test_postgresql_repository(closed→idle 거부+reallocation)

검증: 단위 375 passed / 35 skipped, PG-gated(trex_core_test) 8 passed
(마이그레이션 009 드리프트 + lifecycle/reallocation), ruff clean.

REQ-056/057 은 토대만 충족 → Approved 유지(entry_count/trading_date drop·literal
inactive 전면 전환은 BAT-δ; confirm-req-implemented 는 dcy-020 후속 배치 완료 후).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-10 10:53:39 +09:00
co-authored by Claude Opus 4.8
parent 86c892aa0c
commit 017b8185e0
10 changed files with 232 additions and 151 deletions
+36 -66
View File
@@ -133,78 +133,48 @@ class TestTransitHappyPath:
# ----------------------------------------------------------------------------
# transit_slot — closed → idle atomic counter (REQ-002 AC-3)
# transit_slot — closed→idle recovery REMOVED (dcy-020 / REQ-057)
# ----------------------------------------------------------------------------
class TestClosedToIdleRecovery:
def test_closed_to_idle_resets_fields_and_bumps_counter(
self, service, repo, trading_day,
):
class TestClosedRecoveryRemoved:
def test_closed_to_idle_is_rejected(self, service, repo, trading_day):
"""dcy-020: closed→idle recovery is removed (idle/closed both = inactive)."""
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
# drive to closed
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", 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")
with pytest.raises(SlotTransitionError):
service.transit_slot(slot.slot_id, SlotState.CLOSED, SlotState.IDLE,
reason="recovery", actor="a")
def test_repeated_lifecycle_accumulates_entry_count(
def test_reuse_via_closed_to_pending_buy_reallocation(
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
"""Asset-centric reuse: a closed slot is reactivated via closed→pending_buy
(dcy-019 reallocation), not closed→idle recovery."""
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", symbol="005930")
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")
realloc = service.transit_slot(
slot.slot_id, SlotState.CLOSED, SlotState.PENDING_BUY,
reason="reallocate", actor="a", symbol="000660",
)
assert realloc.status is SlotState.PENDING_BUY
assert realloc.symbol == "000660" # clean-slate
assert realloc.entry_count == 2 # cumulative
# ----------------------------------------------------------------------------
+6 -5
View File
@@ -68,14 +68,15 @@ class TestEntryCount:
# 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):
def test_preserved_while_closed(self, service, repo, trading_day):
# dcy-020: closed→idle recovery removed; entry_count persists on the
# closed slot until the next allocation (closed→pending_buy) bumps it.
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 = repo.fetch_slot(slot.slot_id)
assert closed.status is SlotState.CLOSED
assert closed.entry_count == 1 # slot-scoped cumulative, preserved
# ----------------------------------------------------------------------------
+53 -30
View File
@@ -1,6 +1,7 @@
"""State machine unit tests — verify exactly the allowed transition families.
"""State machine unit tests — asset-centric redefinition (dcy-020 / REQ-057).
Ported from trex-orbit (dcy-001 FR-3). Covers REQ-002 / REQ-003.
`inactive` is the canonical no-position state; `idle`/`closed` are aliases that
normalize to `inactive`. `closed->idle` recovery is removed. Covers REQ-057.
"""
from __future__ import annotations
@@ -11,12 +12,15 @@ from trex_core.domain.slot.state import (
SLOT_ADVISORY_LOCK_ID,
SlotState,
is_allowed_transition,
normalize_state,
slot_advisory_lock_id,
)
def test_slot_state_has_six_members():
"""6 states per dcy-001 5.3.5.1."""
def test_slot_state_members():
"""dcy-020: 5 canonical + 2 aliases(idle/closed) = 7 enum members."""
assert {s.value for s in SlotState} == {
"inactive",
"idle",
"pending_buy",
"holding",
@@ -26,33 +30,53 @@ def test_slot_state_has_six_members():
}
def test_idle_and_closed_normalize_to_inactive():
assert normalize_state(SlotState.IDLE) is SlotState.INACTIVE
assert normalize_state(SlotState.CLOSED) is SlotState.INACTIVE
assert normalize_state(SlotState.INACTIVE) is SlotState.INACTIVE
assert normalize_state(SlotState.HOLDING) is SlotState.HOLDING
def test_advisory_lock_id_is_stable_constant():
"""SLOT_ADVISORY_LOCK_ID must not change between releases (REQ-002 NFR-1)."""
"""SLOT_ADVISORY_LOCK_ID base must not change between releases (REQ-002 NFR-1)."""
assert isinstance(SLOT_ADVISORY_LOCK_ID, int)
assert SLOT_ADVISORY_LOCK_ID == 0x5107_4D31
def test_slot_advisory_lock_id_is_instance_scoped():
"""dcy-020/REQ-057: distinct instance_key -> distinct lock id; same -> same."""
a = slot_advisory_lock_id("inst-a")
b = slot_advisory_lock_id("inst-b")
assert a != b
assert slot_advisory_lock_id("inst-a") == a
# 'default' keeps a stable derived id
assert slot_advisory_lock_id("default") == slot_advisory_lock_id("default")
@pytest.mark.parametrize(
"from_state,to_state",
[
# 1-7. dcy-001 FR-2 base transitions
(SlotState.IDLE, SlotState.PENDING_BUY),
# canonical (inactive-based)
(SlotState.INACTIVE, SlotState.PENDING_BUY),
(SlotState.PENDING_BUY, SlotState.HOLDING),
(SlotState.PENDING_BUY, SlotState.IDLE),
(SlotState.PENDING_BUY, SlotState.INACTIVE),
(SlotState.HOLDING, SlotState.PENDING_SELL),
(SlotState.PENDING_SELL, SlotState.CLOSED),
(SlotState.PENDING_SELL, SlotState.INACTIVE),
(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),
# alias equivalence: idle/closed normalize to inactive
(SlotState.IDLE, SlotState.PENDING_BUY), # idle->pending_buy
(SlotState.CLOSED, SlotState.PENDING_BUY), # closed->pending_buy (reallocation)
(SlotState.PENDING_SELL, SlotState.CLOSED), # sell filled (closed alias)
(SlotState.PENDING_BUY, SlotState.IDLE), # buy rollback (idle alias)
# to error (every non-error)
(SlotState.INACTIVE, SlotState.ERROR),
(SlotState.PENDING_BUY, SlotState.ERROR),
(SlotState.HOLDING, SlotState.ERROR),
(SlotState.PENDING_SELL, SlotState.ERROR),
(SlotState.CLOSED, SlotState.ERROR),
# operator manual resolve (REQ-004)
(SlotState.ERROR, SlotState.IDLE),
# operator resolve out of error
(SlotState.ERROR, SlotState.INACTIVE),
(SlotState.ERROR, SlotState.IDLE), # alias
(SlotState.ERROR, SlotState.HOLDING),
],
)
@@ -63,22 +87,18 @@ def test_allowed_transition(from_state: SlotState, to_state: SlotState):
@pytest.mark.parametrize(
"from_state,to_state",
[
# explicitly disallowed: skipping intermediate states
(SlotState.IDLE, SlotState.HOLDING),
(SlotState.IDLE, SlotState.PENDING_SELL),
(SlotState.IDLE, SlotState.CLOSED),
(SlotState.HOLDING, SlotState.IDLE),
# closed->idle recovery REMOVED (normalizes to inactive self-loop)
(SlotState.CLOSED, SlotState.IDLE),
# skipping intermediate states
(SlotState.INACTIVE, SlotState.HOLDING),
(SlotState.INACTIVE, SlotState.PENDING_SELL),
(SlotState.HOLDING, SlotState.INACTIVE),
(SlotState.HOLDING, SlotState.CLOSED),
(SlotState.PENDING_BUY, SlotState.CLOSED),
(SlotState.PENDING_BUY, SlotState.PENDING_SELL),
(SlotState.PENDING_SELL, SlotState.IDLE),
(SlotState.PENDING_SELL, SlotState.PENDING_BUY),
(SlotState.CLOSED, SlotState.HOLDING),
(SlotState.CLOSED, SlotState.PENDING_SELL),
# error has restricted exits — only idle and holding allowed (REQ-004)
# error has restricted exits — only inactive(+aliases) and holding
(SlotState.ERROR, SlotState.PENDING_BUY),
(SlotState.ERROR, SlotState.PENDING_SELL),
(SlotState.ERROR, SlotState.CLOSED),
(SlotState.ERROR, SlotState.ERROR),
],
)
@@ -87,11 +107,14 @@ def test_disallowed_transition(from_state: SlotState, to_state: SlotState):
def test_self_loops_are_not_allowed():
"""No state may transition to itself."""
"""No state may transition to itself (including inactive and its aliases)."""
for s in SlotState:
assert not is_allowed_transition(s, s)
# alias self-loops also rejected
assert not is_allowed_transition(SlotState.IDLE, SlotState.CLOSED)
assert not is_allowed_transition(SlotState.CLOSED, SlotState.IDLE)
def test_allowed_transitions_set_size():
"""8 base (incl. dcy-019 closed->pending_buy) + 5 to-error + 2 operator-resolve = 15."""
assert len(ALLOWED_TRANSITIONS) == 15
"""6 base (inactive-canonical) + 4 to-error + 2 operator-resolve = 12."""
assert len(ALLOWED_TRANSITIONS) == 12