feat(core-A): reconcile-warning durable store + blocking gate (BAT-050, REQ-102/103/104/107/108)

B/C 불일치 시 슬롯을 durable 차단(ReconcileWarningStore)하고 전략 intent 경로에
pause∨reconcile_warned 게이트를 추가한다. 안전망(safety-sell/kill-switch/watchdog)
경로는 SlotService 직접 호출로 게이트를 구조적으로 우회(OQ-B 확정).
SlotState enum/전이표/wire 계약 필드는 불변, reconcile_warned 필드만 additive 추가.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
This commit is contained in:
2026-06-26 00:43:04 +09:00
co-authored by Claude Sonnet 4.6
parent 35f3147250
commit c193388198
17 changed files with 1410 additions and 27 deletions
+81 -13
View File
@@ -1,10 +1,15 @@
"""Position reconciliation between portfolio-hub and broker (REQ-031).
"""Position reconciliation between portfolio-hub and broker (REQ-031, REQ-103).
The broker account is single (invariant B) so portfolio-hub quantities are
aggregated to `symbol` before being compared with `BrokerPort.get_balance()`.
Mismatches flip the asset's `warning` overlay; a subsequent successful match
clears it automatically (in-memory only — pause is the durable channel for
manual holds).
BAT-050 / REQ-103: B-case (slot qty mismatch) and C-case (ledger mismatch)
now also set a durable reconcile-warning via ReconcileWarningStore (slot_id
keyed). The in-memory warning overlay is kept for backward compat; the durable
store is additive and Optional (None => warn-log-only, backward compat).
"""
from __future__ import annotations
@@ -13,7 +18,7 @@ from typing import Optional
from trex_core.application.alarm_emitter import AlarmEmitter
from trex_core.application.broker_port import BrokerPort
from trex_core.application.portfolio import SnapshotStore
from trex_core.application.portfolio import ReconcileWarningStore, SnapshotStore
from trex_core.domain.slot.state import SlotState
_log = logging.getLogger(__name__)
@@ -26,16 +31,24 @@ def reconcile_core_holdings(
broker: BrokerPort,
instance_key: str,
alarm_emitter: Optional[AlarmEmitter] = None,
warn_store: Optional[ReconcileWarningStore] = None,
) -> dict[str, str]:
"""dcy-020 / REQ-062 (BAT-029): surface core-slot holding ↔ broker divergence.
"""dcy-020 / REQ-062 (BAT-029) + REQ-103 (BAT-050): surface core-slot holding
vs broker divergence and set durable reconcile-warning for B case.
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)
- A. core holding but broker flat (qty 0) -> slot to `error` + WARN + CRITICAL alarm
- C. both hold but qty differs (B in REQ-103 naming) -> WARN + durable reconcile-warning
- B. broker holds, no core holding slot -> WARN (unmanaged position)
REQ-103 case codes:
- case_code='B': slot has holding but qty differs from broker (reconcile_core_holdings)
- case_code='C': ledger/hub qty differs from broker (reconcile_positions)
warn_store: Optional — when None, WARN-log-only (backward compat, REQ-103 AC-5).
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()
}
@@ -65,15 +78,32 @@ def reconcile_core_holdings(
)
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"
elif slot.qty is not None and int(slot.qty) != bq: # B case (REQ-103) — qty mismatch
slot_id_str = str(slot.slot_id)
decisions[slot_id_str] = "qty_warning"
# REQ-107: structured WARNING log for B case.
_log.warning(
"qty mismatch: slot=%s symbol=%s core=%s broker=%d (mirror non-authoritative)",
slot.slot_id, sym, slot.qty, bq,
"reconcile_warning set: slot_id=%s portfolio_id=%s symbol=%s "
"case_code=B broker_qty=%d slot_qty=%s actor=reconcile",
slot_id_str, slot.portfolio_id, sym, bq, slot.qty,
)
# REQ-103 / BAT-050: durable reconcile-warning (case_code='B').
if warn_store is not None:
try:
warn_store.set_warned(
slot_id_str,
portfolio_id=slot.portfolio_id or "",
case_code="B",
actor="reconcile",
reason=f"slot_qty={slot.qty} broker_qty={bq} symbol={sym}",
)
except Exception: # noqa: BLE001 - never let reconcile crash the loop
_log.exception(
"failed to set reconcile_warning for slot %s", slot.slot_id
)
else:
decisions[str(slot.slot_id)] = "ok"
for sym, bq in broker_qty.items(): # B — unmanaged broker position
for sym, bq in broker_qty.items(): # unmanaged broker position
if bq > 0 and sym not in matched:
decisions[f"broker:{sym}"] = "unmanaged_warning"
_log.warning(
@@ -83,11 +113,23 @@ def reconcile_core_holdings(
return decisions
def reconcile_positions(*, store: SnapshotStore, broker: BrokerPort) -> dict[str, str]:
"""Run one reconciliation pass.
def reconcile_positions(
*,
store: SnapshotStore,
broker: BrokerPort,
slot_repo=None,
instance_key: str = "default",
warn_store: Optional[ReconcileWarningStore] = None,
) -> dict[str, str]:
"""Run one reconciliation pass (REQ-031 + REQ-103 BAT-050).
Returns a `{portfolio_id: 'warning' | 'cleared' | 'ok'}` map for telemetry.
The map is also reflected onto `store` via `set_warning(...)`.
BAT-050 / REQ-103: when warn_store and slot_repo are provided, C-case mismatches
(ledger/hub qty vs broker) also set durable reconcile-warning on the corresponding
slot (portfolio_id -> slot lookup via slot_repo). When either is None, falls back
to in-memory warning only (backward compat, REQ-103 AC-5).
"""
broker_qty: dict[str, int] = {
item.symbol: int(item.hldg_qty) for item in broker.get_balance()
@@ -117,6 +159,32 @@ def reconcile_positions(*, store: SnapshotStore, broker: BrokerPort) -> dict[str
)
store.set_warning(pid, True)
decisions[pid] = "warning"
# REQ-103 / BAT-050: durable reconcile-warning for C case (case_code='C').
if warn_store is not None and slot_repo is not None:
try:
slot = slot_repo.find_slot_by_portfolio(instance_key, pid)
if slot is not None:
slot_id_str = str(slot.slot_id)
# REQ-107: structured WARNING log for C case.
_log.warning(
"reconcile_warning set: slot_id=%s portfolio_id=%s "
"symbol=%s case_code=C hub_qty=%d broker_qty=%d actor=reconcile",
slot_id_str, pid, symbol, hub_total, broker_total,
)
warn_store.set_warned(
slot_id_str,
portfolio_id=pid,
case_code="C",
actor="reconcile",
reason=(
f"hub_qty={hub_total} broker_qty={broker_total} "
f"symbol={symbol}"
),
)
except Exception: # noqa: BLE001
_log.exception(
"failed to set reconcile_warning for portfolio_id=%s", pid
)
else:
if was_warned:
store.set_warning(pid, False)