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:
@@ -4,8 +4,12 @@ A single background execution loop (invariant A single writer, invariant B
|
||||
single broker session) that, per tick:
|
||||
dispatch: claim pending slots with broker_order_id IS NULL (option A queue),
|
||||
submit the order, record broker_order_id (idempotency guard).
|
||||
dcy-020/REQ-062 (BAT-030): a SELL is dispatched with the broker
|
||||
balance quantity (hldg_qty) as the single source of truth — never
|
||||
the slot's mirror qty. Broker flat (qty 0) -> skip + WARN
|
||||
(divergence surfaces via reconcile, REQ-062 A).
|
||||
poll: observe fills on dispatched pending slots and transition the slot
|
||||
(pending_buy->holding / pending_sell->closed), or roll back on reject.
|
||||
(pending_buy->holding / pending_sell->inactive), or roll back on reject.
|
||||
On a successful fill, enqueue a LedgerWorkItem (slot transition is
|
||||
kept ON the critical path; the ledger write is eventually-consistent
|
||||
via a separate writer — REQ-019).
|
||||
@@ -47,6 +51,7 @@ class ExecutionResult:
|
||||
ledger_enqueued: int = 0 # REQ-019: ledger work items appended this tick
|
||||
ledger_skipped: int = 0 # REQ-018 AC-4: fills without portfolio_id
|
||||
stale_pending: int = 0 # dcy-013 / REQ-014 FR-3: pending orders over threshold
|
||||
sell_skipped_no_balance: int = 0 # dcy-020 / REQ-062: broker flat -> sell skipped
|
||||
|
||||
|
||||
class ExecutionService:
|
||||
@@ -58,12 +63,16 @@ class ExecutionService:
|
||||
ledger_outbox: Optional[LedgerOutbox] = None,
|
||||
event_emitter: Optional[SlotEventEmitter] = None,
|
||||
stale_pending_threshold_sec: Optional[int] = None,
|
||||
instance_key: str = "default",
|
||||
) -> None:
|
||||
self._svc = slot_service
|
||||
self._repo = repo
|
||||
self._broker = broker
|
||||
self._ledger_outbox = ledger_outbox
|
||||
self._event_emitter = event_emitter
|
||||
# dcy-020/REQ-056 (BAT-030): dispatch/poll are instance-scoped so two
|
||||
# daemons sharing a DB never touch each other's orders.
|
||||
self._instance_key = instance_key
|
||||
# dcy-013 / REQ-014 (issue #9): Alert-only pending-order stale watchdog.
|
||||
# <=0 or None disables it. When set, a dispatched-pending slot whose
|
||||
# last update is older than the threshold is surfaced (WARN + counter)
|
||||
@@ -93,12 +102,32 @@ class ExecutionService:
|
||||
|
||||
# ------------------------------------------------------------
|
||||
def _dispatch(self, r: ExecutionResult) -> None:
|
||||
for _ in range(_MAX_DISPATCH_PER_TICK):
|
||||
slot = self._repo.find_pending_for_dispatch()
|
||||
if slot is None:
|
||||
return
|
||||
sell_balance: Optional[dict[str, int]] = None # lazy, once per tick
|
||||
for slot in self._repo.list_undispatched_pending(
|
||||
self._instance_key, _MAX_DISPATCH_PER_TICK
|
||||
):
|
||||
side = "buy" if slot.status is SlotState.PENDING_BUY else "sell"
|
||||
qty = int(slot.qty or 0)
|
||||
if side == "sell":
|
||||
# dcy-020 / REQ-062 (BAT-030, D3): the sell quantity is the
|
||||
# BROKER balance (hldg_qty) — the slot's mirror qty is never
|
||||
# trusted. Broker flat -> skip dispatch + WARN; the divergence
|
||||
# surfaces via reconcile_core_holdings (REQ-062 A). No mirror
|
||||
# fallback by design.
|
||||
if sell_balance is None:
|
||||
sell_balance = {
|
||||
b.symbol: int(b.hldg_qty) for b in self._broker.get_balance()
|
||||
}
|
||||
qty = sell_balance.get(slot.symbol or "", 0)
|
||||
if qty <= 0:
|
||||
r.sell_skipped_no_balance += 1
|
||||
_log.warning(
|
||||
"sell dispatch skipped: slot=%s symbol=%s broker balance is 0 "
|
||||
"(divergence — no order submitted; operator/reconcile attention)",
|
||||
slot.slot_id, slot.symbol,
|
||||
)
|
||||
continue
|
||||
else:
|
||||
qty = int(slot.qty or 0)
|
||||
# dcy-012 / REQ-013: side-agnostic — use the slot's pending-order
|
||||
# limit_price only. A sell never reuses a buy limit (issue #10):
|
||||
# limit_price is cleared on entering HOLDING, so a market sell
|
||||
@@ -123,7 +152,7 @@ class ExecutionService:
|
||||
|
||||
def _poll(self, r: ExecutionResult) -> None:
|
||||
now = datetime.now(tz=timezone.utc)
|
||||
for slot in self._repo.list_dispatched_pending():
|
||||
for slot in self._repo.list_dispatched_pending(self._instance_key):
|
||||
side = "buy" if slot.status is SlotState.PENDING_BUY else "sell"
|
||||
fs = self._broker.poll_fill(slot.broker_order_id, side=side, symbol=slot.symbol or "")
|
||||
if fs.is_filled:
|
||||
@@ -153,9 +182,9 @@ class ExecutionService:
|
||||
avg_price=fs.avg_price, qty=float(fs.filled_qty) or slot.qty,
|
||||
)
|
||||
event_type = "slot_filled_buy"
|
||||
else: # PENDING_SELL
|
||||
else: # PENDING_SELL — asset slot returns to inactive (dcy-020/REQ-057)
|
||||
updated = self._svc.transit_slot(
|
||||
slot.slot_id, SlotState.PENDING_SELL, SlotState.CLOSED,
|
||||
slot.slot_id, SlotState.PENDING_SELL, SlotState.INACTIVE,
|
||||
reason="sell_filled", actor="execution_loop",
|
||||
)
|
||||
event_type = "slot_filled_sell"
|
||||
@@ -271,9 +300,9 @@ class ExecutionService:
|
||||
try:
|
||||
if slot.status is SlotState.PENDING_BUY:
|
||||
self._svc.transit_slot(
|
||||
slot.slot_id, SlotState.PENDING_BUY, SlotState.IDLE,
|
||||
slot.slot_id, SlotState.PENDING_BUY, SlotState.INACTIVE,
|
||||
reason=reason, actor="execution_loop",
|
||||
) # idle reset clears broker_order_id in the domain
|
||||
) # inactive reset clears broker_order_id in the domain
|
||||
else: # PENDING_SELL rejected -> back to holding, clear order for re-dispatch
|
||||
self._svc.transit_slot(
|
||||
slot.slot_id, SlotState.PENDING_SELL, SlotState.HOLDING,
|
||||
|
||||
Reference in New Issue
Block a user