Coverage for src/copytrading_engine/execution/application/restore_preflight.py: 75%

130 statements  

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

1"""Eligibility policy for restoring an archived execution snapshot.""" 

2 

3from __future__ import annotations 

4 

5from dataclasses import dataclass 

6from datetime import datetime 

7from enum import StrEnum 

8from typing import Literal, Protocol 

9 

10from pydantic import SecretStr 

11 

12from copytrading_engine.execution.application.ports import RestoreEvidenceBroker 

13from copytrading_engine.execution.application.restore_reconciliation import ( 

14 RestoreReconciliationError, 

15 reconcile_restore_snapshot, 

16) 

17from copytrading_engine.execution.domain.ledger_state import LedgerSnapshot 

18 

19 

20class RestorePreflightBlocker(StrEnum): 

21 CANDIDATE_INVALID = "candidate_invalid" 

22 CANDIDATE_CHANGED = "candidate_changed" 

23 APPLICATION_WORK_PENDING = "application_work_pending" 

24 ACCOUNT_OUTBOX_PENDING = "account_outbox_pending" 

25 ACCOUNT_SNAPSHOT_INCOMPLETE = "account_snapshot_incomplete" 

26 ACCOUNT_IDENTITY_MISMATCH = "account_identity_mismatch" 

27 BROKER_STATE_MISMATCH = "broker_state_mismatch" 

28 BROKER_EVIDENCE_UNAVAILABLE = "broker_evidence_unavailable" 

29 

30 

31@dataclass(frozen=True, slots=True) 

32class RestoreBrokerCredential: 

33 account_id: str 

34 environment: Literal["paper", "live"] 

35 key: SecretStr 

36 secret: SecretStr 

37 

38 

39@dataclass(frozen=True, slots=True) 

40class RestoreAccountInspection: 

41 account_id: str 

42 snapshot: LedgerSnapshot 

43 pending_delivery: bool 

44 

45 

46@dataclass(frozen=True, slots=True) 

47class RestoreCandidateInspection: 

48 """Immutable facts read by an outer adapter from a validated candidate.""" 

49 

50 candidate_id: str 

51 created_at: datetime 

52 environment_ids: tuple[str, ...] 

53 account_member_ids: tuple[str, ...] 

54 accounts: tuple[RestoreAccountInspection, ...] 

55 incomplete_account_ids: tuple[str, ...] 

56 application_readable: bool 

57 application_work_pending: bool 

58 candidate_manifest_sha256: str 

59 

60 

61class RestoreCandidateInspector(Protocol): 

62 def inspect_candidate(self, candidate_id: str) -> RestoreCandidateInspection: ... 

63 

64 

65class RestoreEvidenceBrokerFactory(Protocol): 

66 def __call__(self, credential: RestoreBrokerCredential) -> RestoreEvidenceBroker: ... 

67 

68 

69@dataclass(frozen=True, slots=True) 

70class RestorePreflightResult: 

71 candidate_id: str 

72 checked_account_count: int 

73 blockers: tuple[RestorePreflightBlocker, ...] 

74 

75 @property 

76 def eligible(self) -> bool: 

77 return not self.blockers 

78 

79 

80class RestoreCandidatePreflight: 

81 """Coordinate local snapshot inspection and read-only broker reconciliation.""" 

82 

83 def __init__( 

84 self, 

85 inspector: RestoreCandidateInspector, 

86 broker_factory: RestoreEvidenceBrokerFactory, 

87 ) -> None: 

88 self._inspector = inspector 

89 self._broker_factory = broker_factory 

90 

91 def preflight_restore_candidate( 

92 self, 

93 candidate_id: str, 

94 credentials: tuple[RestoreBrokerCredential, ...], 

95 ) -> RestorePreflightResult: 

96 blockers: set[RestorePreflightBlocker] = set() 

97 checked_accounts = 0 

98 try: 

99 inspection = self._inspector.inspect_candidate(candidate_id) 

100 except Exception: # noqa: BLE001 - any failure blocks the restore candidate 

101 return self._result( 

102 candidate_id, 

103 checked_accounts, 

104 {RestorePreflightBlocker.CANDIDATE_INVALID}, 

105 ) 

106 

107 try: 

108 if inspection.candidate_id != candidate_id: 108 ↛ 109line 108 didn't jump to line 109 because the condition on line 108 was never true

109 blockers.add(RestorePreflightBlocker.CANDIDATE_INVALID) 

110 if not inspection.application_readable: 110 ↛ 111line 110 didn't jump to line 111 because the condition on line 110 was never true

111 blockers.add(RestorePreflightBlocker.CANDIDATE_INVALID) 

112 elif inspection.application_work_pending: 112 ↛ 113line 112 didn't jump to line 113 because the condition on line 112 was never true

113 blockers.add(RestorePreflightBlocker.APPLICATION_WORK_PENDING) 

114 

115 manifest_accounts = _manifest_accounts(inspection.environment_ids) 

116 if set(inspection.account_member_ids) != set(manifest_accounts): 116 ↛ 117line 116 didn't jump to line 117 because the condition on line 116 was never true

117 blockers.add(RestorePreflightBlocker.ACCOUNT_SNAPSHOT_INCOMPLETE) 

