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
+4
View File
@@ -34,6 +34,8 @@ from trex_core.domain.slot.state import (
SLOT_ADVISORY_LOCK_ID,
SlotState,
is_allowed_transition,
normalize_state,
slot_advisory_lock_id,
)
__all__ = [
@@ -51,4 +53,6 @@ __all__ = [
"SlotTransitionError",
"SlotTransitionRecord",
"is_allowed_transition",
"normalize_state",
"slot_advisory_lock_id",
]
+13 -5
View File
@@ -23,7 +23,11 @@ from trex_core.domain.slot.errors import (
)
from trex_core.domain.slot.models import Slot, SlotCapacity, SlotTransitionRecord
from trex_core.domain.slot.repository import SlotRepository
from trex_core.domain.slot.state import SLOT_ADVISORY_LOCK_ID, SlotState, is_allowed_transition
from trex_core.domain.slot.state import (
SlotState,
is_allowed_transition,
slot_advisory_lock_id,
)
# Sentinel distinguishing "field omitted (keep current)" from "field set to
# None (clear threshold)" in update_thresholds (REQ-040 AC-4 vs AC-5).
@@ -33,8 +37,12 @@ _UNSET: Any = object()
class SlotService:
"""Slot lifecycle service. Race-free transitions via advisory lock + transaction."""
def __init__(self, repository: SlotRepository) -> None:
def __init__(self, repository: SlotRepository, instance_key: str = "default") -> None:
self._repo = repository
# dcy-020/REQ-057: advisory lock is scoped per instance so a shared DB
# does not serialize transitions across instances (NFR-1).
self._instance_key = instance_key
self._lock_id = slot_advisory_lock_id(instance_key)
# ------------------------------------------------------------
# preallocate_daily_slots
@@ -49,7 +57,7 @@ class SlotService:
"""
if count <= 0:
raise ValueError(f"slot count must be > 0, got {count}")
with self._repo.transactional_advisory_lock(SLOT_ADVISORY_LOCK_ID):
with self._repo.transactional_advisory_lock(self._lock_id):
return self._repo.pre_allocate_slots(trading_date, count)
# ------------------------------------------------------------
@@ -96,7 +104,7 @@ class SlotService:
f"transition not allowed: {from_state.value} -> {to_state.value}"
)
with self._repo.transactional_advisory_lock(SLOT_ADVISORY_LOCK_ID):
with self._repo.transactional_advisory_lock(self._lock_id):
slot = self._repo.fetch_slot(slot_id)
if slot is None:
raise SlotNotFoundError(f"slot not found: {slot_id}")
@@ -323,7 +331,7 @@ class SlotService:
the holding state (AC-6). Raises SlotNotFoundError for unknown slots.
The caller (RPC handler) resets the watchdog last_seen_at (AC-3).
"""
with self._repo.transactional_advisory_lock(SLOT_ADVISORY_LOCK_ID):
with self._repo.transactional_advisory_lock(self._lock_id):
slot = self._repo.fetch_slot(slot_id)
if slot is None:
raise SlotNotFoundError(f"slot not found: {slot_id}")
+61 -28
View File
@@ -1,66 +1,99 @@
"""Slot state machine: 6 states + 9 base allowed transitions (REQ-001, REQ-002).
"""Slot state machine (REQ-001, REQ-002; dcy-020/REQ-057 asset-centric redefinition).
The transitions match dcy-001 FR-2 and BAT-001 design, extended by dcy-019 with
`closed -> pending_buy` (closed-slot direct reallocation, BAT-025).
dcy-020 (안 B): the asset-centric permanent slot collapses the pool-model `idle`
(never-bought) and `closed` (sold, now flat) into a single `inactive` (no open
position) state, and removes the `closed -> idle` recovery transition. `idle` and
`closed` are retained as **backward-compatible aliases** that normalize to
`inactive` for transition checks, so existing rows/runtime stay valid until the
cutover (BAT-δ) drops the aliases. The canonical transition set is expressed in
terms of `inactive`.
"""
from __future__ import annotations
import zlib
from enum import Enum
# Shared PostgreSQL advisory lock id for Buy/Sell decision threads and
# operator CLI manual transitions. Single constant so all callers serialize
# through the same lock (REQ-002 NFR-1, dcy-001 R-1).
# Shared PostgreSQL advisory lock base id. dcy-020/REQ-057 (NFR-1): in a shared
# DB the lock is scoped per instance via `slot_advisory_lock_id(instance_key)` so
# one instance's transitions never serialize against another's.
SLOT_ADVISORY_LOCK_ID: int = 0x5107_4D31 # arbitrary mnemonic constant
class SlotState(str, Enum):
"""6-state slot lifecycle (dcy-001 5.3.5.1)."""
def slot_advisory_lock_id(instance_key: str) -> int:
"""Per-instance advisory lock id (dcy-020/REQ-057). Combines the base id with
a stable hash of instance_key so distinct instances take distinct locks while
the same instance always takes the same lock. Result stays in signed-32 range
(pg advisory lock accepts bigint; this keeps it deterministic and small)."""
h = zlib.crc32((instance_key or "default").encode("utf-8")) & 0x7FFF_FFFF
return SLOT_ADVISORY_LOCK_ID ^ h
IDLE = "idle"
class SlotState(str, Enum):
"""Slot lifecycle states. `inactive` is the asset-centric standard
(dcy-020/REQ-057); `idle`/`closed` are retained as aliases normalizing to
`inactive` (removed at cutover, BAT-δ)."""
INACTIVE = "inactive" # dcy-020: no open position (replaces idle/closed)
IDLE = "idle" # alias -> inactive (pool-model lineage; drop at BAT-δ)
PENDING_BUY = "pending_buy"
HOLDING = "holding"
PENDING_SELL = "pending_sell"
CLOSED = "closed"
CLOSED = "closed" # alias -> inactive (pool-model lineage; drop at BAT-δ)
ERROR = "error"
# 9 base allowed transitions (dcy-001 FR-2 + dcy-019). Any pair not in this set
# must be rejected by SlotService.
# Note: `* -> error` is represented as transitions from every non-error state.
# idle/closed are pool-model aliases of the asset-centric `inactive` state.
_INACTIVE_ALIASES: frozenset[SlotState] = frozenset(
{SlotState.IDLE, SlotState.CLOSED, SlotState.INACTIVE}
)
def normalize_state(state: SlotState) -> SlotState:
"""Map pool-model aliases (idle/closed) to the canonical `inactive`."""
return SlotState.INACTIVE if state in _INACTIVE_ALIASES else state
# Canonical base transitions in terms of `inactive` (dcy-020/REQ-057).
# `closed -> idle` recovery is REMOVED (it normalizes to inactive->inactive, a
# disallowed self-loop). `inactive -> pending_buy` covers both the old
# idle->pending_buy and closed->pending_buy (reallocation) families.
_BASE_TRANSITIONS: frozenset[tuple[SlotState, SlotState]] = frozenset(
{
(SlotState.IDLE, SlotState.PENDING_BUY), # 1. buy decision
(SlotState.PENDING_BUY, SlotState.HOLDING), # 2. buy filled
(SlotState.PENDING_BUY, SlotState.IDLE), # 3. buy rejected/rollback
(SlotState.HOLDING, SlotState.PENDING_SELL), # 4. sell decision
(SlotState.PENDING_SELL, SlotState.CLOSED), # 5. sell filled
(SlotState.PENDING_SELL, SlotState.HOLDING), # 6. sell rejected/rollback
(SlotState.CLOSED, SlotState.IDLE), # 7. recovery (with daily_symbol_entries +1)
(SlotState.CLOSED, SlotState.PENDING_BUY), # 9. closed-slot direct reallocation (dcy-019/BAT-025)
(SlotState.INACTIVE, SlotState.PENDING_BUY), # 1. buy decision (activate)
(SlotState.PENDING_BUY, SlotState.HOLDING), # 2. buy filled
(SlotState.PENDING_BUY, SlotState.INACTIVE), # 3. buy rejected/rollback
(SlotState.HOLDING, SlotState.PENDING_SELL), # 4. sell decision
(SlotState.PENDING_SELL, SlotState.INACTIVE), # 5. sell filled (deactivate)
(SlotState.PENDING_SELL, SlotState.HOLDING), # 6. sell rejected/rollback
}
)
# 8th transition family: any non-error state may move to error (operator manual
# resolve uses `error -> idle | holding` which is also covered explicitly).
# Any non-error state may move to error.
_TO_ERROR_TRANSITIONS: frozenset[tuple[SlotState, SlotState]] = frozenset(
(s, SlotState.ERROR) for s in SlotState if s is not SlotState.ERROR
(s, SlotState.ERROR)
for s in (SlotState.INACTIVE, SlotState.PENDING_BUY, SlotState.HOLDING,
SlotState.PENDING_SELL)
)
# Operator manual resolve transitions out of error (REQ-004).
# Operator manual resolve out of error (REQ-004).
_FROM_ERROR_TRANSITIONS: frozenset[tuple[SlotState, SlotState]] = frozenset(
{
(SlotState.ERROR, SlotState.IDLE),
(SlotState.ERROR, SlotState.INACTIVE),
(SlotState.ERROR, SlotState.HOLDING),
}
)
# Canonical allowed transitions (inactive-based). Use `is_allowed_transition`
# which normalizes aliases before lookup.
ALLOWED_TRANSITIONS: frozenset[tuple[SlotState, SlotState]] = (
_BASE_TRANSITIONS | _TO_ERROR_TRANSITIONS | _FROM_ERROR_TRANSITIONS
)
def is_allowed_transition(from_state: SlotState, to_state: SlotState) -> bool:
"""Return True iff (from_state, to_state) is one of the 8 transition families."""
return (from_state, to_state) in ALLOWED_TRANSITIONS
"""Return True iff (from_state, to_state) — after normalizing idle/closed to
inactive — is an allowed transition family. `closed->idle` and any
inactive self-loop are rejected (dcy-020/REQ-057)."""
return (normalize_state(from_state), normalize_state(to_state)) in ALLOWED_TRANSITIONS
+1 -1
View File
@@ -140,7 +140,7 @@ class Daemon:
# Persistence + services
self.slot_repo = PostgreSQLSlotRepository(config.dsn)
self.intent_store = PostgreSQLIntentStore(config.dsn)
self.slot_service = SlotService(self.slot_repo)
self.slot_service = SlotService(self.slot_repo, instance_key=config.instance_key)
self.intent_service = IntentService(
self.slot_service, self.slot_repo, self.intent_store,
resolve_symbol=self._resolve_symbol,