Deliver BAT-001: bootstrap trex-core + port slot pure domain
Implement REQ-001~004 (dcy-001): scaffold the trex-core package (pyproject, trex_core/, tests/), port the slot pure domain into trex_core.domain.slot with import rewrites, add the EXPECTED_SLOT_FIELDS contract guard (test_contract), and port the state/service unit tests. Verification: 56 passed, ruff clean, import sweep shows zero external deps, public __all__ exposes no infra symbols, contract negative case reproduced. Align project-structure/runtime-flows baselines to the real tree. Sync SDLC tracking: REQ-001~004 → Implemented, BAT-001 → release-candidate. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,250 @@
|
||||
"""Slot domain service — 4 main APIs (REQ-002).
|
||||
|
||||
- preallocate_daily_slots(trading_date, count)
|
||||
- transit_slot(slot_id, from_state, to_state, reason, actor, **fields)
|
||||
- get_today_entry_count(trading_date, symbol)
|
||||
- compute_slot_capacity(trading_date, total_slots)
|
||||
|
||||
All state-mutating APIs run inside repository.transactional_advisory_lock()
|
||||
to serialize Buy/Sell decision threads + operator CLI (REQ-002 AC-2).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Any, Optional
|
||||
from uuid import UUID
|
||||
|
||||
from trex_core.domain.slot.errors import (
|
||||
SlotNotFoundError,
|
||||
SlotStateMismatchError,
|
||||
SlotTransitionError,
|
||||
)
|
||||
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
|
||||
|
||||
|
||||
class SlotService:
|
||||
"""Slot lifecycle service. Race-free transitions via advisory lock + transaction."""
|
||||
|
||||
def __init__(self, repository: SlotRepository) -> None:
|
||||
self._repo = repository
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# preallocate_daily_slots
|
||||
# ------------------------------------------------------------
|
||||
def preallocate_daily_slots(self, trading_date: date, count: int) -> int:
|
||||
"""Insert `count` idle slots for trading_date if none exist.
|
||||
|
||||
Idempotent: second+ call on the same trading_date returns 0.
|
||||
Returns number of slots inserted.
|
||||
|
||||
REQ-002 AC-4, REQ-003 AC-5 (count must be > 0).
|
||||
"""
|
||||
if count <= 0:
|
||||
raise ValueError(f"slot count must be > 0, got {count}")
|
||||
with self._repo.transactional_advisory_lock(SLOT_ADVISORY_LOCK_ID):
|
||||
return self._repo.pre_allocate_slots(trading_date, count)
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# transit_slot
|
||||
# ------------------------------------------------------------
|
||||
def transit_slot(
|
||||
self,
|
||||
slot_id: UUID,
|
||||
from_state: SlotState,
|
||||
to_state: SlotState,
|
||||
reason: str,
|
||||
actor: str,
|
||||
*,
|
||||
symbol: Optional[str] = None,
|
||||
qty: Optional[float] = None,
|
||||
avg_price: Optional[float] = None,
|
||||
entry_price: Optional[float] = None,
|
||||
allocated_capital: Optional[float] = None,
|
||||
order_id: Optional[str] = None,
|
||||
strategy_id: Optional[str] = None,
|
||||
broker_order_id: Optional[str] = None,
|
||||
portfolio_id: Optional[str] = None,
|
||||
sell_strategy_id: Optional[str] = None,
|
||||
forced_close_at: Optional[datetime] = None,
|
||||
extra: Optional[dict[str, Any]] = None,
|
||||
) -> Slot:
|
||||
"""Transition slot from one state to another atomically.
|
||||
|
||||
Within a single advisory-locked transaction:
|
||||
1. fetch slot
|
||||
2. verify current state == from_state (race detection)
|
||||
3. verify (from_state, to_state) is in the allowed set
|
||||
4. update slot row (fields per to_state semantics)
|
||||
5. append transition_log row
|
||||
6. on closed->idle, increment daily_symbol_entries (REQ-002 AC-3)
|
||||
|
||||
External I/O (broker, kis-data-hub, portfolio-hub) MUST NOT be performed
|
||||
inside this function — caller does I/O outside the lock (REQ-002 AC-5).
|
||||
"""
|
||||
if not is_allowed_transition(from_state, to_state):
|
||||
raise SlotTransitionError(
|
||||
f"transition not allowed: {from_state.value} -> {to_state.value}"
|
||||
)
|
||||
|
||||
with self._repo.transactional_advisory_lock(SLOT_ADVISORY_LOCK_ID):
|
||||
slot = self._repo.fetch_slot(slot_id)
|
||||
if slot is None:
|
||||
raise SlotNotFoundError(f"slot not found: {slot_id}")
|
||||
|
||||
# Race detection — current state must match caller's from_state.
|
||||
if slot.status is not from_state:
|
||||
raise SlotStateMismatchError(
|
||||
f"slot {slot_id} current state {slot.status.value} "
|
||||
f"!= requested from_state {from_state.value}"
|
||||
)
|
||||
|
||||
updated = self._apply_transition_fields(
|
||||
slot,
|
||||
to_state,
|
||||
symbol=symbol,
|
||||
qty=qty,
|
||||
avg_price=avg_price,
|
||||
entry_price=entry_price,
|
||||
allocated_capital=allocated_capital,
|
||||
order_id=order_id,
|
||||
strategy_id=strategy_id,
|
||||
broker_order_id=broker_order_id,
|
||||
portfolio_id=portfolio_id,
|
||||
sell_strategy_id=sell_strategy_id,
|
||||
forced_close_at=forced_close_at,
|
||||
)
|
||||
self._repo.update_slot(updated)
|
||||
|
||||
# closed -> idle recovery: bump daily_symbol_entries atomically
|
||||
# (REQ-002 AC-3, REQ-001 split-by-purpose).
|
||||
if from_state is SlotState.CLOSED and to_state is SlotState.IDLE:
|
||||
# Use the symbol carried by the slot before reset.
|
||||
symbol_for_entry = slot.symbol
|
||||
if symbol_for_entry:
|
||||
self._repo.increment_symbol_entry(slot.trading_date, symbol_for_entry)
|
||||
|
||||
self._repo.append_transition_log(
|
||||
SlotTransitionRecord(
|
||||
slot_id=slot_id,
|
||||
from_state=from_state,
|
||||
to_state=to_state,
|
||||
ts=datetime.now(tz=timezone.utc),
|
||||
reason=reason,
|
||||
actor=actor,
|
||||
extra=extra or {},
|
||||
)
|
||||
)
|
||||
return updated
|
||||
|
||||
@staticmethod
|
||||
def _apply_transition_fields(
|
||||
slot: Slot,
|
||||
to_state: SlotState,
|
||||
*,
|
||||
symbol: Optional[str],
|
||||
qty: Optional[float],
|
||||
avg_price: Optional[float],
|
||||
entry_price: Optional[float],
|
||||
allocated_capital: Optional[float],
|
||||
order_id: Optional[str],
|
||||
strategy_id: Optional[str],
|
||||
broker_order_id: Optional[str] = None,
|
||||
portfolio_id: Optional[str] = None,
|
||||
sell_strategy_id: Optional[str] = None,
|
||||
forced_close_at: Optional[datetime] = None,
|
||||
) -> Slot:
|
||||
"""Compute the post-transition Slot row.
|
||||
|
||||
Special: closed -> idle resets occupancy fields (FR-2 #7).
|
||||
Special: pending_buy -> idle resets occupancy (REQ-011 AC-6 rollback).
|
||||
"""
|
||||
if to_state is SlotState.IDLE and slot.status in {
|
||||
SlotState.CLOSED,
|
||||
SlotState.PENDING_BUY,
|
||||
}:
|
||||
# Recovery / rollback: clear occupancy + broker handle.
|
||||
# transition_log retains audit trail.
|
||||
return replace(
|
||||
slot,
|
||||
status=SlotState.IDLE,
|
||||
symbol=None,
|
||||
qty=None,
|
||||
avg_price=None,
|
||||
entry_price=None,
|
||||
allocated_capital=None,
|
||||
order_id=None,
|
||||
strategy_id=None,
|
||||
broker_order_id=None,
|
||||
portfolio_id=None,
|
||||
sell_strategy_id=None,
|
||||
forced_close_at=None,
|
||||
updated_at=datetime.now(tz=timezone.utc),
|
||||
)
|
||||
|
||||
# Generic update: caller-supplied fields override; None means "keep".
|
||||
return replace(
|
||||
slot,
|
||||
status=to_state,
|
||||
symbol=symbol if symbol is not None else slot.symbol,
|
||||
qty=qty if qty is not None else slot.qty,
|
||||
avg_price=avg_price if avg_price is not None else slot.avg_price,
|
||||
entry_price=entry_price if entry_price is not None else slot.entry_price,
|
||||
allocated_capital=(
|
||||
allocated_capital if allocated_capital is not None else slot.allocated_capital
|
||||
),
|
||||
order_id=order_id if order_id is not None else slot.order_id,
|
||||
strategy_id=strategy_id if strategy_id is not None else slot.strategy_id,
|
||||
broker_order_id=(
|
||||
broker_order_id if broker_order_id is not None else slot.broker_order_id
|
||||
),
|
||||
portfolio_id=(
|
||||
portfolio_id if portfolio_id is not None else slot.portfolio_id
|
||||
),
|
||||
sell_strategy_id=(
|
||||
sell_strategy_id
|
||||
if sell_strategy_id is not None
|
||||
else slot.sell_strategy_id
|
||||
),
|
||||
forced_close_at=(
|
||||
forced_close_at if forced_close_at is not None else slot.forced_close_at
|
||||
),
|
||||
updated_at=datetime.now(tz=timezone.utc),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# get_today_entry_count
|
||||
# ------------------------------------------------------------
|
||||
def get_today_entry_count(self, trading_date: date, symbol: str) -> int:
|
||||
"""Return today's entry_count for a symbol (0 if no entries yet).
|
||||
|
||||
Used by buy decision state gate to enforce re-entry policy.
|
||||
Reads daily_symbol_entries (decision input), NEVER queries
|
||||
slot_transition_log (audit only). REQ-001, dcy-001 5.3.5.5.
|
||||
"""
|
||||
return self._repo.get_symbol_entry_count(trading_date, symbol)
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# compute_slot_capacity
|
||||
# ------------------------------------------------------------
|
||||
def compute_slot_capacity(self, trading_date: date, total_slots: int) -> SlotCapacity:
|
||||
"""Return idle/holding/pending counts + scarcity_ratio (REQ-002 AC-6).
|
||||
|
||||
scarcity_ratio = 1 - idle_count / total_slots, clamped to [0.0, 1.0].
|
||||
"""
|
||||
if total_slots <= 0:
|
||||
raise ValueError(f"total_slots must be > 0, got {total_slots}")
|
||||
counts = self._repo.count_slots_by_status(trading_date)
|
||||
idle = counts.get(SlotState.IDLE, 0)
|
||||
holding = counts.get(SlotState.HOLDING, 0)
|
||||
pending = counts.get(SlotState.PENDING_BUY, 0) + counts.get(SlotState.PENDING_SELL, 0)
|
||||
scarcity = max(0.0, min(1.0, 1.0 - (idle / total_slots)))
|
||||
return SlotCapacity(
|
||||
idle_count=idle,
|
||||
holding_count=holding,
|
||||
pending_count=pending,
|
||||
total_slots=total_slots,
|
||||
scarcity_ratio=scarcity,
|
||||
)
|
||||
Reference in New Issue
Block a user