118 if inspection.incomplete_account_ids: 118 ↛ 119line 118 didn't jump to line 119 because the condition on line 118 was never true

119 blockers.add(RestorePreflightBlocker.ACCOUNT_SNAPSHOT_INCOMPLETE) 

120 

121 supplied: dict[str, RestoreBrokerCredential] = {} 

122 for credential in credentials: 

123 if credential.account_id in supplied: 123 ↛ 124line 123 didn't jump to line 124 because the condition on line 123 was never true

124 blockers.add(RestorePreflightBlocker.ACCOUNT_IDENTITY_MISMATCH) 

125 supplied[credential.account_id] = credential 

126 if set(supplied) != set(manifest_accounts): 126 ↛ 127line 126 didn't jump to line 127 because the condition on line 126 was never true

127 blockers.add(RestorePreflightBlocker.ACCOUNT_IDENTITY_MISMATCH) 

128 if any( 128 ↛ 133line 128 didn't jump to line 133 because the condition on line 128 was never true

129 supplied[account_id].environment != environment 

130 for account_id, environment in manifest_accounts.items() 

131 if account_id in supplied 

132 ): 

133 blockers.add(RestorePreflightBlocker.ACCOUNT_IDENTITY_MISMATCH) 

134 

135 for account in inspection.accounts: 

136 credential = supplied.get(account.account_id) 

137 if account.pending_delivery: 137 ↛ 138line 137 didn't jump to line 138 because the condition on line 137 was never true

138 blockers.add(RestorePreflightBlocker.ACCOUNT_OUTBOX_PENDING) 

139 if ( 139 ↛ 146line 139 didn't jump to line 146 because the condition on line 139 was never true

140 credential is None 

141 or account.snapshot.environment != manifest_accounts.get(account.account_id) 

142 or account.snapshot.environment != credential.environment 

143 or account.snapshot.control.entry_permission != "disabled" 

144 or account.snapshot.control.recovery_preference != "manual" 

145 ): 

146 blockers.add(RestorePreflightBlocker.ACCOUNT_IDENTITY_MISMATCH) 

147 

148 if not blockers: 148 ↛ 172line 148 didn't jump to line 172 because the condition on line 148 was always true

149 for account in inspection.accounts: 

150 credential = supplied[account.account_id] 

151 broker = None 

152 try: 

153 broker = self._broker_factory(credential) 

154 evidence = broker.restore_evidence(account.snapshot, inspection.created_at) 

155 reconcile_restore_snapshot(account.snapshot, evidence) 

156 except RestoreReconciliationError: 

157 blockers.add(RestorePreflightBlocker.BROKER_STATE_MISMATCH) 

158 except Exception: # noqa: BLE001 - any failure blocks the restore candidate 

159 blockers.add(RestorePreflightBlocker.BROKER_EVIDENCE_UNAVAILABLE) 

160 finally: 

161 if broker is not None: 161 ↛ 166line 161 didn't jump to line 166 because the condition on line 161 was always true

162 try: 

163 broker.close() 

164 except Exception: # noqa: BLE001 - any failure blocks the restore candidate 

165 blockers.add(RestorePreflightBlocker.BROKER_EVIDENCE_UNAVAILABLE) 

166 if blockers: 166 ↛ 167line 166 didn't jump to line 167 because the condition on line 166 was never true

167 break 

168 checked_accounts += 1 

169 except Exception: # noqa: BLE001 - any failure blocks the restore candidate 

170 blockers.add(RestorePreflightBlocker.CANDIDATE_INVALID) 

171 

172 try: 

173 inspection_after = self._inspector.inspect_candidate(candidate_id) 

174 if ( 174 ↛ 179line 174 didn't jump to line 179 because the condition on line 174 was never true

175 inspection_after.candidate_id != candidate_id 

176 or inspection_after.candidate_manifest_sha256 

177 != inspection.candidate_manifest_sha256 

178 ): 

179 blockers.add(RestorePreflightBlocker.CANDIDATE_CHANGED) 

180 except Exception: # noqa: BLE001 - any failure blocks the restore candidate 

181 blockers.add(RestorePreflightBlocker.CANDIDATE_CHANGED) 

182 return self._result(candidate_id, checked_accounts, blockers) 

183 

184 @staticmethod 

185 def _result( 

186 candidate_id: str, 

187 checked_accounts: int, 

188 blockers: set[RestorePreflightBlocker], 

189 ) -> RestorePreflightResult: 

190 return RestorePreflightResult( 

191 candidate_id=candidate_id, 

192 checked_account_count=checked_accounts, 

193 blockers=tuple(sorted(blockers, key=lambda blocker: blocker.value)), 

194 ) 

195 

196 

197def _manifest_accounts(environment_ids: tuple[str, ...]) -> dict[str, str]: 

198 accounts: dict[str, str] = {} 

199 for identity in environment_ids: 

200 environment, separator, account_id = identity.partition(":") 

201 if not separator or environment not in {"paper", "live"} or not account_id: 201 ↛ 202line 201 didn't jump to line 202 because the condition on line 201 was never true

202 raise ValueError("restore account identity is invalid") 

203 if account_id in accounts: 203 ↛ 204line 203 didn't jump to line 204 because the condition on line 203 was never true

204 raise ValueError("restore account identity is duplicated") 

205 accounts[account_id] = environment 

206 return accounts