Files
trex-core/tests/application/test_ledger_option_d.py
T
genichinandClaude Opus 4.8 f0ad37747b feat(rel-007): dcy-025/024 + BAT-035/036 — slots.req 즉시 교체 + safety_sell_enabled
BAT-035 (dcy-025): trex.snapshot.req → trex.slots.req 즉시 교체
- topology: SNAPSHOT_REQ_QUEUE 제거, SLOTS_REQ_QUEUE = "trex.slots.req" 추가
- portfolio.py: View/build_snapshot_envelope/SnapshotEnvelope/_asset_to_dict 제거;
  slot_to_dict 시그니처 확장(snapshot_store/watchdog_store/pause_store/watchdog_timeout_sec)
  — asset_quantity(hub)/cash_balance/cash_estimated/warned/watchdog{}/paused 병합 (REQ-074)
- messaging_handlers.py: make_snapshot_rpc_handler 제거, make_slots_rpc_handler 추가
  — filter(all/inactive/pending/holding/error) + spy(bool) 처리; strategy 필드 제외 (REQ-073/074)
- daemon.py: _snapshot_rpc_loop → _slots_rpc_loop, make_slots_rpc_handler 연결
- cli.py: universe/slots → slots_queue + spy=True + server-side filter; buyable→inactive 매핑 (REQ-063)
- rabbitmq.py: snapshot_queue → slots_queue
- docs: interface-contract.md + runtime-flows.md slots.req 계약으로 업데이트 (REQ-075)
- REQ-028: Implemented → Deprecated (코드 삭제 완료)
- 테스트: test_snapshot_handler/selection/rpc_watchdog/messaging_snapshot_consumer 삭제;
  test_slots_handler.py(신규, 13 cases), test_killswitch_masking_resume 재작성,
  test_ledger_option_d._apply_cash_estimate → slots handler 경유, test_topology/cli_operator 갱신

BAT-036 (dcy-024): per-instance safety_sell_enabled 플래그
- config.py: DaemonInstanceConfig + DaemonConfig 에 safety_sell_enabled: bool = True 추가;
  from_toml 파싱, from_config 전파
- daemon.py: start() workers 조건부 — safety_sell_enabled=false 시 trex-safety-sell 미기동 + WARNING
- tests: test_instance_config.py 에 safety_sell_enabled 파싱 3개 케이스 추가

REQ: 073/074/075/021/034/063/048/005 Approved → Implemented

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-11 14:45:45 +09:00

128 lines
5.5 KiB
Python

