feat(slot): BAT-030 — 자산 중심 cutover 완성 (dcy-020 BAT-δ, REQ-056·057·062·064·065)
M1 literal inactive 전면화: SlotState 5-state(idle/closed 별칭 제거), 마이그레이션 010(CHECK 교체+행 rewrite), ops_checks 를 transition_log 기반 재작성. M2 집행 매도 수량 브로커 정본(D3): dispatch 매도 qty=broker hldg_qty, 미러 fallback 없음, 브로커 0 → skip+WARN, 리스트 기반 dispatch(head-block 방지). M3 컬럼 drop + legacy pool 제거: 마이그레이션 011(trading_date·entry_count DROP), repo 계약 instance 스코프 개편(집행 큐 포함), preallocation 폐기(데몬 7스레드), admission 자산 중심 단일 경로(slot_id 정본), capacity 재정의(available=M−active), daily_symbol_entries 코드 경로 제거. M4 cutover 도구(D1·D4): trex-core-cutover(전체 rebuild, preflight/브로커 carry-over/ --allow-unmapped/--promote-unique/dry-run) + PG 리허설 테스트 8건. M5 baseline 마감: data-model/runtime-flows/project-structure/interface-contract 자산 중심 최종 갱신 + run-trex-core-daemon 스킬 정합. 검증: 단위 367 passed + ruff clean; PG-gated 29 passed(010/011 round-trip·드리프트 가드·cutover 리허설); RabbitMQ 21 passed; run-the-app e2e(test DB+실 MQ, M=1): reconcile 슬롯 생성→slot_id 매수→dedup→capacity_full→fill→already_active→ 매도→inactive(자산 바인딩 보존)→영구 슬롯 재활성 전 구간 green. 실 cutover 는 운영자 실행(REL 단계, D4). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -1,19 +1,24 @@
|
||||
"""Intent application service (REQ-007).
|
||||
"""Intent application service (REQ-007; dcy-020/REQ-059·061 asset-centric).
|
||||
|
||||
Turns a buy/sell intent submitted over HTTP into a single-writer slot
|
||||
Turns a buy/sell intent submitted over messaging into a single-writer slot
|
||||
transition, with intent_id idempotency backed by a durable intent_log.
|
||||
|
||||
Idempotency model (dcy-002 OQ-1): `intent_store.try_insert` is the dedup
|
||||
gate. On a duplicate intent_id it returns the prior decision without
|
||||
re-driving any transition (NFR-3). Slot transitions go exclusively through
|
||||
SlotService (advisory-lock serialized) so the single-writer invariant
|
||||
holds (NFR-2). Concurrency on the last idle slot is resolved by retrying
|
||||
on SlotStateMismatchError.
|
||||
holds (NFR-2).
|
||||
|
||||
dcy-020 (BAT-030): admission is asset-centric only — the legacy pool path
|
||||
(daily preallocation + idle∪closed candidate selection) was removed at the
|
||||
cutover. Buy is keyed by slot_id (REQ-061 canonical; portfolio_id is the
|
||||
legacy dual-accept mapping) and admits FCFS under the `max_active_slots` cap
|
||||
M when configured (no cap when unset).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, Optional
|
||||
from uuid import UUID
|
||||
@@ -26,7 +31,7 @@ from trex_core.domain.slot import (
|
||||
SlotStateMismatchError,
|
||||
)
|
||||
|
||||
_MAX_IDLE_RETRY = 8
|
||||
_MAX_ADMIT_RETRY = 8
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -45,15 +50,11 @@ class IntentDecision:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BuyIntent:
|
||||
# dcy-011 / REQ-007: portfolio_id (= asset_id) is the required canonical key.
|
||||
# symbol is no longer a client input — it is resolved server-side from the
|
||||
# universe (SnapshotStore) at admission. It remains here as the resolved
|
||||
# value carried onto the slot.
|
||||
# dcy-020 / REQ-061: slot_id is the canonical buy key (snapshot slots[]
|
||||
# round-trip); portfolio_id is accepted as a legacy dual-accept mapping.
|
||||
# symbol is not a client input — it is resolved server-side from the
|
||||
# universe at admission and carried onto the slot.
|
||||
intent_id: str
|
||||
trading_date: date
|
||||
# dcy-020 / REQ-061 (BAT-029): asset-centric contract key. slot_id is the
|
||||
# canonical buy key (snapshot slots[] round-trip); portfolio_id is retained
|
||||
# for the legacy pool path and as dual-accept in asset-centric mode.
|
||||
portfolio_id: Optional[str] = None
|
||||
slot_id: Optional[UUID] = None
|
||||
symbol: Optional[str] = None
|
||||
@@ -100,9 +101,8 @@ class IntentService:
|
||||
# callable(portfolio_id) -> Optional[str]. When set, admission resolves symbol
|
||||
# from the universe and rejects unknown_portfolio if absent.
|
||||
self._resolve_symbol = resolve_symbol
|
||||
# dcy-020 / REQ-059 (BAT-028): asset-centric mode gate. When max_active_slots
|
||||
# is set, buy admission activates the asset's permanent slot under an M cap
|
||||
# (FCFS, no eviction); otherwise the legacy pool path runs (unchanged).
|
||||
# dcy-020 / REQ-059·060: M cap. None = no capacity cap (the operator is
|
||||
# expected to set max_active_slots in the instance TOML — design §5).
|
||||
self._instance_key = instance_key
|
||||
self._max_active_slots = max_active_slots
|
||||
|
||||
@@ -116,14 +116,14 @@ class IntentService:
|
||||
|
||||
def submit_buy(self, intent: BuyIntent) -> IntentDecision:
|
||||
payload = {
|
||||
"trading_date": intent.trading_date.isoformat(),
|
||||
"slot_id": str(intent.slot_id) if intent.slot_id else None,
|
||||
"portfolio_id": intent.portfolio_id,
|
||||
"symbol": intent.symbol,
|
||||
"qty": intent.qty,
|
||||
"allocated_capital": intent.allocated_capital,
|
||||
"entry_price": intent.entry_price,
|
||||
"strategy_id": intent.strategy_id,
|
||||
"sell_strategy_id": intent.sell_strategy_id,
|
||||
"portfolio_id": intent.portfolio_id,
|
||||
}
|
||||
prior = self._dedup(intent.intent_id, "buy", payload)
|
||||
if prior is not None:
|
||||
@@ -163,68 +163,14 @@ class IntentService:
|
||||
return IntentDecision(intent_id, rec.status, rec.slot_id, rec.reason)
|
||||
|
||||
def _admit_buy(self, intent: BuyIntent) -> IntentDecision:
|
||||
# dcy-020 / REQ-061 (BAT-029): asset-centric mode keys buy by slot_id
|
||||
# (legacy portfolio_id dual-accept); the target slot + symbol are resolved
|
||||
# inside the asset-centric path.
|
||||
if self._max_active_slots is not None:
|
||||
return self._admit_buy_asset_centric(intent)
|
||||
# legacy pool path (dcy-011 / REQ-007): portfolio_id required; symbol is
|
||||
# resolved server-side from the universe.
|
||||
if not intent.portfolio_id:
|
||||
return IntentDecision(intent.intent_id, "rejected", None, "portfolio_id_required")
|
||||
symbol = intent.symbol
|
||||
if self._resolve_symbol is not None:
|
||||
symbol = self._resolve_symbol(intent.portfolio_id)
|
||||
if not symbol:
|
||||
return IntentDecision(intent.intent_id, "rejected", None, "unknown_portfolio")
|
||||
elif not symbol:
|
||||
# No resolver wired and no symbol carried — cannot determine the order target.
|
||||
return IntentDecision(intent.intent_id, "rejected", None, "unknown_portfolio")
|
||||
# Retry on the last-candidate race: another intent may claim the slot
|
||||
# between our find and transit (SlotStateMismatchError).
|
||||
# dcy-019 / REQ-007: admission candidate is idle ∪ closed (closed-slot
|
||||
# reallocation), ordered by entry_count asc → updated_at asc → slot_id.
|
||||
# The candidate may already be CLOSED, so the transit's from_state must
|
||||
# follow the slot's current status rather than a hardcoded IDLE.
|
||||
for _ in range(_MAX_IDLE_RETRY):
|
||||
slot = self._repo.find_allocatable_slot(intent.trading_date)
|
||||
if slot is None:
|
||||
return IntentDecision(intent.intent_id, "rejected", None, "no_idle_slot")
|
||||
try:
|
||||
updated = self._svc.transit_slot(
|
||||
slot.slot_id,
|
||||
slot.status,
|
||||
SlotState.PENDING_BUY,
|
||||
reason="buy_intent",
|
||||
actor="intent_api",
|
||||
symbol=symbol,
|
||||
qty=intent.qty,
|
||||
allocated_capital=intent.allocated_capital,
|
||||
# dcy-012 / REQ-007: buy entry price maps to the slot's
|
||||
# side-agnostic pending limit_price (cleared on fill→HOLDING).
|
||||
limit_price=intent.entry_price,
|
||||
strategy_id=intent.strategy_id,
|
||||
sell_strategy_id=intent.sell_strategy_id,
|
||||
portfolio_id=intent.portfolio_id,
|
||||
forced_close_at=intent.forced_close_at,
|
||||
stop_loss_price=intent.stop_loss_price,
|
||||
take_profit_price=intent.take_profit_price,
|
||||
extra={"intent_id": intent.intent_id, "symbol": symbol},
|
||||
)
|
||||
except SlotStateMismatchError:
|
||||
continue # slot was claimed concurrently; try another idle slot
|
||||
return IntentDecision(intent.intent_id, "admitted", updated.slot_id, None)
|
||||
return IntentDecision(intent.intent_id, "rejected", None, "idle_slot_contended")
|
||||
|
||||
# ------------------------------------------------------------
|
||||
def _admit_buy_asset_centric(self, intent: BuyIntent) -> IntentDecision:
|
||||
"""dcy-020 / REQ-059·REQ-061: activate the slot under the M cap.
|
||||
"""dcy-020 / REQ-059·REQ-061: activate the asset's permanent slot.
|
||||
|
||||
Contract key is slot_id (REQ-061); portfolio_id is accepted as a legacy
|
||||
dual-accept mapping. Symbol is resolved from the slot's portfolio_id.
|
||||
FCFS + no eviction: already-active -> already_active; at M -> capacity_full
|
||||
(existing holdings untouched, incl. over-cap). Single intent thread +
|
||||
instance-scoped advisory lock serialize admissions (dcy-020 OQ-1)."""
|
||||
FCFS + no eviction: already-active -> already_active; at M ->
|
||||
capacity_full (existing holdings untouched, incl. over-cap). Single
|
||||
intent thread + instance-scoped advisory lock serialize admissions
|
||||
(dcy-020 OQ-1)."""
|
||||
_ACTIVE = (SlotState.PENDING_BUY, SlotState.HOLDING, SlotState.PENDING_SELL)
|
||||
|
||||
def _resolve(sl):
|
||||
@@ -233,7 +179,7 @@ class IntentService:
|
||||
return self._resolve_symbol(pid)
|
||||
return intent.symbol or sl.symbol
|
||||
|
||||
for _ in range(_MAX_IDLE_RETRY):
|
||||
for _ in range(_MAX_ADMIT_RETRY):
|
||||
# resolve the target slot: slot_id (canonical) or portfolio_id (legacy)
|
||||
if intent.slot_id is not None:
|
||||
slot = self._repo.fetch_slot(intent.slot_id)
|
||||
@@ -250,7 +196,8 @@ class IntentService:
|
||||
symbol = _resolve(slot)
|
||||
if not symbol:
|
||||
return IntentDecision(intent.intent_id, "rejected", None, "unknown_portfolio")
|
||||
if self._repo.count_active(self._instance_key) >= self._max_active_slots:
|
||||
if (self._max_active_slots is not None
|
||||
and self._repo.count_active(self._instance_key) >= self._max_active_slots):
|
||||
return IntentDecision(intent.intent_id, "rejected", None, "capacity_full")
|
||||
try:
|
||||
updated = self._svc.transit_slot(
|
||||
@@ -262,6 +209,8 @@ class IntentService:
|
||||
symbol=symbol,
|
||||
qty=intent.qty,
|
||||
allocated_capital=intent.allocated_capital,
|
||||
# dcy-012 / REQ-007: buy entry price maps to the slot's
|
||||
# side-agnostic pending limit_price (cleared on fill→HOLDING).
|
||||
limit_price=intent.entry_price,
|
||||
strategy_id=intent.strategy_id,
|
||||
sell_strategy_id=intent.sell_strategy_id,
|
||||
|
||||
Reference in New Issue
Block a user