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:
@@ -32,11 +32,11 @@ _SNAPSHOT = {
|
||||
# BAT-022: envelope per-slot state (operator-facing). `slots` queries read
|
||||
# this, not the universe `assets[]`.
|
||||
"slots": [
|
||||
{"slot_id": "S-1", "trading_date": "2026-06-08", "status": "holding",
|
||||
{"slot_id": "S-1", "status": "holding",
|
||||
"symbol": "005930", "qty": 10.0, "avg_price": 28700.0, "entry_price": None,
|
||||
"allocated_capital": None, "strategy_id": "orb", "sell_strategy_id": None,
|
||||
"portfolio_id": "PF-1", "forced_close_at": None},
|
||||
{"slot_id": "S-2", "trading_date": "2026-06-08", "status": "idle",
|
||||
{"slot_id": "S-2", "status": "inactive",
|
||||
"symbol": None, "qty": None, "avg_price": None, "entry_price": None,
|
||||
"allocated_capital": None, "strategy_id": None, "sell_strategy_id": None,
|
||||
"portfolio_id": None, "forced_close_at": None},
|
||||
@@ -81,7 +81,7 @@ def test_slots_shows_real_slot_state_not_universe(capsys):
|
||||
assert rpc.calls[0]["payload"]["touch_watchdog"] is False
|
||||
# both slots shown, with status column (slot state, not universe assets)
|
||||
assert "count=2" in out
|
||||
assert "S-1\tholding" in out and "S-2\tidle" in out
|
||||
assert "S-1\tholding" in out and "S-2\tinactive" in out
|
||||
|
||||
|
||||
def test_slots_status_filters_by_slot_status(capsys):
|
||||
@@ -97,7 +97,7 @@ def test_slots_marks_watchdog_owned(capsys):
|
||||
resp = {
|
||||
"assets": [], "view": "all", "available_slots": 9, "degraded": False,
|
||||
"reason": None,
|
||||
"slots": [{"slot_id": "S-1", "trading_date": "2026-06-08",
|
||||
"slots": [{"slot_id": "S-1",
|
||||
"status": "holding", "symbol": "005930", "qty": 10.0,
|
||||
"avg_price": 28700.0, "entry_price": None,
|
||||
"allocated_capital": None, "strategy_id": "orb",
|
||||
|
||||
@@ -6,8 +6,8 @@ import pytest
|
||||
from trex_core.runtime.config import DaemonConfig
|
||||
|
||||
_KEYS = (
|
||||
"TREX_POSTGRESQL_DSN", "TREX_TOTAL_SLOTS", "TREX_API_HOST", "TREX_API_PORT",
|
||||
"TREX_PAPER_FILL_AFTER_POLLS", "TREX_PAPER_QTY_PER_POLL",
|
||||
"TREX_POSTGRESQL_DSN", "TREX_EXECUTION_INTERVAL_SEC", "TREX_API_HOST",
|
||||
"TREX_API_PORT", "TREX_PAPER_FILL_AFTER_POLLS", "TREX_PAPER_QTY_PER_POLL",
|
||||
"TREX_PAPER_REJECT_SYMBOLS",
|
||||
)
|
||||
|
||||
@@ -21,12 +21,12 @@ def _clean_env(monkeypatch):
|
||||
def test_loads_values_from_dotenv(tmp_path, monkeypatch):
|
||||
"""AC-1: .env in CWD is loaded when the OS env var is unset."""
|
||||
(tmp_path / ".env").write_text(
|
||||
"TREX_POSTGRESQL_DSN=dbname=from_dotenv\nTREX_TOTAL_SLOTS=7\n"
|
||||
"TREX_POSTGRESQL_DSN=dbname=from_dotenv\nTREX_EXECUTION_INTERVAL_SEC=7.0\n"
|
||||
)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
cfg = DaemonConfig.from_env()
|
||||
assert cfg.dsn == "dbname=from_dotenv"
|
||||
assert cfg.total_slots == 7
|
||||
assert cfg.execution_interval_sec == 7.0
|
||||
|
||||
|
||||
def test_os_env_takes_precedence_over_dotenv(tmp_path, monkeypatch):
|
||||
@@ -44,7 +44,7 @@ def test_no_dotenv_uses_os_env_only(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("TREX_POSTGRESQL_DSN", "dbname=os_only")
|
||||
cfg = DaemonConfig.from_env()
|
||||
assert cfg.dsn == "dbname=os_only"
|
||||
assert cfg.total_slots == 10 # default
|
||||
assert cfg.execution_interval_sec == 1.0 # default
|
||||
|
||||
|
||||
def test_missing_dsn_raises(tmp_path, monkeypatch):
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Cutover rehearsal tests (dcy-020 / REQ-064, BAT-030 M4).
|
||||
|
||||
PostgreSQL-gated (TREX_POSTGRESQL_TEST_DSN) — the rehearsal the design
|
||||
requires before the operator runs the live cutover: full rebuild, broker
|
||||
holding carry-over, in-flight abort, unmapped abort/skip, dry-run rollback.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from trex_core.adapters.persistence.postgresql import PostgreSQLSlotRepository
|
||||
from trex_core.domain.slot import SlotService, SlotState
|
||||
from trex_core.runtime.cutover import CutoverAbort, run_cutover
|
||||
|
||||
INST = "default"
|
||||
UNIVERSE = [("pf-a", "005930"), ("pf-b", "000660"), ("pf-c", "035720")]
|
||||
|
||||
|
||||
def _legacy_rows(dsn):
|
||||
"""Seed pre-cutover state: an old pool-ish slot + a holding slot."""
|
||||
repo = PostgreSQLSlotRepository(dsn)
|
||||
svc = SlotService(repo, instance_key=INST)
|
||||
repo.reconcile_universe(INST, {"pf-old", "pf-b"})
|
||||
held = repo.find_slot_by_portfolio(INST, "pf-b")
|
||||
svc.transit_slot(held.slot_id, SlotState.INACTIVE, SlotState.PENDING_BUY,
|
||||
reason="r", actor="t", symbol="000660", qty=7.0)
|
||||
svc.transit_slot(held.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
|
||||
reason="r", actor="t", avg_price=100.0)
|
||||
return repo, svc
|
||||
|
||||
|
||||
def test_full_rebuild_with_broker_carry_over(pg_clean):
|
||||
repo, _ = _legacy_rows(pg_clean)
|
||||
report = run_cutover(
|
||||
pg_clean, INST, UNIVERSE, [("000660", 12)], # broker ground truth qty=12
|
||||
)
|
||||
assert report.deleted == 2 # pf-old + pf-b wiped
|
||||
assert report.created == 3 # one slot per universe asset
|
||||
assert report.holdings == 1
|
||||
slots = {s.portfolio_id: s for s in repo.list_slots(INST)}
|
||||
assert set(slots) == {"pf-a", "pf-b", "pf-c"}
|
||||
assert slots["pf-a"].status is SlotState.INACTIVE
|
||||
held = slots["pf-b"]
|
||||
assert held.status is SlotState.HOLDING
|
||||
assert held.qty == 12.0 # broker qty, NOT the old mirror (7)
|
||||
assert held.avg_price is None # balance API has no cost basis (WARN)
|
||||
assert held.symbol == "000660"
|
||||
# old pf-old row is gone
|
||||
assert repo.find_slot_by_portfolio(INST, "pf-old") is None
|
||||
|
||||
|
||||
def test_aborts_on_in_flight_pending(pg_clean):
|
||||
repo = PostgreSQLSlotRepository(pg_clean)
|
||||
svc = SlotService(repo, instance_key=INST)
|
||||
repo.reconcile_universe(INST, {"pf-a"})
|
||||
s = repo.find_slot_by_portfolio(INST, "pf-a")
|
||||
svc.transit_slot(s.slot_id, SlotState.INACTIVE, SlotState.PENDING_BUY,
|
||||
reason="r", actor="t", symbol="005930")
|
||||
with pytest.raises(CutoverAbort, match="in-flight"):
|
||||
run_cutover(pg_clean, INST, UNIVERSE, [])
|
||||
# nothing was changed
|
||||
assert repo.fetch_slot(s.slot_id).status is SlotState.PENDING_BUY
|
||||
|
||||
|
||||
def test_aborts_on_unmapped_broker_holding(pg_clean):
|
||||
with pytest.raises(CutoverAbort, match="outside the universe"):
|
||||
run_cutover(pg_clean, INST, UNIVERSE, [("999999", 3)])
|
||||
# DB untouched (abort happened before any write)
|
||||
repo = PostgreSQLSlotRepository(pg_clean)
|
||||
assert repo.list_slots(INST) == []
|
||||
|
||||
|
||||
def test_allow_unmapped_skips_with_warning(pg_clean):
|
||||
report = run_cutover(
|
||||
pg_clean, INST, UNIVERSE, [("999999", 3), ("005930", 5)],
|
||||
allow_unmapped=True,
|
||||
)
|
||||
assert report.unmapped == ["999999"]
|
||||
assert report.holdings == 1 # only the mapped one carried over
|
||||
repo = PostgreSQLSlotRepository(pg_clean)
|
||||
held = repo.find_slot_by_portfolio(INST, "pf-a")
|
||||
assert held.status is SlotState.HOLDING and held.qty == 5.0
|
||||
|
||||
|
||||
def test_dry_run_rolls_back(pg_clean):
|
||||
repo, _ = _legacy_rows(pg_clean)
|
||||
before = {s.slot_id for s in repo.list_slots(INST)}
|
||||
report = run_cutover(pg_clean, INST, UNIVERSE, [("000660", 12)], dry_run=True)
|
||||
assert report.dry_run and report.created == 3
|
||||
after = {s.slot_id for s in repo.list_slots(INST)}
|
||||
assert after == before # rolled back — nothing changed
|
||||
|
||||
|
||||
def test_instance_isolation_other_instance_untouched(pg_clean):
|
||||
other = PostgreSQLSlotRepository(pg_clean)
|
||||
other.reconcile_universe("inst-other", {"pf-z"})
|
||||
run_cutover(pg_clean, INST, UNIVERSE, [])
|
||||
assert other.find_slot_by_portfolio("inst-other", "pf-z") is not None
|
||||
|
||||
|
||||
def test_promote_unique_sets_not_null(pg_clean):
|
||||
import psycopg
|
||||
run_cutover(pg_clean, INST, UNIVERSE, [], promote_unique=True)
|
||||
with psycopg.connect(pg_clean) as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT is_nullable FROM information_schema.columns "
|
||||
"WHERE table_name='daily_slot' AND column_name='portfolio_id'"
|
||||
)
|
||||
assert cur.fetchone()[0] == "NO"
|
||||
# restore for other tests (pg_clean truncates but keeps schema)
|
||||
cur.execute("ALTER TABLE daily_slot ALTER COLUMN portfolio_id DROP NOT NULL")
|
||||
conn.commit()
|
||||
|
||||
|
||||
def test_audit_rows_written(pg_clean):
|
||||
import psycopg
|
||||
run_cutover(pg_clean, INST, UNIVERSE, [("005930", 5)])
|
||||
with psycopg.connect(pg_clean) as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT count(*) FROM slot_transition_log WHERE reason='cutover_rebuild'"
|
||||
)
|
||||
assert int(cur.fetchone()[0]) == 3
|
||||
@@ -52,11 +52,11 @@ def test_default_instance_key_when_from_env(monkeypatch):
|
||||
|
||||
|
||||
def test_trading_timezone_defaults_to_kst(tmp_path, monkeypatch):
|
||||
"""dcy-014 / REQ-048: trading TZ + daily trigger default to KST / midnight."""
|
||||
"""dcy-014 / REQ-048: trading TZ defaults to KST (preallocation trigger
|
||||
removed at BAT-030 with the pool model)."""
|
||||
monkeypatch.setenv("TREX_POSTGRESQL_DSN", "postgresql://x/y")
|
||||
inst = DaemonInstanceConfig.from_toml(_write_toml(tmp_path, 'instance_key = "i1"\n'))
|
||||
assert inst.trading_timezone == "Asia/Seoul"
|
||||
assert inst.daily_preallocation_time == "00:00"
|
||||
assert DaemonConfig.from_env().trading_timezone == "Asia/Seoul"
|
||||
|
||||
|
||||
@@ -65,11 +65,10 @@ def test_trading_timezone_from_toml_propagates(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("TREX_POSTGRESQL_DSN", "postgresql://x/y")
|
||||
path = _write_toml(
|
||||
tmp_path,
|
||||
'instance_key = "i2"\ntrading_timezone = "UTC"\ndaily_preallocation_time = "07:30"\n',
|
||||
'instance_key = "i2"\ntrading_timezone = "UTC"\n',
|
||||
)
|
||||
cfg = DaemonConfig.from_config(path)
|
||||
assert cfg.trading_timezone == "UTC"
|
||||
assert cfg.daily_preallocation_time == "07:30"
|
||||
|
||||
|
||||
def test_config_required_cli_exits_nonzero():
|
||||
|
||||
Reference in New Issue
Block a user