feat(slot): BAT-029 M2(a)/M3 — holding 불일치 reconcile + slots 단일 뷰 (dcy-020/REQ-062·063)

- REQ-062 divergence: list_holding_slots(protocol+in_memory+PG) +
  reconcile_core_holdings(A=코어 holding/broker0→error, C=수량 불일치→warning,
  B=broker 보유/코어 없음→warning; 자동 청산 없음 issue #15). snapshot_scheduler
  자산 중심 모드에서 best-effort 호출, daemon slot_service 배선.
- REQ-063: slot_to_dict 에 universe_detached(retired_at) 추가 — slots 단일 뷰 tombstone 표시.
- 신규 테스트: test_holding_divergence(4).

M2(b) 청산 수량 브로커 정본(execution dispatch)은 라이브 집행 변경 → BAT-δ carry-over.

검증: 단위 393 passed / 36 skipped, PG-gated 18 passed, ruff clean. legacy 무파손.
REQ-061/062/063 Approved 유지(γ 경로 도입 검증; default 전환·M2(b) 는 BAT-δ).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-10 12:18:56 +09:00
co-authored by Claude Opus 4.8
parent b80407098e
commit 78a743a2ef
10 changed files with 215 additions and 10 deletions
@@ -154,6 +154,16 @@ class PostgreSQLSlotRepository:
row = cur.fetchone()
return int(row[0]) if row else 0
def list_holding_slots(self, instance_key: str) -> list[Slot]:
with self._psycopg.connect(self._dsn) as conn:
with conn.cursor() as cur:
cur.execute(
f"SELECT {_SLOT_COLUMNS} FROM daily_slot "
"WHERE instance_key = %s AND status = 'holding'",
(instance_key,),
)
return [self._row_to_slot(r) for r in cur.fetchall()]
def reconcile_universe(
self, instance_key: str, trading_date: date, universe_portfolio_ids: set[str],
*, allow_retire: bool = True,
+3
View File
@@ -319,6 +319,9 @@ def slot_to_dict(s) -> dict:
"sell_strategy_id": s.sell_strategy_id,
"portfolio_id": s.portfolio_id,
"forced_close_at": s.forced_close_at.isoformat() if s.forced_close_at else None,
# dcy-020 / REQ-063 (BAT-029): asset-centric single view — universe-detached
# (soft-retired/tombstone) marker so the operator sees retired assets.
"universe_detached": getattr(s, "retired_at", None) is not None,
}
+52
View File
@@ -12,10 +12,62 @@ import logging
from trex_core.application.broker_port import BrokerPort
from trex_core.application.portfolio import SnapshotStore
from trex_core.domain.slot.state import SlotState
_log = logging.getLogger(__name__)
def reconcile_core_holdings(*, slot_repo, slot_service, broker: BrokerPort,
instance_key: str) -> dict[str, str]:
"""dcy-020 / REQ-062 (BAT-029): surface core-slot holding ↔ broker divergence.
Broker balance is the reconcile ground truth. Decisions (no silent auto-fix,
no auto-liquidation — issue #15):
- A. core holding but broker flat (qty 0) -> slot to `error` + WARN (operator resolve)
- C. both hold but qty differs -> WARN (mirror is non-authoritative)
- B. broker holds, no core holding slot -> WARN (unmanaged position)
Returns {key: 'error'|'qty_warning'|'ok'|'unmanaged_warning'} for telemetry.
(Liquidation qty = broker authoritative in execution dispatch is BAT-δ.)"""
broker_qty: dict[str, int] = {
item.symbol: int(item.hldg_qty) for item in broker.get_balance()
}
decisions: dict[str, str] = {}
matched: set[str] = set()
for slot in slot_repo.list_holding_slots(instance_key):
sym = slot.symbol
matched.add(sym)
bq = broker_qty.get(sym, 0)
if bq == 0: # A — phantom holding
try:
slot_service.transit_slot(
slot.slot_id, SlotState.HOLDING, SlotState.ERROR,
reason="reconcile_mismatch:broker_flat", actor="reconcile",
)
decisions[str(slot.slot_id)] = "error"
_log.warning(
"core holding but broker flat: slot=%s symbol=%s -> error",
slot.slot_id, sym,
)
except Exception: # noqa: BLE001 - never let reconcile crash the loop
_log.exception("failed to error-quarantine slot %s", slot.slot_id)
elif slot.qty is not None and int(slot.qty) != bq: # C — qty mismatch
decisions[str(slot.slot_id)] = "qty_warning"
_log.warning(
"qty mismatch: slot=%s symbol=%s core=%s broker=%d (mirror non-authoritative)",
slot.slot_id, sym, slot.qty, bq,
)
else:
decisions[str(slot.slot_id)] = "ok"
for sym, bq in broker_qty.items(): # B — unmanaged broker position
if bq > 0 and sym not in matched:
decisions[f"broker:{sym}"] = "unmanaged_warning"
_log.warning(
"broker holds %s qty=%d with no core holding slot (unmanaged position)",
sym, bq,
)
return decisions
def reconcile_positions(*, store: SnapshotStore, broker: BrokerPort) -> dict[str, str]:
"""Run one reconciliation pass.
@@ -38,6 +38,7 @@ class SnapshotScheduler:
schedule_kst: time = time(hour=7, minute=30),
clock: Optional[Callable[[], datetime]] = None,
slot_repo=None,
slot_service=None,
instance_key: str = "default",
reconcile_enabled: bool = False,
trading_date_fn: Optional[Callable[[], object]] = None,
@@ -52,6 +53,7 @@ class SnapshotScheduler:
# 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._slot_service = slot_service
self._instance_key = instance_key
self._reconcile_enabled = reconcile_enabled
self._trading_date_fn = trading_date_fn
@@ -115,6 +117,15 @@ class SnapshotScheduler:
self._reconcile_slots(items)
except Exception: # noqa: BLE001
_log.exception("slot reconcile pass failed")
if self._slot_service is not None:
try:
from trex_core.application.reconciliation import reconcile_core_holdings
reconcile_core_holdings(
slot_repo=self._slot_repo, slot_service=self._slot_service,
broker=self._broker, instance_key=self._instance_key,
)
except Exception: # noqa: BLE001
_log.exception("core-holding divergence reconcile failed")
self._last_fired_date = self._clock()
return True
@@ -115,6 +115,12 @@ class InMemorySlotRepository:
if s.instance_key == instance_key and s.status in self._ACTIVE
)
def list_holding_slots(self, instance_key: str) -> list[Slot]:
return [
s for s in self._slots.values()
if s.instance_key == instance_key and s.status is SlotState.HOLDING
]
def reconcile_universe(
self, instance_key: str, trading_date: date, universe_portfolio_ids: set[str],
*, allow_retire: bool = True,
+5
View File
@@ -75,6 +75,11 @@ class SlotRepository(Protocol):
{holding, pending_buy, pending_sell} (dcy-020/REQ-059 M cap, D2)."""
...
def list_holding_slots(self, instance_key: str) -> list[Slot]:
"""Return holding slots for this instance (dcy-020/REQ-062 divergence
reconcile)."""
...
def reconcile_universe(
self, instance_key: str, trading_date: date, universe_portfolio_ids: set[str],
*, allow_retire: bool = True,
+3 -1
View File
@@ -176,8 +176,10 @@ class Daemon:
store=self.snapshot_store,
broker=self.broker,
schedule_kst=_parse_kst_time(config.snapshot_schedule.kst_time),
# dcy-020 / REQ-058 (BAT-028): asset-centric slot reconcile when M set.
# dcy-020 / REQ-058·062 (BAT-028/029): asset-centric slot reconcile +
# core-holding divergence reconcile when M set.
slot_repo=self.slot_repo,
slot_service=self.slot_service,
instance_key=config.instance_key,
reconcile_enabled=config.max_active_slots is not None,
trading_date_fn=(lambda: datetime.now(ZoneInfo(config.trading_timezone)).date()),