Files
trex-core/trex_core/domain/slot/state.py
T
genichinandClaude Opus 4.8 017b8185e0 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>
2026-06-10 10:53:39 +09:00

100 lines
4.3 KiB
Python

"""Slot state machine (REQ-001, REQ-002; dcy-020/REQ-057 asset-centric redefinition).
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 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
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
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" # alias -> inactive (pool-model lineage; drop at BAT-δ)
ERROR = "error"
# 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.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
}
)
# Any non-error state may move to error.
_TO_ERROR_TRANSITIONS: frozenset[tuple[SlotState, SlotState]] = frozenset(
(s, SlotState.ERROR)
for s in (SlotState.INACTIVE, SlotState.PENDING_BUY, SlotState.HOLDING,
SlotState.PENDING_SELL)
)
# Operator manual resolve out of error (REQ-004).
_FROM_ERROR_TRANSITIONS: frozenset[tuple[SlotState, SlotState]] = frozenset(
{
(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) — 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