"""Execution loop ledger-hook tests (REQ-018, REQ-019, dcy-004). Exercises the full buy/sell lifecycle with the in-memory paper broker and in-memory outbox + ledger writer, ensuring the slot transition is on the critical path while the ledger write is eventually-consistent. """ from __future__ import annotations from datetime import date from trex_core.adapters.broker.paper import PaperBroker from trex_core.adapters.ledger.in_memory import InMemoryLedger from trex_core.adapters.persistence.in_memory_intent_store import InMemoryIntentStore from trex_core.application.execution import ExecutionService from trex_core.application.intents import BuyIntent, IntentService, SellIntent from trex_core.application.ledger_outbox import ( InMemoryLedgerOutbox, LedgerWriter, OutboxOutcome, WorkItemStatus, ) from trex_core.domain.slot import SlotService, SlotState from trex_core.domain.slot.in_memory_repository import InMemorySlotRepository DAY = date(2026, 6, 4) def _wire(broker, *, ledger=None): repo = InMemorySlotRepository() svc = SlotService(repo) intents = IntentService(svc, repo, InMemoryIntentStore()) outbox = InMemoryLedgerOutbox() execution = ExecutionService(svc, repo, broker, ledger_outbox=outbox) writer = LedgerWriter(outbox, ledger or InMemoryLedger()) svc.preallocate_daily_slots(DAY, 5) return repo, svc, intents, execution, outbox, writer def _buy(intents, *, iid="b1", portfolio_id="PF-1"): return intents.submit_buy(BuyIntent( intent_id=iid, trading_date=DAY, symbol="005930", qty=10, entry_price=1000, portfolio_id=portfolio_id, )) def test_buy_fill_enqueues_one_ledger_item_and_writer_records_it(): ledger = InMemoryLedger() repo, svc, intents, execution, outbox, writer = _wire(PaperBroker(fill_after_polls=0), ledger=ledger) sid = _buy(intents).slot_id r = execution.run_once() assert r.filled == 1 and r.ledger_enqueued == 1 assert repo.fetch_slot(sid).status is SlotState.HOLDING stats = writer.run_once() assert stats.completed == 1 assert ledger.count() == 1 t = ledger.trades()[0] assert (t.asset_id, t.side, t.qty, t.price) == ("PF-1", "buy", 10, 1000.0) assert t.execution_id.startswith("paper:PAPER-") assert t.fee > 0.0 and t.tax == 0.0 def test_sell_fill_enqueues_sell_ledger_item(): ledger = InMemoryLedger() repo, svc, intents, execution, outbox, writer = _wire(PaperBroker(fill_after_polls=0), ledger=ledger) sid = _buy(intents).slot_id execution.run_once() # -> holding + buy ledger item writer.run_once() # drain buy intents.submit_sell(SellIntent(intent_id="s1", slot_id=sid)) r = execution.run_once() # dispatch sell + fill -> closed + sell ledger item assert r.ledger_enqueued == 1 assert repo.fetch_slot(sid).status is SlotState.CLOSED writer.run_once() sides = [t.side for t in ledger.trades()] assert sides == ["buy", "sell"] def test_portfolio_id_absent_skips_ledger_but_transitions_slot(): ledger = InMemoryLedger() repo, svc, intents, execution, outbox, writer = _wire(PaperBroker(fill_after_polls=0), ledger=ledger) sid = _buy(intents, iid="no-pf", portfolio_id=None).slot_id r = execution.run_once() assert r.filled == 1 and r.ledger_enqueued == 0 and r.ledger_skipped == 1 assert repo.fetch_slot(sid).status is SlotState.HOLDING assert outbox.all_items() == [] assert ledger.count() == 0 def test_duplicate_execution_id_results_in_zero_duplicate_in_ledger(): """REQ-019 AC-1: same execution_id enqueued twice = 1 ledger entry.""" ledger = InMemoryLedger() repo, svc, intents, execution, outbox, writer = _wire(PaperBroker(fill_after_polls=0), ledger=ledger) _buy(intents).slot_id execution.run_once() writer.run_once() assert ledger.count() == 1 # Re-enqueue the same trade explicitly (simulate accidental re-fill). first = outbox.all_items()[0] outbox.enqueue(first.trade) # idempotent on correlation_id stats = writer.run_once() # still terminal-completed; reports duplicate assert stats.duplicates >= 1 assert ledger.count() == 1 # no duplicate in the ledger def test_retryable_failure_then_eventually_completes(): """REQ-019 AC-2: retry until completed; slot transition unaffected.""" ledger = InMemoryLedger(fail_n_then_succeed=2) repo, svc, intents, execution, outbox, writer = _wire(PaperBroker(fill_after_polls=0), ledger=ledger) sid = _buy(intents).slot_id execution.run_once() assert repo.fetch_slot(sid).status is SlotState.HOLDING # slot already transitioned stats1 = writer.run_once() assert stats1.retryable == 1 and stats1.completed == 0 and ledger.count() == 0 stats2 = writer.run_once() assert stats2.retryable == 1 and ledger.count() == 0 stats3 = writer.run_once() assert stats3.completed == 1 and ledger.count() == 1 # outbox row terminal-completed [item] = outbox.all_items() assert item.status is WorkItemStatus.COMPLETED assert item.last_outcome is OutboxOutcome.COMPLETED def test_conflict_blocks_without_auto_retry(): """REQ-019 AC-3: 409 conflict halts auto-retry.""" # The execution_id paper synthesizes is paper:{oid}:{qty}; first dispatched # order id is PAPER-000001 / qty=10 => execution_id = paper:PAPER-000001:10. conflict_id = "paper:PAPER-000001:10" ledger = InMemoryLedger(conflict_executions={conflict_id}) repo, svc, intents, execution, outbox, writer = _wire(PaperBroker(fill_after_polls=0), ledger=ledger) _buy(intents) execution.run_once() stats = writer.run_once() assert stats.conflicts == 1 [item] = outbox.all_items() assert item.status is WorkItemStatus.CONFLICT_BLOCKED # second writer tick must NOT call the adapter again stats2 = writer.run_once() assert stats2.completed == 0 and stats2.retryable == 0 # ledger is still empty (conflict blocked; operator resolves) assert ledger.count() == 0 def test_duplicate_completed_when_reprocessing_terminal_item(): """REQ-019 AC-4: a completed item reports duplicate_completed if re-listed.""" ledger = InMemoryLedger() repo, svc, intents, execution, outbox, writer = _wire(PaperBroker(fill_after_polls=0), ledger=ledger) _buy(intents) execution.run_once() writer.run_once() # Force a duplicate enqueue of the same trade — outbox keeps single row, # ledger keeps single entry. [item] = outbox.all_items() outbox.enqueue(item.trade) assert len(outbox.all_items()) == 1 # Writer sees no PENDING rows now; stats are all zero (terminal). stats = writer.run_once() assert stats.completed == 0 and stats.duplicates == 0 and stats.retryable == 0 assert ledger.count() == 1 def test_slot_transition_proceeds_when_ledger_is_down(): """REQ-019 AC-5: portfolio-hub outage does not block the fill transition.""" ledger = InMemoryLedger(fail_n_then_succeed=100) repo, svc, intents, execution, outbox, writer = _wire(PaperBroker(fill_after_polls=0), ledger=ledger) sid = _buy(intents).slot_id execution.run_once() assert repo.fetch_slot(sid).status is SlotState.HOLDING writer.run_once() # all retries fail assert ledger.count() == 0 [item] = outbox.all_items() assert item.status is WorkItemStatus.PENDING # still waiting for retry