feat(slot): BAT-028 M2/M3 — universe reconcile + 자산 중심 admission (dcy-020/REQ-058·059)
config 게이트 이중 경로(max_active_slots 설정 시 자산 중심, 미설정 시 legacy pool). 운영 데몬은 cutover(BAT-δ) 전까지 pool 무중단. - repository: find_slot_by_portfolio·count_active(holding+pending_buy+pending_sell)· reconcile_universe(생성 멱등/soft-retire/tombstone, allow_retire 가드) — protocol+in_memory+PG (PG: ON CONFLICT (instance_key, portfolio_id) WHERE portfolio_id IS NOT NULL) - snapshot_scheduler: run_once swap 직후 _reconcile_slots(빈 universe skip, ≥50%↓ retire 보류) - intents: _admit_buy 모드 분기 + _admit_buy_asset_centric(활성화/already_active/ capacity_full/unknown_portfolio/over-cap, 인스턴스 lock) - daemon: instance_key·max_active_slots·reconcile_enabled·trading_date_fn 배선 - 신규 테스트: test_universe_reconcile(6), test_asset_centric_admission(6), PG reconcile(1) 검증: 단위 387 passed / 35 skipped, PG-gated 17 passed, ruff clean. legacy 무파손. REQ-058/059/060 은 Approved 유지(자산 중심 경로 도입 검증; default 전환·cutover 는 BAT-δ). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -85,6 +85,9 @@ class IntentService:
|
||||
slot_repo: SlotRepository,
|
||||
intent_store: IntentStore,
|
||||
resolve_symbol=None,
|
||||
*,
|
||||
instance_key: str = "default",
|
||||
max_active_slots: Optional[int] = None,
|
||||
) -> None:
|
||||
self._svc = slot_service
|
||||
self._repo = slot_repo
|
||||
@@ -93,6 +96,11 @@ 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).
|
||||
self._instance_key = instance_key
|
||||
self._max_active_slots = max_active_slots
|
||||
|
||||
# ------------------------------------------------------------
|
||||
def lookup(self, intent_id: str) -> Optional[IntentDecision]:
|
||||
@@ -163,6 +171,9 @@ class IntentService:
|
||||
elif not symbol:
|
||||
# No resolver wired and no symbol carried — cannot determine the order target.
|
||||
return IntentDecision(intent.intent_id, "rejected", None, "unknown_portfolio")
|
||||
# dcy-020 / REQ-059 (BAT-028): asset-centric admission when M is configured.
|
||||
if self._max_active_slots is not None:
|
||||
return self._admit_buy_asset_centric(intent, symbol)
|
||||
# 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
|
||||
@@ -199,6 +210,48 @@ class IntentService:
|
||||
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, symbol: str) -> IntentDecision:
|
||||
"""dcy-020 / REQ-059: activate the asset's permanent slot under the M cap.
|
||||
|
||||
FCFS + no eviction: if the asset is already active -> already_active; if the
|
||||
instance is at M active slots -> capacity_full (existing holdings untouched,
|
||||
incl. over-cap when M is lowered). Single intent thread + instance-scoped
|
||||
advisory lock serialize admissions (REQ-002 NFR-1 / dcy-020 OQ-1)."""
|
||||
_ACTIVE = (SlotState.PENDING_BUY, SlotState.HOLDING, SlotState.PENDING_SELL)
|
||||
for _ in range(_MAX_IDLE_RETRY):
|
||||
slot = self._repo.find_slot_by_portfolio(self._instance_key, intent.portfolio_id)
|
||||
if slot is None:
|
||||
# no asset slot for this instance (not in reconciled universe)
|
||||
return IntentDecision(intent.intent_id, "rejected", None, "unknown_portfolio")
|
||||
if slot.status in _ACTIVE:
|
||||
return IntentDecision(intent.intent_id, "rejected", None, "already_active")
|
||||
if 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(
|
||||
slot.slot_id,
|
||||
slot.status,
|
||||
SlotState.PENDING_BUY,
|
||||
reason="buy_intent",
|
||||
actor="intent_api",
|
||||
symbol=symbol,
|
||||
qty=intent.qty,
|
||||
allocated_capital=intent.allocated_capital,
|
||||
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 changed under us; re-fetch and re-evaluate
|
||||
return IntentDecision(intent.intent_id, "admitted", updated.slot_id, None)
|
||||
return IntentDecision(intent.intent_id, "rejected", None, "already_active")
|
||||
|
||||
def _admit_sell(self, intent: SellIntent) -> IntentDecision:
|
||||
slot = self._repo.fetch_slot(intent.slot_id)
|
||||
if slot is None:
|
||||
|
||||
@@ -37,6 +37,10 @@ class SnapshotScheduler:
|
||||
broker: BrokerPort,
|
||||
schedule_kst: time = time(hour=7, minute=30),
|
||||
clock: Optional[Callable[[], datetime]] = None,
|
||||
slot_repo=None,
|
||||
instance_key: str = "default",
|
||||
reconcile_enabled: bool = False,
|
||||
trading_date_fn: Optional[Callable[[], object]] = None,
|
||||
) -> None:
|
||||
self._read = read_port
|
||||
self._store = store
|
||||
@@ -45,6 +49,13 @@ class SnapshotScheduler:
|
||||
self._clock = clock or (lambda: datetime.now(tz=timezone.utc))
|
||||
self._daemon_id: Optional[str] = None
|
||||
self._last_fired_date: Optional[datetime] = None
|
||||
# dcy-020 / REQ-058 (BAT-028): asset-centric slot reconcile after each
|
||||
# universe fetch (only when enabled = asset-centric mode).
|
||||
self._slot_repo = slot_repo
|
||||
self._instance_key = instance_key
|
||||
self._reconcile_enabled = reconcile_enabled
|
||||
self._trading_date_fn = trading_date_fn
|
||||
self._last_universe_size: Optional[int] = None
|
||||
|
||||
# ---- callable from a daemon thread loop --------------------------------
|
||||
def run_forever(self, stop: threading.Event, *, tick_sec: float = 60.0) -> None:
|
||||
@@ -99,5 +110,36 @@ class SnapshotScheduler:
|
||||
reconcile_positions(store=self._store, broker=self._broker)
|
||||
except Exception: # noqa: BLE001
|
||||
_log.exception("reconciliation pass failed")
|
||||
if self._reconcile_enabled and self._slot_repo is not None:
|
||||
try:
|
||||
self._reconcile_slots(items)
|
||||
except Exception: # noqa: BLE001
|
||||
_log.exception("slot reconcile pass failed")
|
||||
self._last_fired_date = self._clock()
|
||||
return True
|
||||
|
||||
# ---- asset-centric slot reconcile (dcy-020/REQ-058, BAT-028) ----------
|
||||
def _reconcile_slots(self, items: list) -> None:
|
||||
universe = {it.portfolio_id for it in items if getattr(it, "portfolio_id", None)}
|
||||
if not universe:
|
||||
_log.warning("slot reconcile skipped: empty universe (degrade guard)")
|
||||
return
|
||||
# mass-disappearance guard (D3): retire 보류 on N→0 (above) or >=50% shrink
|
||||
allow_retire = True
|
||||
prior = self._last_universe_size
|
||||
if prior is not None and len(universe) < 0.5 * prior:
|
||||
allow_retire = False
|
||||
_log.warning(
|
||||
"slot reconcile: universe shrank %d->%d (>=50%%) — retire held",
|
||||
prior, len(universe),
|
||||
)
|
||||
if self._trading_date_fn is not None:
|
||||
trading_date = self._trading_date_fn()
|
||||
else:
|
||||
trading_date = self._clock().date()
|
||||
result = self._slot_repo.reconcile_universe(
|
||||
self._instance_key, trading_date, universe, allow_retire=allow_retire,
|
||||
)
|
||||
self._last_universe_size = len(universe)
|
||||
if any(result.values()):
|
||||
_log.info("slot reconcile: %s (instance=%s)", result, self._instance_key)
|
||||
|
||||
Reference in New Issue
Block a user