"""Option D cash/position write-back + estimate overlay tests (dcy-018, issue: cash stale).
Covers: LedgerWriter write-back to SnapshotStore on new/duplicate, skip when
*_after missing, best-effort isolation, and the slots handler's estimated-cash
overlay from pending outbox deltas (OQ-4).
"""
from __future__ import annotations
from datetime import datetime, timezone
from trex_core.adapters.ledger.in_memory import InMemoryLedger
from trex_core.application.ledger_outbox import (
InMemoryLedgerOutbox,
LedgerWriter,
trade_cash_delta,
)
from trex_core.application.ledger_port import LedgerTrade
from trex_core.application.messaging import RpcRequest
from trex_core.application.messaging_handlers import make_slots_rpc_handler
from trex_core.application.portfolio import PortfolioItem, SnapshotStore
from trex_core.domain.slot.in_memory_repository import InMemorySlotRepository
UTC = timezone.utc
def _trade(execution_id="e-1", asset="PF-1", side="buy", qty=10, price=1000.0, fee=1.0):
return LedgerTrade(asset_id=asset, order_id="O-1", execution_id=execution_id,
side=side, qty=qty, price=price, fee=fee,
executed_at=datetime(2026, 6, 4, tzinfo=UTC))
def _store_with(pid="PF-1", cash=1_000_000.0, qty=0.0):
s = SnapshotStore()
s.swap([PortfolioItem(portfolio_id=pid, symbol="005930",
cash_balance=cash, asset_quantity=qty)])
return s
# --- write-back (REQ-019/030) ----------------------------------------------
def test_writeback_updates_snapshot_on_new():
store = _store_with()
outbox = InMemoryLedgerOutbox()
ledger = InMemoryLedger(cash_after=300_000.0, quantity_after=10.0)
writer = LedgerWriter(outbox, ledger, snapshot_store=store)
outbox.enqueue(_trade())
writer.run_once()
a = store.get("PF-1").item
assert a.cash_balance == 300_000.0 and a.asset_quantity == 10.0
def test_writeback_applies_on_duplicate_too():
store = _store_with(cash=1_000_000.0)
outbox = InMemoryLedgerOutbox()
# execution already recorded once → second write is duplicate, *_after still authoritative
ledger = InMemoryLedger(cash_after=300_000.0, quantity_after=10.0)
ledger.record_trade(_trade(execution_id="dup")) # pre-record → next is duplicate
writer = LedgerWriter(outbox, ledger, snapshot_store=store)
outbox.enqueue(_trade(execution_id="dup"))
writer.run_once()
assert store.get("PF-1").item.cash_balance == 300_000.0 # duplicate still wrote back
def test_writeback_skipped_when_after_missing():
store = _store_with(cash=1_000_000.0)
outbox = InMemoryLedgerOutbox()
ledger = InMemoryLedger() # no cash_after/quantity_after → None
writer = LedgerWriter(outbox, ledger, snapshot_store=store)
outbox.enqueue(_trade())
writer.run_once()
assert store.get("PF-1").item.cash_balance == 1_000_000.0 # unchanged
def test_writeback_best_effort_does_not_block_completion():
class _BoomStore:
def update_cash_position(self, *a, **k):
raise RuntimeError("boom")
outbox = InMemoryLedgerOutbox()
ledger = InMemoryLedger(cash_after=1.0, quantity_after=1.0)
writer = LedgerWriter(outbox, ledger, snapshot_store=_BoomStore())
outbox.enqueue(_trade())
stats = writer.run_once()
assert stats.completed == 1 # ledger still completed despite write-back error
def test_no_writeback_without_store():
outbox = InMemoryLedgerOutbox()
ledger = InMemoryLedger(cash_after=1.0, quantity_after=1.0)
writer = LedgerWriter(outbox, ledger) # no snapshot_store
outbox.enqueue(_trade())
assert writer.run_once().completed == 1 # no crash
# --- estimate overlay (REQ-029 / OQ-4) — via make_slots_rpc_handler ----------
def test_pending_cash_delta_sums_by_asset():
outbox = InMemoryLedgerOutbox()
outbox.enqueue(_trade(execution_id="b", side="buy", qty=10, price=1000.0, fee=1.0))
deltas = outbox.pending_cash_delta()
assert deltas["PF-1"] == trade_cash_delta(_trade(side="buy", qty=10, price=1000.0, fee=1.0))
assert deltas["PF-1"] == -(10 * 1000.0 + 1.0) # buy: cash down
def test_apply_cash_estimate_overlays_pending_delta():
"""Cash-estimated overlay applied through slots handler (REQ-029 OQ-4)."""
outbox = InMemoryLedgerOutbox()
outbox.enqueue(_trade(execution_id="b", side="buy", qty=10, price=1000.0, fee=1.0))
store = _store_with(pid="PF-1", cash=1_000_000.0, qty=0.0)
repo = InMemorySlotRepository()
repo.reconcile_universe("default", {"PF-1"})
handler = make_slots_rpc_handler(repo, snapshot_store=store, ledger_outbox=outbox)
resp = handler(RpcRequest(payload={"filter": "all"}, correlation_id="test"))
slots = resp.payload["slots"]
pf1 = next(s for s in slots if s["portfolio_id"] == "PF-1")
assert pf1["cash_estimated"] is True
assert pf1["cash_balance"] == 1_000_000.0 - (10 * 1000.0 + 1.0) # estimated cash
def test_estimate_clears_after_writeback():
"""Once the ledger write completes (no longer pending), the estimate is gone."""
store = _store_with(cash=1_000_000.0)
outbox = InMemoryLedgerOutbox()
ledger = InMemoryLedger(cash_after=989_999.0, quantity_after=10.0)
writer = LedgerWriter(outbox, ledger, snapshot_store=store)
outbox.enqueue(_trade(side="buy", qty=10, price=1000.0, fee=1.0))
assert outbox.pending_cash_delta() # estimate present while pending
writer.run_once() # completes → write-back authoritative
assert outbox.pending_cash_delta() == {} # no longer pending → no estimate
assert store.get("PF-1").item.cash_balance == 989_999.0