feat(ledger): dcy-018 option D cash/position write-back + 추정 현금 (BAT-023)
ledger write 응답의 portfolio-hub 권위 cash/quantity 를 스냅샷에 write-back 해
매수/매도 직후 "수량 live·현금 stale" 비대칭 제거(option D 활성화). portfolio-hub#8
(*_after 응답) 동작 중 확인으로 그간 deferred 됐던 REQ-030 을 닫음.
거버넌스: 전부 change-req (신규 REQ 없음, dcy-018 OQ-3 a).
- REQ-017: record_trade → LedgerWriteOutcome{result, cash_balance_after,
asset_quantity_after}. 어댑터가 응답 root flat *_after 파싱(new+duplicate, 누락 None)
- REQ-019: LedgerWriter 에 SnapshotStore 주입 → new+duplicate write-back
(best-effort, *_after 절대값이라 멱등). LedgerOutbox.pending_cash_delta()
- REQ-029: 추정 현금 오버레이(_apply_cash_estimate, cash_estimated 라벨, OQ-4 i)
+ 슬롯 오버레이 유지(OQ-1 B). 미정산 outbox delta 기반, write-back 수렴
- REQ-030: option D 활성화 → Approved→Implemented
best-effort 격리(NFR-1): write-back/추정 실패가 ledger 멱등·청산 무차단.
배치 번호: 동시 커밋된 BAT-022(slot-state, dcy-016)와 충돌해 BAT-023 으로 배정.
검증: 단위 350 passed/35 skipped, 인프라 게이트(PG+RabbitMQ) 385 passed, ruff clean.
신규 test_ledger_option_d + adapter/PG 테스트. BAT-023 release-candidate.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -13,6 +13,7 @@ from trex_core.application.ledger_port import (
|
||||
LedgerPermanentError,
|
||||
LedgerRetryableError,
|
||||
LedgerTrade,
|
||||
LedgerWriteResult,
|
||||
)
|
||||
|
||||
|
||||
@@ -90,6 +91,39 @@ def test_client_errors_are_permanent(status):
|
||||
adapter.record_trade(_trade())
|
||||
|
||||
|
||||
def test_outcome_parses_cash_quantity_after_on_new():
|
||||
"""dcy-018 / REQ-017: option D authoritative cash/quantity from 201 response."""
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(201, json={"cash_balance_after": 300000.0,
|
||||
"asset_quantity_after": 10})
|
||||
|
||||
out = PortfolioHubLedger("https://portfolio-hub.test", client=_client(handler)).record_trade(_trade())
|
||||
assert out.result is LedgerWriteResult.NEW
|
||||
assert out.cash_balance_after == 300000.0 and out.asset_quantity_after == 10.0
|
||||
|
||||
|
||||
def test_outcome_parses_after_on_duplicate():
|
||||
"""duplicate(200) also carries current authoritative values (OQ-2 b)."""
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(200, json={"duplicate": True,
|
||||
"cash_balance_after": 50000.0,
|
||||
"asset_quantity_after": 3})
|
||||
|
||||
out = PortfolioHubLedger("https://portfolio-hub.test", client=_client(handler)).record_trade(_trade())
|
||||
assert out.result is LedgerWriteResult.DUPLICATE_OK
|
||||
assert out.cash_balance_after == 50000.0 and out.asset_quantity_after == 3.0
|
||||
|
||||
|
||||
def test_outcome_after_none_when_response_omits():
|
||||
"""Older hub without *_after → None → write-back skipped downstream."""
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(201, json={"ok": True})
|
||||
|
||||
out = PortfolioHubLedger("https://portfolio-hub.test", client=_client(handler)).record_trade(_trade())
|
||||
assert out.result is LedgerWriteResult.NEW
|
||||
assert out.cash_balance_after is None and out.asset_quantity_after is None
|
||||
|
||||
|
||||
def test_429_stays_retryable():
|
||||
"""dcy-015 / REQ-017: rate-limit is transient → retryable (not permanent)."""
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
|
||||
@@ -89,6 +89,16 @@ def test_writer_marks_delivery_failed_permanent_on_pg(pg_clean):
|
||||
assert outbox.list_pending() == []
|
||||
|
||||
|
||||
def test_pending_cash_delta_on_pg(pg_clean):
|
||||
"""dcy-018 / REQ-029: estimated cash delta of pending rows summed by asset (SQL)."""
|
||||
outbox = PostgreSQLLedgerOutbox(pg_clean)
|
||||
outbox.enqueue(LedgerTrade(asset_id="PF-1", order_id="O-1", execution_id="cd-buy",
|
||||
side="buy", qty=10, price=1000.0, fee=1.0, tax=0.0,
|
||||
executed_at=datetime(2026, 6, 4, tzinfo=timezone.utc)))
|
||||
deltas = outbox.pending_cash_delta()
|
||||
assert deltas["PF-1"] == -(10 * 1000.0 + 1.0) # buy => cash down by notional+fee
|
||||
|
||||
|
||||
def test_backoff_row_skipped_by_pending_scan_on_pg(pg_clean):
|
||||
"""dcy-015 / REQ-019: a future next_retry_at excludes the row from list_pending."""
|
||||
outbox = PostgreSQLLedgerOutbox(pg_clean)
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
"""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 snapshot 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_handlers import _apply_cash_estimate
|
||||
from trex_core.application.portfolio import PortfolioItem, SnapshotStore
|
||||
|
||||
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) -------------------------------------
|
||||
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():
|
||||
outbox = InMemoryLedgerOutbox()
|
||||
outbox.enqueue(_trade(execution_id="b", side="buy", qty=10, price=1000.0, fee=1.0))
|
||||
payload = {"assets": [{"asset_id": "PF-1", "symbol": "005930",
|
||||
"cash_balance": 1_000_000.0, "asset_quantity": 0.0}]}
|
||||
_apply_cash_estimate(payload, outbox)
|
||||
a = payload["assets"][0]
|
||||
assert a["cash_estimated"] is True
|
||||
assert a["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
|
||||
@@ -19,6 +19,7 @@ from trex_core.application.ledger_port import (
|
||||
LedgerPermanentError,
|
||||
LedgerRetryableError,
|
||||
LedgerTrade,
|
||||
LedgerWriteOutcome,
|
||||
LedgerWriteResult,
|
||||
)
|
||||
|
||||
@@ -40,7 +41,7 @@ class _ProgrammableLedger:
|
||||
self.behavior = behavior
|
||||
self.calls = 0
|
||||
|
||||
def record_trade(self, trade) -> LedgerWriteResult:
|
||||
def record_trade(self, trade) -> LedgerWriteOutcome:
|
||||
self.calls += 1
|
||||
return self.behavior(trade)
|
||||
|
||||
@@ -142,7 +143,7 @@ def test_backoff_row_does_not_block_new_rows():
|
||||
def behavior(trade):
|
||||
if trade.asset_id == "PF-bad":
|
||||
raise LedgerRetryableError("503")
|
||||
return LedgerWriteResult.NEW
|
||||
return LedgerWriteOutcome(LedgerWriteResult.NEW)
|
||||
|
||||
outbox, ledger, writer = _wire(
|
||||
behavior, clock=lambda: now["t"], retry_base_sec=100.0, max_attempts=99,
|
||||
|
||||
Reference in New Issue
Block a user