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:
@@ -1,10 +1,10 @@
|
||||
# BAT-027 Implementation
|
||||
|
||||
- Status: in-progress (M1 완료, M2/M3 대기)
|
||||
- Status: completed (M1·M2·M3 완료)
|
||||
- Batch: BAT-027
|
||||
|
||||
## 구현 요약
|
||||
- 안 B(점진/additive-first). M1(REQ-056 additive 모델+마이그레이션+persistence) 완료. M2/M3(상태머신 inactive 별칭 + 인스턴스 스코프 lock + 소비처 cascade)는 다음 단계.
|
||||
- 안 B(점진/additive-first). M1(additive 모델+마이그레이션+persistence)·M2(상태머신 inactive 별칭+인스턴스 스코프 lock)·M3(소비처 cascade — runtime 무변경, idle/closed 별칭으로 흡수) 완료. 전체 375 passed + PG-gated 8 passed, ruff clean.
|
||||
|
||||
## 변경 내역
|
||||
|
||||
@@ -13,14 +13,21 @@
|
||||
- `trex_core/adapters/persistence/sql/009_add_slot_instance_key_and_retired_at.sql`(신규): instance_key NOT NULL DEFAULT 'default', retired_at, 부분 UNIQUE(instance_key, portfolio_id) WHERE portfolio_id IS NOT NULL. additive·멱등.
|
||||
- `trex_core/adapters/persistence/postgresql.py`: `_SLOT_COLUMNS` +instance_key/retired_at(row[19]/[20]), `_row_to_slot` 매핑, `update_slot` SET. pre_allocate INSERT 는 DEFAULT 의존(변경 없음).
|
||||
|
||||
### M2 — REQ-057 상태머신+인스턴스 lock (대기)
|
||||
- state.py inactive 표준 + idle/closed 별칭(closed→idle 제거), advisory lock 인스턴스 스코프(2-int).
|
||||
### M2 — REQ-057 상태머신 + 인스턴스 lock (완료)
|
||||
- `trex_core/domain/slot/state.py`: `SlotState.INACTIVE` 추가 + `idle`/`closed` 를 별칭으로 `normalize_state()` 매핑. `_BASE_TRANSITIONS` 를 inactive 기준으로 재정의(`inactive↔pending_buy↔holding↔pending_sell`), **`closed→idle` 복구 제거**(inactive self-loop). `is_allowed_transition` 가 양쪽 정규화. `slot_advisory_lock_id(instance_key)` 헬퍼(전역 base ⊕ crc32(instance_key)).
|
||||
- `trex_core/domain/slot/service.py`: `SlotService(repository, instance_key="default")` + advisory lock 을 `self._lock_id`(인스턴스 스코프)로 3개소 치환. holding 은 status 로컬 정본(불변).
|
||||
- `trex_core/domain/slot/__init__.py`: `normalize_state`/`slot_advisory_lock_id` export. `trex_core/runtime/daemon.py`: `SlotService(..., instance_key=config.instance_key)`.
|
||||
|
||||
### M3 — 소비처 cascade 정합 (대기)
|
||||
- execution/intents/cli/ops_checks/service 등 idle·closed·전역 lock 참조 정합.
|
||||
### M3 — 소비처 cascade (완료, runtime 무변경)
|
||||
- idle/closed 가 inactive 별칭으로 흡수되어 **execution/cli/ops_checks/postgresql 의 idle·closed 사용은 그대로 유효**(별칭 정규화). closed→idle 은 runtime 미사용이라 무파손. → 별도 소비처 코드 변경 없음. (실제 inactive 전면 전환·컬럼 drop 은 BAT-δ.)
|
||||
- 테스트 갱신: test_state(새 전이/멤버/락), test_service(closed→idle 제거→reallocation), test_slot_entry_count, test_postgresql_repository(PG).
|
||||
|
||||
## 테스트
|
||||
- M1: 도메인 슬롯 단위 79 + 전체 375 passed / 35 skipped, ruff clean(additive 무파손). PG 마이그레이션 009 round-trip 은 verification 단계에서 test DSN 검증.
|
||||
- 단위 전체: 375 passed / 35 skipped / 1 deselected.
|
||||
- PG-gated(실 trex_core_test): `test_migration_and_drift`(마이그레이션 009 + `EXPECTED_SLOT_FIELDS`↔컬럼 드리프트, instance_key/retired_at 포함) + `test_postgresql_repository`(lifecycle + closed→idle 거부 + closed→pending_buy reallocation) → **8 passed**.
|
||||
- `ruff check trex_core tests` All passed.
|
||||
|
||||
## 검증 실행
|
||||
- M1: `TREX_BROKER=paper pytest -q` → 375 passed / 35 skipped / 1 deselected. `ruff check trex_core` All passed.
|
||||
- `TREX_BROKER=paper pytest -q --deselect …test_sandbox…` → 375 passed / 35 skipped / 1 deselected.
|
||||
- `TREX_POSTGRESQL_TEST_DSN=…(trex_core_test) pytest tests/adapters/persistence/test_migration_and_drift.py test_postgresql_repository.py` → 8 passed.
|
||||
- `ruff check trex_core tests` → All checks passed.
|
||||
|
||||
@@ -1,13 +1,38 @@
|
||||
# BAT-027 Verification
|
||||
|
||||
- Status: not-started
|
||||
- Status: verified (배치 범위 — 안 B 토대)
|
||||
- Batch: BAT-027
|
||||
|
||||
## Acceptance Mapping
|
||||
- (draft-batch-verification / confirm-batch-verification 단계에서 작성)
|
||||
|
||||
### REQ-056 (영구 슬롯 스키마, 안 B 부분)
|
||||
| AC | 상태 | Evidence |
|
||||
|----|------|----------|
|
||||
| instance_key·retired_at·`UNIQUE(instance_key, portfolio_id)` 존재 | ✅ | 마이그레이션 009 + test_migration_and_drift(PG) green |
|
||||
| `EXPECTED_SLOT_FIELDS` ↔ daily_slot 컬럼 일치(+instance_key/retired_at) | ✅ | test_contract + test_migration_and_drift(PG) |
|
||||
| 중복 (instance_key, portfolio_id) 거부 | ✅ | 부분 UNIQUE 인덱스(WHERE portfolio_id NOT NULL) |
|
||||
| `entry_count`/슬롯 `trading_date` 컬럼 **부재** | ⏳ 이월(BAT-δ) | 안 B로 유지 — cutover(REQ-064)에서 drop |
|
||||
|
||||
### REQ-057 (상태머신 재정의 + 인스턴스 lock)
|
||||
| AC | 상태 | Evidence |
|
||||
|----|------|----------|
|
||||
| 전이 집합 inactive 기준(closed→idle 제거) | ✅ | test_state(allowed/disallowed/size 12) |
|
||||
| 종료 시 inactive 복귀(idle/closed 별칭) | ✅(별칭) | test_state·test_service. 엄밀 literal `inactive` 산출 전면 전환은 BAT-δ |
|
||||
| 인스턴스별 락 비교차 | ✅ | test_state::test_slot_advisory_lock_id_is_instance_scoped |
|
||||
| 동일 슬롯 직렬화(단일 writer) | ✅ | test_service Advisory lock 직렬화 |
|
||||
| holding 로컬 정본 | ✅ | status 로컬(hub 미의존) — 수량 정본 분리는 REQ-062/BAT-γ |
|
||||
|
||||
## Evidence
|
||||
- (대기)
|
||||
- 단위 전체: `375 passed / 35 skipped / 1 deselected`(KIS sandbox live-env 1건 deselect).
|
||||
- PG-gated(실 trex_core_test): `8 passed` — 마이그레이션 009 적용 + 드리프트 가드(instance_key/retired_at 포함) + lifecycle/closed→idle 거부/closed→pending_buy reallocation.
|
||||
- `ruff check trex_core tests` All passed.
|
||||
|
||||
## Carried-Over (REQ 완전 충족은 후속 배치)
|
||||
- REQ-056 `entry_count`/`trading_date` 컬럼 drop → **BAT-δ(cutover, REQ-064)**.
|
||||
- REQ-057 literal `inactive` 전면 산출(별칭 제거) → BAT-δ.
|
||||
- admission/capacity(REQ-059)·reconcile(REQ-058)·intent 자산 키(REQ-061)·수량/불일치(REQ-062)·운영자 뷰(REQ-063) → BAT-β/γ.
|
||||
- 따라서 **REQ-056/057 은 본 배치에서 Implemented 로 확정하지 않고 Approved 유지**(토대만 충족; 전체 AC 는 dcy-020 후속 배치 완료 시 confirm-req-implemented).
|
||||
|
||||
## Result
|
||||
- Ready for Release: false (구현 전)
|
||||
- Ready for Release: false (dcy-020 전체 delivery 미완 — 토대 배치)
|
||||
- Blocking Issues: 없음(배치 범위 단위/PG green). 단, dcy-020 REQ 완전 충족은 BAT-β/γ/δ 필요.
|
||||
|
||||
@@ -3,6 +3,8 @@ from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from trex_core.adapters.persistence.in_memory_intent_store import InMemoryIntentStore # noqa: F401
|
||||
from trex_core.adapters.persistence.postgresql import (
|
||||
PostgreSQLIntentStore,
|
||||
@@ -10,6 +12,7 @@ from trex_core.adapters.persistence.postgresql import (
|
||||
)
|
||||
from trex_core.application.intents import BuyIntent, IntentService, SellIntent
|
||||
from trex_core.domain.slot import SlotService, SlotState
|
||||
from trex_core.domain.slot.errors import SlotTransitionError
|
||||
|
||||
DAY = date(2026, 6, 3)
|
||||
|
||||
@@ -48,7 +51,9 @@ def test_buy_intent_idempotent_on_pg(pg_clean):
|
||||
assert len(pending) == 1 # no double transition
|
||||
|
||||
|
||||
def test_full_lifecycle_recovery_bumps_entry_count(pg_clean):
|
||||
def test_full_lifecycle_then_closed_reallocation_bumps_entry_count(pg_clean):
|
||||
# dcy-020: closed→idle recovery removed. Reuse a closed slot via
|
||||
# closed→pending_buy reallocation (dcy-019); entry_count is cumulative.
|
||||
repo, svc, intents = _wire(pg_clean)
|
||||
svc.preallocate_daily_slots(DAY, 1)
|
||||
d = intents.submit_buy(BuyIntent(intent_id="pg-life", trading_date=DAY, symbol="005930", portfolio_id="PF-1"))
|
||||
@@ -56,6 +61,11 @@ def test_full_lifecycle_recovery_bumps_entry_count(pg_clean):
|
||||
svc.transit_slot(sid, SlotState.PENDING_BUY, SlotState.HOLDING, reason="filled", actor="t")
|
||||
intents.submit_sell(SellIntent(intent_id="pg-sell", slot_id=sid))
|
||||
svc.transit_slot(sid, SlotState.PENDING_SELL, SlotState.CLOSED, reason="filled", actor="t")
|
||||
assert repo.get_symbol_entry_count(DAY, "005930") == 0
|
||||
assert repo.fetch_slot(sid).entry_count == 1
|
||||
# closed→idle is now rejected
|
||||
with pytest.raises(SlotTransitionError):
|
||||
svc.transit_slot(sid, SlotState.CLOSED, SlotState.IDLE, reason="recovery", actor="t")
|
||||
assert repo.get_symbol_entry_count(DAY, "005930") == 1
|
||||
# reuse via reallocation
|
||||
realloc = svc.transit_slot(sid, SlotState.CLOSED, SlotState.PENDING_BUY,
|
||||
reason="reallocate", actor="t", symbol="000660")
|
||||
assert realloc.entry_count == 2 and realloc.symbol == "000660"
|
||||
|
||||
@@ -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):
|
||||
"""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.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",
|
||||
)
|
||||
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
|
||||
assert realloc.status is SlotState.PENDING_BUY
|
||||
assert realloc.symbol == "000660" # clean-slate
|
||||
assert realloc.entry_count == 2 # cumulative
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
@@ -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}")
|
||||
|
||||
@@ -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.INACTIVE, SlotState.PENDING_BUY), # 1. buy decision (activate)
|
||||
(SlotState.PENDING_BUY, SlotState.HOLDING), # 2. buy filled
|
||||
(SlotState.PENDING_BUY, SlotState.IDLE), # 3. buy rejected/rollback
|
||||
(SlotState.PENDING_BUY, SlotState.INACTIVE), # 3. buy rejected/rollback
|
||||
(SlotState.HOLDING, SlotState.PENDING_SELL), # 4. sell decision
|
||||
(SlotState.PENDING_SELL, SlotState.CLOSED), # 5. sell filled
|
||||
(SlotState.PENDING_SELL, SlotState.INACTIVE), # 5. sell filled (deactivate)
|
||||
(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)
|
||||
}
|
||||
)
|
||||
|
||||
# 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
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user