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:
2026-06-10 15:16:15 +09:00
co-authored by Claude Opus 4.8
parent cec34be5f4
commit 7d727824dc
67 changed files with 1584 additions and 1862 deletions
+29 -25
View File
@@ -4,14 +4,14 @@
- Baseline Seed: .stage-pilot/bootstrap/baseline.yaml
- Status: draft
- Owner: project maintainers
- Last Updated (KST): 2026-06-08 (BAT-019)
- Last Updated (KST): 2026-06-10 (BAT-030 — dcy-020 자산 중심 모델 마감)
- Source Discovery / Batch: bootstrap-baseline (pre-Discovery)
## Project Summary
- trex 제품군의 공용 베이스로, 첫 도메인으로 trex-orbit 의 일일 거래 슬롯 생명주기(slot) 순수 도메인을 storage-agnostic 하게 이식한 코어다.
## Primary Domain
- 자동매매 일일 거래 슬롯 생명주기 도메인 (equity trading slot lifecycle)
- 자동매매 **자산 중심 영구 슬롯** 생명주기 도메인 (dcy-020 — portfolio-hub universe 자산 1:1 영구 슬롯; 일일 풀 모델은 BAT-030 cutover 로 폐기)
## Primary Persistence Backend
- PostgreSQL (BAT-002, REQ-006; BAT-006 확장) — 코어 데몬의 durable 단일 writer. 도메인은 여전히 storage-agnostic(SlotRepository Protocol); in-memory 어댑터는 테스트용으로 잔존. 슬라이스 1 테이블: daily_slot / daily_symbol_entries / slot_transition_log / intent_log / ledger_outbox (daily_slot_archive·prune 은 범위 밖).
@@ -27,22 +27,23 @@
## Model Summary
- Slot :: 하나의 일일 거래 슬롯의 현재 생명주기 상태/점유 정보(source of truth)
- SlotTransitionRecord :: 슬롯 상태 전이의 append-only 감사 기록
- daily_symbol_entries (카운터) :: (trading_date, symbol) 별 재진입 횟수(결정 입력)
- SlotCapacity (계산 스냅샷) :: idle/holding/pending + scarcity_ratio (영속 엔티티 아님)
- Slot :: universe 자산 1:1 **영구 슬롯**의 현재 생명주기 상태/점유 정보(source of truth). 키 = (instance_key, portfolio_id) UNIQUE.
- SlotTransitionRecord :: 슬롯 상태 전이의 append-only 감사 기록 (시간 속성의 정본 — 슬롯 행에는 거래일 없음)
- SlotCapacity (계산 스냅샷) :: inactive/holding/pending/active + available(= max(0, M − active)) + scarcity_ratio (영속 엔티티 아님; dcy-020/REQ-059)
- ~~daily_symbol_entries~~ :: **폐기(dcy-020/BAT-030)** — closed→idle 복구 제거로 writer 소멸. 테이블은 잔존하나 코드 경로 없음.
## Entity: `Slot`
- Purpose: 하나의 일일 거래 슬롯의 현재 생명주기 상태와 점유 정보를 담는 source of truth.
- Source of Truth: daily_slot (향후 테이블) / 현재는 in-memory dict
- Lifecycle: idle -> pending_buy -> holding -> pending_sell -> closed -> (recovery) idle ; closed -> pending_buy (직접 재할당, dcy-019) ; 모든 비-error 상태 -> error ; error -> {idle, holding}
- Purpose: portfolio-hub universe 자산 1:1 **영구 슬롯**의 현재 생명주기 상태와 점유 정보를 담는 source of truth (dcy-020/REQ-056). 거래일을 넘어 존속하며, universe reconcile(REQ-058)이 생성/소프트 폐기한다.
- Source of Truth: daily_slot (PostgreSQL; 이름은 역사적 잔존 — 행은 영구)
- Lifecycle (5-state, REQ-057): inactive -> pending_buy -> holding -> pending_sell -> inactive ; pending_buy -> inactive (롤백) ; pending_sell -> holding (롤백) ; 모든 비-error -> error ; error -> {inactive, holding}. `idle`/`closed` 는 BAT-030(마이그레이션 010)에서 `inactive` 로 폐합.
### Key Fields
- slot_id :: UUID :: 슬롯 식별자(PK)
- trading_date :: date :: 거래일 — 설정 타임존(`trading_timezone`, 기본 `Asia/Seoul`) 기준 날짜로 계산(dcy-014/REQ-005). 시스템 UTC 날짜가 아니라 거래 캘린더 일자와 일치. 일일 preallocation 이 TZ 일자 경계마다 멱등 생성.
- status :: SlotState :: 6 상태(idle/pending_buy/holding/pending_sell/closed/error) 중 현재 상태
- slot_id :: UUID :: 슬롯 식별자(PK) — 외부 intent 계약의 정본 키(REQ-061)
- instance_key :: TEXT NOT NULL DEFAULT 'default' :: 공유 DB 에서 데몬 인스턴스 스코프(REQ-056). UNIQUE(instance_key, portfolio_id) (partial — portfolio_id NOT NULL; cutover `--promote-unique` 후 NOT NULL 승격)
- retired_at :: TIMESTAMPTZ? :: universe 이탈 자산의 soft-retire 마커(REQ-058; 운영 뷰 `universe_detached`)
- status :: SlotState :: 5 상태(inactive/pending_buy/holding/pending_sell/error) 중 현재 상태 — CHECK 제약(마이그레이션 010)
- symbol :: str? :: 점유 종목
- qty / avg_price :: numeric? :: 수량 / 평단
- limit_price :: numeric? :: 현재 pending 주문 지정가(side 무관, dcy-012/REQ-002 — 과거 `entry_price`에서 rename). pending 진입(매수/매도 지정가) 시 set, pending 이탈(→holding/→closed) 시 None 으로 clear → 매수 지정가가 매도로 누수되지 않음(issue #10). None 이면 dispatch 시 시장가.
@@ -51,20 +52,21 @@
- strategy_id / sell_strategy_id :: str? :: 진입/청산 전략 식별
- portfolio_id :: str? :: 포트폴리오 식별
- forced_close_at :: datetime? :: 강제 청산 마감선
- entry_count :: int :: 슬롯 단위 누적 진입 횟수(dcy-019/REQ-002). 매 `→pending_buy`(idle→ / closed→ 모두) 시 +1, 그 외 전이·closed→idle 복구는 보존. buy admission selector 의 공정 정렬 키(최저 진입 우선). 종목 단위 `daily_symbol_entries.entry_count`(재진입 캡)와 별개.
- created_at / updated_at :: datetime? :: 생성/갱신 시각 — **UTC 저장 유지**(dcy-014/REQ-005 NFR-1: `trading_date` 만 TZ 기준, timestamp 는 UTC)
- created_at / updated_at :: datetime? :: 생성/갱신 시각 — UTC 저장
- (DROP, BAT-030/마이그레이션 011) ~~trading_date~~ — 영구 슬롯에 거래일 정체성 없음(시간 속성은 transition_log/원장). ~~entry_count~~ — 풀 공정 정렬 키 폐기.
### Relationships
- daily_symbol_entries :: closed->idle 복구 시 (trading_date, symbol) 카운트 +1
- slot_transition_log :: 매 전이마다 append-only 기록 1행
- portfolio-hub universe :: portfolio_id 1:1 — universe reconcile(REQ-058)이 신규 자산 슬롯 생성(inactive)·이탈 자산 soft-retire(retired_at)·보유 중 이탈은 tombstone(유지).
- slot_transition_log :: 매 전이마다 append-only 기록 1행 (매도 체결 검출·ledger-gap 검출의 정본)
### State Rules
- 전이 패밀리(8 base[dcy-019 closed→pending_buy 포함] + *→error + error→{idle,holding})에 없는 전이는 거부한다.
- 전이 패밀리(6 base + *→error + error→{inactive,holding} = 12)에 없는 전이는 거부한다(REQ-057).
- 전이 전 current status == from_state 여야 한다(레이스 감지).
- closed->idle / pending_buy->idle 복구 시 점유 필드(symbol/qty/.../forced_close_at)를 초기화한다.
- closed->pending_buy 직접 재할당 시에도 이전 사이클의 점유 필드를 clean-slate 로 초기화한 뒤 새 진입 필드를 적용한다. entry_count 만 누적 보존(dcy-019/REQ-002).
- **INACTIVE 진입 시**(매수 롤백 / 매도 체결 / error 해소) 포지션·주문 점유 필드(qty/avg_price/limit_price/allocated_capital/order_id/strategy_id/broker_order_id/sell_strategy_id/forced_close_at/SL·TP)를 초기화하되 **자산 정체성(instance_key/portfolio_id/symbol/retired_at)은 보존**한다 — 영구 슬롯 재사용의 전제.
- buy admission(REQ-059/061): slot_id 정본(portfolio_id dual-accept) → 대상 자산 슬롯 활성화. FCFS, M(`max_active_slots`) 캡, 무치환(over-cap 시 기존 보유 유지·신규만 거부). active = holding+pending_buy+pending_sell.
- 청산 수량(REQ-062, D3): 집행 dispatch 의 매도 수량은 **브로커 잔고(hldg_qty) 정본** — slot.qty 미러 fallback 없음, 브로커 0 이면 skip+WARN(divergence 표면화).
## Entity: `SlotTransitionRecord`
@@ -162,9 +164,9 @@
## Shared Consistency Rules
- (trading_date, symbol) 재진입 카운트는 closed->idle 복구와 원자적으로 증가한다.
- 모든 상태 변경과 전이 로그 append 는 동일 advisory-locked 트랜잭션 안에서 일어난다.
- 재진입 정책 결정 입력은 daily_symbol_entries 카운터에서 읽고, slot_transition_log(감사 전용)를 join 하지 않는다.
- 모든 상태 변경과 전이 로그 append 는 동일 advisory-locked 트랜잭션 안에서 일어난다. advisory lock 은 인스턴스 스코프(`slot_advisory_lock_id(instance_key)`, REQ-057 NFR-1).
- 집행 dispatch/poll 큐 조회는 instance_key 스코프 — 공유 DB 의 두 데몬이 서로의 주문을 집행하지 않는다(REQ-056).
- holding ↔ 브로커 정합(REQ-062): 브로커 잔고가 reconcile ground truth. core holding/브로커 0 → slot error 격리, 수량 불일치 → WARN(미러 비정본), 브로커 보유/슬롯 없음 → WARN(unmanaged).
## Persistence / Integration Notes
@@ -174,9 +176,10 @@
## Current Gaps / Planned Changes
- daily_slot / daily_symbol_entries / slot_transition_log 의 물리 스키마(DDL)는 미이식 — 영속화 단계에서 작성.
- daily_slot_archive(EOD 아카이브)와 retention prune 은 trex-orbit 인프라 기능으로, 이번 순수 도메인 범위 밖.
- SlotState/필드 계약을 코드와 문서 사이에서 드리프트 없이 유지할 방법은 첫 Discovery 에서 정의(plan.md OQ-4).
- `daily_symbol_entries` 테이블은 폐기 상태로 잔존(코드 경로 없음) — 후속 정리 시 DROP 가능.
- daily_slot_archive(EOD 아카이브)와 retention prune 은 범위 밖 유지.
- 포지션 사이징(issue #1 잔여, dcy-020 OQ-4 분리)은 후속 Discovery.
- 실 cutover(REQ-064)는 운영자 실행: `trex-core-cutover --config <instance> --yes` (전체 rebuild, 보유 carry-over=브로커 잔고; avg_price 는 NULL 로 carry — 잔고 API 미제공).
## Update Triggers
@@ -190,3 +193,4 @@
- 2026-06-03 :: BAT-002 — PostgreSQL 영속화 확정 + `intent_log` 엔티티 추가(REQ-006/007/009).
- 2026-06-04 :: BAT-004 — 브로커 집행 레이어 반영(BrokerPort/paper·KIS 어댑터, execution 루프, broker_order_id 실행큐·멱등, reconciliation) (REQ-011~015).
- 2026-06-04 :: BAT-006 — ledger 통합 데이터 모델 반영(LedgerTrade DTO + `ledger_outbox` 테이블/`correlation_id` 멱등/outcome 어휘, FillStatus.execution_id/fee/tax 운반) (REQ-017~020).
- 2026-06-10 :: BAT-030 (dcy-020 마감) — 자산 중심 영구 슬롯 모델 확정: 5-state(inactive), idle/closed 폐합(마이그레이션 010), trading_date/entry_count DROP(011), instance_key/retired_at 정식화, slot_id intent 계약, M 캡 admission, 매도 수량 브로커 정본, daily_symbol_entries·일일 preallocation(dcy-014)·풀 admission(dcy-001/019) 폐기, cutover 도구(trex-core-cutover) (REQ-056~065).