Coverage for src/copytrading_engine/trading/adapters/routing.py: 87%

69 statements  

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

1"""Bind queued source and parser work to the saved routing configuration.""" 

2 

3import json 

4import re 

5import sqlite3 

6from pathlib import Path 

7 

8from copytrading_engine.execution.adapters.ownership_probe import ( 

9 UnsettledOwnership, 

10 unsettled_ownership, 

11) 

12from copytrading_engine.shared.sqlite import SchemaComponent, SQLiteUnit, ensure_schema 

13from copytrading_engine.trading.domain.config import TradingConfiguration 

14 

15ROUTING_SCHEMA = SchemaComponent( 

16 "trading_routing", 

17 1, 

18 """ 

19CREATE TABLE IF NOT EXISTS trading_routing_revision ( 

20 singleton INTEGER PRIMARY KEY CHECK (singleton=1), 

21 fingerprint TEXT NOT NULL, 

22 account_ids TEXT NOT NULL 

23); 

24""", 

25) 

26 

27 

28class RoutingChangePending(Exception): 

29 """A new configuration cannot claim work captured under a prior route.""" 

30 

31 

32class AccountOwnershipPending(Exception): 

33 """Removing these local accounts would abandon work they still have in flight. 

34 

35 `accounts` names each removed account, A to Z, with that work; None when its records could 

36 not be read, so whether it has any is unknown.""" 

37 

38 def __init__(self, accounts: tuple[tuple[str, UnsettledOwnership | None], ...]) -> None: 

39 super().__init__(", ".join(account_id for account_id, _ in accounts)) 

40 self.accounts = accounts 

41 

42 

43class RoutingRevision: 

44 def __init__(self, unit: SQLiteUnit, account_root: Path) -> None: 

45 self._unit = unit 

46 self._account_root = account_root 

47 

48 @classmethod 

49 async def open(cls, path: Path) -> RoutingRevision: 

50 unit = await SQLiteUnit.open(path) 

51 try: 

52 await unit.run( 

53 lambda db: ensure_schema(db, ROUTING_SCHEMA), 

54 write=True, 

55 ) 

56 return cls(unit, path.parent / "accounts") 

57 except BaseException: 

58 await unit.close() 

59 raise 

60 

61 async def validate(self, configuration: TradingConfiguration) -> None: 

62 """Check revision ownership and pending work without committing a new revision.""" 

63 await self._unit.run(lambda db: self._check(db, configuration, commit=False), write=False) 

64 

65 async def accept(self, configuration: TradingConfiguration) -> None: 

66 """Persist a validated revision after atomically rechecking pending work.""" 

67 await self._unit.run(lambda db: self._check(db, configuration, commit=True), write=True) 

68 

69 def _check( 

70 self, db: sqlite3.Connection, configuration: TradingConfiguration, *, commit: bool 

71 ) -> None: 

72 fingerprint = configuration.routing_revision() 

73 new_accounts = {account.id for account in configuration.accounts} 

74 old = db.execute( 

75 "SELECT fingerprint,account_ids FROM trading_routing_revision WHERE singleton=1" 

76 ).fetchone() 

77 if old is not None and old[0] == fingerprint: 

78 return 

79 if old is not None: 

80 saved_accounts = json.loads(old[1]) 

81 if not isinstance(saved_accounts, list) or not all( 81 ↛ 84line 81 didn't jump to line 84 because the condition on line 81 was never true

82 isinstance(value, str) for value in saved_accounts 

83 ): 

84 raise RuntimeError("Saved account identities are invalid") 

85 prior_accounts = set(saved_accounts) 

86 else: 

87 prior_accounts = set() 

88 if self._account_root.exists(): 

89 if self._account_root.is_symlink(): 89 ↛ 90line 89 didn't jump to line 90 because the condition on line 89 was never true

90 raise RuntimeError("Account state directory is invalid") 

91 prior_accounts.update(path.name for path in self._account_root.iterdir()) 

92 unsettled: list[tuple[str, UnsettledOwnership | None]] = [] 

93 for account_id in sorted(prior_accounts - new_accounts): 

94 if not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", account_id): 94 ↛ 95line 94 didn't jump to line 95 because the condition on line 94 was never true

95 raise RuntimeError("Saved account identity is invalid") 

96 account_dir = self._account_root / account_id 

97 if account_dir.is_symlink(): 97 ↛ 98line 97 didn't jump to line 98 because the condition on line 97 was never true

98 raise RuntimeError("Account state directory is invalid") 

99 try: 

100 held = unsettled_ownership(account_dir) 

101 except RuntimeError: 

102 unsettled.append((account_id, None)) 

103 continue 

104 if held is not None: 

105 unsettled.append((account_id, held)) 

106 if unsettled: 

107 raise AccountOwnershipPending(tuple(unsettled)) 

108 pending = any( 

109 db.execute(query).fetchone() is not None 

110 for query in ( 

111 "SELECT 1 FROM source_captures WHERE mode='live' AND confirmed=0 LIMIT 1", 

112 "SELECT 1 FROM parser_inbox WHERE result IS NULL LIMIT 1", 

113 "SELECT 1 FROM parser_signal_deliveries WHERE delivered_at IS NULL LIMIT 1", 

114 ) 

115 ) 

116 if pending: 

117 raise RoutingChangePending 

118 if commit: 118 ↛ exitline 118 didn't return from function '_check' because the condition on line 118 was always true

119 db.execute( 

120 "INSERT INTO trading_routing_revision(singleton,fingerprint,account_ids) " 

121 "VALUES (1,?,?) ON CONFLICT(singleton) DO UPDATE SET " 

122 "fingerprint=excluded.fingerprint,account_ids=excluded.account_ids", 

123 (fingerprint, json.dumps(sorted(new_accounts))), 

124 ) 

125 

126 async def close(self) -> None: 

127 await self._unit.close()