Coverage for src/copytrading_engine/execution/application/restore_reconciliation.py: 85%

44 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-16 16:55 +0000

1"""Read-only broker evidence required before activating a restored ledger.""" 

2 

3from __future__ import annotations 

4 

5from copytrading_engine.execution.application.ports import BrokerRestoreEvidence 

6from copytrading_engine.execution.domain.ledger_state import LedgerSnapshot 

7from copytrading_engine.execution.domain.order_lifecycle import OrderStatus, map_broker_status 

8 

9 

10class RestoreReconciliationError(ValueError): 

11 """A restored account cannot be activated from incomplete or changed evidence.""" 

12 

13 

14def reconcile_restore_snapshot( 

15 snapshot: LedgerSnapshot, 

16 evidence: BrokerRestoreEvidence, 

17) -> None: 

18 """Require active identity, open-lot attribution, holdings, and activity evidence. 

19 

20 Any returned order or activity at/after the archived timestamp blocks 

21 activation. The bounded broker queries are not a complete external order 

22 history: an external order submitted and canceled unfilled before the cut can 

23 be absent from both the current open-order set and the post-cut cursor. That 

24 case has no position or future ownership effect and is accepted. App-owned 

25 unresolved intents, current open orders, changed holdings, and observed 

26 post-cut activity still block activation. This also catches a filled-and- 

27 closed round trip whose current net position is unchanged. Only orders backing 

28 lots that remain open are re-read for future sell attribution. 

29 """ 

30 if not evidence.complete: 

31 raise RestoreReconciliationError("complete broker activity evidence is unavailable") 

32 if snapshot.account_id is None or snapshot.environment is None: 32 ↛ 33line 32 didn't jump to line 33 because the condition on line 32 was never true

33 raise RestoreReconciliationError("restored broker identity is incomplete") 

34 if not evidence.account.active: 

35 raise RestoreReconciliationError("broker account is not active and tradable") 

36 if (evidence.account.id, evidence.environment) != ( 

37 snapshot.account_id, 

38 snapshot.environment, 

39 ): 

40 raise RestoreReconciliationError("broker account identity does not match the restore") 

41 if evidence.orders_after_snapshot or evidence.activity_ids_after_snapshot: 

42 raise RestoreReconciliationError("broker activity after the snapshot blocks restore") 

43 if evidence.open_order_client_ids: 

44 raise RestoreReconciliationError("open broker orders block restore activation") 

45 if snapshot.entry_halted or any( 

46 not incident.resolved for incident in snapshot.ownership_incidents.values() 

47 ): 

48 raise RestoreReconciliationError("saved account contains unresolved broker evidence") 

49 

50 for _, order in snapshot.orders.items(): 

51 if order.status == OrderStatus.ABORTED_BEFORE_SUBMIT: 51 ↛ 52line 51 didn't jump to line 52 because the condition on line 51 was never true

52 if order.broker_id is not None: 

53 raise RestoreReconciliationError("aborted order has an uncertain broker identity") 

54 continue 

55 if order.pending or order.status == OrderStatus.RELEASED_UNSUBMITTED: 

56 raise RestoreReconciliationError("saved order intent is unresolved") 

57 if order.broker_id is None: 57 ↛ 58line 57 didn't jump to line 58 because the condition on line 57 was never true

58 raise RestoreReconciliationError("saved order has an uncertain broker identity") 

59 

60 for lot_id, lot in snapshot.lots.items(): 

61 if lot.remaining_qty <= 0: 61 ↛ 62line 61 didn't jump to line 62 because the condition on line 61 was never true

62 continue 

63 for entry in lot.entries(lot_id): 

64 order = snapshot.orders.get(entry) 

65 broker_order = evidence.known_orders.get(entry) 

66 if order is None or broker_order is None: 

67 raise RestoreReconciliationError( 

68 "open owned lot is missing fresh broker order evidence" 

69 ) 

70 # A lot of one buy carries that buy's average; a joined lot checks each buy's own. 

71 average = lot.average_price if not lot.joined_entries else order.filled_avg_price 

72 if ( 

73 order.side != "buy" 

74 or order.broker_id is None 

75 or broker_order.id != order.broker_id 

76 or broker_order.client_order_id != entry 

77 or broker_order.symbol != order.symbol 

78 or broker_order.side != order.side 

79 or broker_order.qty != order.qty 

80 or broker_order.filled_qty != order.filled_qty 

81 or broker_order.filled_avg_price != average 

82 or broker_order.position_intent != order.position_intent 

83 or map_broker_status(broker_order.status) != order.status 

84 ): 

85 raise RestoreReconciliationError( 

86 "open owned lot differs from fresh broker order identity, quantity, status, " 

87 "or price" 

88 ) 

89 

90 expected = snapshot.expected_holdings 

91 actual = {symbol: quantity for symbol, quantity in evidence.positions.items() if quantity} 

92 if expected != actual: 

93 raise RestoreReconciliationError("broker holdings do not match the restored ledger")