Implement REQ-005~009 (dcy-002 slice 1) as an onion stack on top of the
BAT-001 pure domain:
- application: IntentService (admission + single-writer transition +
intent_id idempotency via durable intent_log)
- adapters/persistence: PostgreSQLSlotRepository + PostgreSQLIntentStore +
trex-core-owned migrations (daily_slot per Appendix A, daily_symbol_entries,
slot_transition_log, intent_log) + in-memory intent store
- adapters/api: FastAPI /v1 (healthz, intents/buy|sell|{id}, slots, capacity)
- runtime: trex-core-daemon entrypoint with lifespan migrate+preallocate
Verification (against local PostgreSQL 18): 74 passed, ruff clean, domain
import sweep shows zero web/db deps (NFR-1), 20-thread concurrency admits
exactly the idle count (NFR-2), idempotent resubmit causes no double
transition (NFR-3), EXPECTED_SLOT_FIELDS<->information_schema drift test
(realizes dcy-001 OQ-2's deferred DB-side check), and a daemon E2E smoke.
Align all four baseline docs to the new daemon/API/persistence layers.
BAT-002 -> release-candidate; REQ-005~009 -> Implemented. Full async outbox,
broker execution, safety floor, and strategy daemons remain deferred to a
follow-up Discovery.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
5.5 KiB
5.5 KiB
Trex Core Runtime Flows
- Baseline Mode: mixed
- Baseline Seed: .stage-pilot/bootstrap/baseline.yaml
- Status: draft
- Owner: project maintainers
- Last Updated (KST): 2026-06-03 (BAT-002)
- Source Discovery / Batch: bootstrap-baseline (pre-Discovery); 데몬/HTTP 흐름 = dcy-002 / BAT-002
- Primary Runtime: daemon (HTTP API) + library (slot 도메인)
Project Summary
- trex 제품군의 공용 베이스로, 첫 도메인으로 trex-orbit 의 일일 거래 슬롯 생명주기(slot) 순수 도메인을 storage-agnostic 하게 이식한 코어다.
Purpose
- This document is the current approved execution-flow baseline for the project.
- It is a cross-cutting reference document for Discovery, REQ, Batch Design, Batch Verification, and implementation updates.
Scope
- Covers representative domain-service flows (library 형태이므로 외부 명령이 아니라 in-process API 호출 흐름).
- Does not duplicate full acceptance criteria or low-level implementation details.
Covered Entry Points
trex-core-daemon:: 슬롯 코어 데몬 (lifecycle + HTTP/v1서빙, BAT-002)- HTTP
/v1:: intent 제출/조회 경계 (전략 데몬 클라이언트) - SlotService :: 슬롯 생명주기 도메인 서비스 (preallocate / transit / capacity / entry-count)
- SlotRepository (Protocol) :: 저장소 구현체 주입 경계
Flow: 데몬 lifecycle (BAT-002)
trex-core-daemon기동 →DaemonConfig.from_env()(TREX_POSTGRESQL_DSN 등).- startup(lifespan):
apply_migrations(dsn)(멱등) → 거래일 슬롯preallocate_daily_slots(멱등, 공개 엔드포인트 아님). - uvicorn 이 FastAPI
/v1앱 서빙(GET /v1/healthz200). - shutdown: 연결-당-호출 어댑터라 풀 정리 없음, graceful 종료.
Flow: 매수 intent (POST /v1/intents/buy, BAT-002)
- 전략 데몬이 intent(intent_id 포함)를 POST.
- IntentService:
intent_log.try_insert(intent_id) dedup 게이트 — 중복이면 기존 decision 동기 반환(슬롯 무전이). - 신규면 admission:
find_idle_slot→SlotService.transit_slot(idle→pending_buy)(advisory lock 단일 writer). last-idle 경합 시 StateMismatch 재시도. intent_log.finalize(admitted/rejected, slot_id)→ admit/reject 동기 응답.
Flow: 매도 intent (POST /v1/intents/sell, BAT-002)
- 전략 데몬이 holding 슬롯을
GET /v1/slots?status=holding로 조회 후 sell intent POST. - dedup 게이트 → 검증(slot 이 holding 인가) →
transit_slot(holding→pending_sell)→ finalize → 동기 응답.
Shared Components
- SlotRepository Protocol :: 저장소 추상화. 구현체(InMemorySlotRepository, 향후 PostgreSQLSlotRepository)를 주입.
- SLOT_ADVISORY_LOCK_ID :: 모든 상태 변경을 직렬화하는 공유 advisory lock 식별자.
- transactional_advisory_lock :: 단일 트랜잭션 + advisory lock 컨텍스트(외부 I/O 금지).
Flow: slot 사전 할당 (preallocate_daily_slots)
- 호출자가
preallocate_daily_slots(trading_date, count)를 호출한다(count > 0 검증). - SlotService 가
transactional_advisory_lock(SLOT_ADVISORY_LOCK_ID)를 획득한다. - 저장소가 해당 trading_date 에 슬롯이 이미 있으면 0 을 반환(멱등), 없으면
count개 idle 슬롯을 삽입한다. - 삽입된 슬롯 수를 반환한다.
Flow: slot 상태 전이 (transit_slot)
- 호출자가
transit_slot(slot_id, from_state, to_state, reason, actor, **fields)를 호출한다. - (from_state, to_state) 가 8 전이 패밀리에 속하는지 먼저 검증한다(아니면 SlotTransitionError).
- advisory lock 획득 후 슬롯을 fetch 한다(없으면 SlotNotFoundError).
- 현재 status == from_state 인지 확인한다(아니면 SlotStateMismatchError — 레이스 감지).
- to_state 의미에 맞춰 점유 필드를 계산하고 슬롯 행을 update 한다. (closed/pending_buy -> idle 은 점유 초기화)
- closed -> idle 복구면 (trading_date, symbol) 재진입 카운트를 +1 한다.
- slot_transition_log 에 전이 기록 1행을 append 하고 갱신된 슬롯을 반환한다.
- 외부 I/O(브로커 등)는 lock 밖에서 호출자가 수행한다(lock 보유 중 금지).
Flow Constraints
- 모든 상태 변경 API 는 advisory-locked 단일 트랜잭션 안에서 수행한다.
- lock 보유 중에는 외부 I/O 를 수행하지 않는다.
- slot_transition_log 는 append-only 다(UPDATE/DELETE 금지).
- 상태 전이는 read(현재 상태)-검증-write 가 동일 트랜잭션에서 원자적으로 이뤄져 레이스를 차단한다.
Current Gaps / Planned Changes
- 실제 영속화(PostgreSQL) 흐름은 미구현 — 현재는 in-memory repository 로만 구동.
- CLI/데몬 런타임 흐름 없음(library). 상위 애플리케이션 통합 흐름은 영속화 단계 이후 정의.
- 강제 청산/EOD 같은 상위 운영 흐름은 이번 순수 도메인 범위 밖.
Update Triggers
- Update this document when a command entry point changes.
- Update this document when a runtime orchestration path changes.
- Update this document when a batch changes the approved flow baseline.
Change Log
- 2026-06-03 :: bootstrap-baseline 으로 초기 흐름 baseline 생성(slot 도메인 in-process API 흐름 기준).
- 2026-06-03 :: BAT-001 이식 완료 반영 — preallocate/transit 흐름이
trex_core.domain.slot실제 코드로 구현됨(REQ-004). 영속화/CLI 흐름은 여전히 미구현(범위 밖). - 2026-06-03 :: BAT-002 — 데몬 lifecycle + 매수/매도 intent HTTP 흐름 추가, Primary Runtime=daemon+library(REQ-005~009). 브로커 집행/safety floor 흐름은 후속 Discovery.