Coverage for src/copytrading_engine/control/proposals.py: 99%

152 statements  

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

1"""Owner-approved proposals: what an agent asked for, and whether it may run. 

2 

3A proposal is created by an agent and performed only after the owner approves the exact 

4content they saw. Approval is accepted once, while the proposal is pending, before it 

5expires, and only with the digest of that content. Proposals live in memory: they last 

6minutes and end with the app's lock; durable facts belong to the audit trail and ledger. 

7""" 

8 

9import datetime as dt 

10import hashlib 

11import json 

12import secrets 

13from collections import deque 

14from collections.abc import Callable 

15from dataclasses import asdict, dataclass, replace 

16from decimal import Decimal 

17from typing import Final, Literal 

18from uuid import uuid4 

19 

20from copytrading_engine.control.wire import ErrorCode, RecoveryPreference 

21 

22PROPOSAL_LIFETIME: Final = dt.timedelta(minutes=5) 

23REJECTION_LIMIT: Final = 3 

24REJECTION_WINDOW: Final = dt.timedelta(minutes=10) 

25COOLDOWN: Final = dt.timedelta(minutes=10) 

26RETENTION: Final = dt.timedelta(hours=1) 

27 

28 

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

30class ResumeAccount: 

31 account_id: str 

32 

33 

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

35class SetRecovery: 

36 account_id: str 

37 preference: RecoveryPreference 

38 

39 

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

41class ConfirmManualOrder: 

42 account_id: str 

43 preview_id: str 

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

45 symbol: str 

46 side: Literal["buy", "sell"] 

47 order_type: Literal["limit", "market", "stop"] 

48 quantity: Decimal 

49 limit_price: Decimal | None 

50 

51 

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

53class SetAccountLimits: 

54 """New values for some of an account's settings, each as the text the agent sent. The app 

55 applies them over the setup it has saved; nothing else about the setup can change.""" 

56 

57 account_id: str 

58 changes: tuple[tuple[str, str], ...] 

59 

60 

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

62class StartProcessing: 

63 """Start copying the saved setup; the app runs its own Start Copying checks and start.""" 

64 

65 

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

67class ApplySetup: 

68 """Check, save and start the app's unsaved setup, which touches these live accounts. The app 

69 keeps the setup itself, keys included, and applies only the one the owner was shown.""" 

70 

71 made_live: tuple[str, ...] 

72 new_live_keys: tuple[str, ...] 

73 changed_live: tuple[str, ...] 

74 starts_live: tuple[str, ...] 

75 

76 

77type Subject = ( 

78 ResumeAccount 

79 | SetRecovery 

80 | ConfirmManualOrder 

81 | SetAccountLimits 

82 | StartProcessing 

83 | ApplySetup 

84) 

85type Kind = Literal[ 

86 "resume_account", 

87 "set_recovery", 

88 "confirm_manual_order", 

89 "set_account_limits", 

90 "start_processing", 

91 "apply_setup", 

92] 

93 

94# Kinds only the app can perform, because the setup file and its keys are the app's. Approving 

95# one leaves it running until the app reports how it went. 

96APP_PERFORMED: Final[frozenset[Kind]] = frozenset( 

97 {"set_recovery", "set_account_limits", "start_processing", "apply_setup"} 

98) 

99# How long the app has to report before the outcome is called unknown: applying a setup runs 

100# every connection check, may pause copying first, and asks for Touch ID for a live account. 

101APP_REPORT_WINDOW: Final = dt.timedelta(minutes=5) 

102type Outcome = Literal["succeeded", "failed", "outcome_unknown"] 

103 

104 

105def kind_of(subject: Subject) -> Kind: 

106 match subject: 

107 case ResumeAccount(): 

108 return "resume_account" 

109 case SetRecovery(): 

110 return "set_recovery" 

111 case ConfirmManualOrder(): 

112 return "confirm_manual_order" 

113 case SetAccountLimits(): 

114 return "set_account_limits" 

115 case StartProcessing(): 

116 return "start_processing" 

117 case ApplySetup(): 117 ↛ exitline 117 didn't return from function 'kind_of' because the pattern on line 117 always matched

118 return "apply_setup" 

119 

120 

121def digest(subject: Subject) -> str: 

122 """A stable fingerprint of exactly what the owner is asked to approve.""" 

123 content = {"kind": kind_of(subject), **asdict(subject)} 

124 encoded = json.dumps(content, sort_keys=True, separators=(",", ":"), default=str) 

125 return hashlib.sha256(encoded.encode()).hexdigest() 

126 

127 

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

129class Caller: 

130 pid: int | None 

131 path: str | None 

132 

133 

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

135class Pending: 

136 pass 

137 

138 

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

140class Running: 

141 approved_at: dt.datetime 

142 

143 

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

145class Finished: 

146 result: Outcome 

147 code: str | None 

148 finished_at: dt.datetime 

149 

150 

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

152class Closed: 

153 reason: Literal["rejected", "expired", "discarded"] 

154 closed_at: dt.datetime 

155 

156 

157type State = Pending | Running | Finished | Closed 

158 

159 

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

161class Proposal: 

162 proposal_id: str 

163 subject: Subject 

164 digest: str 

165 command_id: str 

166 caller: Caller 

167 created_at: dt.datetime 

168 expires_at: dt.datetime 

169 state: State 

170 

171 @property 

172 def kind(self) -> Kind: 

173 return kind_of(self.subject) 

174 

175 

176class ProposalRefused(Exception): 

177 """A proposal cannot be created or advanced; `code` says why.""" 

178 

179 def __init__(self, code: ErrorCode) -> None: 

180 super().__init__(code) 

181 self.code: ErrorCode = code 

182 

183 

184class ProposalBook: 

185 """Hold proposals and enforce their limits; every transition is synchronous.""" 

186 

187 def __init__( 

188 self, 

189 clock: Callable[[], dt.datetime], 

190 *, 

191 lifetime: dt.timedelta = PROPOSAL_LIFETIME, 

192 rejection_limit: int = REJECTION_LIMIT, 

193 rejection_window: dt.timedelta = REJECTION_WINDOW, 

194 cooldown: dt.timedelta = COOLDOWN, 

195 ) -> None: 

196 self._clock = clock 

197 self._lifetime = lifetime 

198 self._rejection_limit = rejection_limit 

199 self._rejection_window = rejection_window 

200 self._cooldown = cooldown 

201 self._proposals: dict[str, Proposal] = {} 

202 self._rejections: deque[dt.datetime] = deque() 

203 self._cooling_until: dt.datetime | None = None 

204 

205 def propose( 

206 self, 

207 subject: Subject, 

208 caller: Caller, 

209 *, 

210 expires_by: dt.datetime | None = None, 

211 ) -> Proposal: 

212 now = self._clock() 

213 self._expire(now) 

214 if self._cooling_until is not None and now < self._cooling_until: 

215 raise ProposalRefused("cooling_down") 

216 kind = kind_of(subject) 

217 if any( 

218 item.kind == kind and isinstance(item.state, Pending) 

219 for item in self._proposals.values() 

220 ): 

221 raise ProposalRefused("proposal_limit") 

222 expires_at = now + self._lifetime 

223 if expires_by is not None: 

224 expires_at = min(expires_at, expires_by) 

225 if expires_at <= now: 

226 raise ProposalRefused("expired") 

227 proposal = Proposal( 

228 proposal_id=f"p-{secrets.token_hex(6)}", 

229 subject=subject, 

230 digest=digest(subject), 

231 command_id=f"agent-{uuid4().hex}", 

232 caller=caller, 

233 created_at=now, 

234 expires_at=expires_at, 

235 state=Pending(), 

236 ) 

237 self._proposals[proposal.proposal_id] = proposal 

238 return proposal 

239 

240 def get(self, proposal_id: str) -> Proposal: 

241 self._expire(self._clock()) 

242 try: 

243 return self._proposals[proposal_id] 

244 except KeyError: 

245 raise ProposalRefused("not_found") from None 

246 

247 def all(self) -> tuple[Proposal, ...]: 

248 self._expire(self._clock()) 

249 return tuple(sorted(self._proposals.values(), key=lambda item: item.created_at)) 

250 

251 def pending(self) -> tuple[Proposal, ...]: 

252 return tuple(item for item in self.all() if isinstance(item.state, Pending)) 

253 

254 def begin(self, proposal_id: str, approved_digest: str) -> Proposal: 

255 """Accept the owner's approval once; the caller then performs the action.""" 

256 proposal = self.get(proposal_id) 

257 if isinstance(proposal.state, Closed) and proposal.state.reason == "expired": 

258 raise ProposalRefused("expired") 

259 if not isinstance(proposal.state, Pending): 

260 raise ProposalRefused("conflict") 

261 if approved_digest != proposal.digest: 

262 raise ProposalRefused("conflict") 

263 return self._store(replace(proposal, state=Running(self._clock()))) 

264 

265 def finish( 

266 self, 

267 proposal_id: str, 

268 result: Outcome, 

269 code: str | None = None, 

270 ) -> Proposal: 

271 proposal = self._proposals[proposal_id] 

272 if not isinstance(proposal.state, Running): 

273 raise ProposalRefused("conflict") 

274 return self._store(replace(proposal, state=Finished(result, code, self._clock()))) 

275 

276 def reject(self, proposal_id: str) -> Proposal: 

277 proposal = self.get(proposal_id) 

278 if not isinstance(proposal.state, Pending): 

279 raise ProposalRefused("conflict") 

280 now = self._clock() 

281 while self._rejections and now - self._rejections[0] >= self._rejection_window: 

282 self._rejections.popleft() 

283 self._rejections.append(now) 

284 if len(self._rejections) >= self._rejection_limit: 

285 self._cooling_until = now + self._cooldown 

286 self._rejections.clear() 

287 return self._store(replace(proposal, state=Closed("rejected", now))) 

288 

289 def discard_pending(self) -> int: 

290 """Close every waiting proposal, as when the app locks or quits.""" 

291 now = self._clock() 

292 waiting = [item for item in self._proposals.values() if isinstance(item.state, Pending)] 

293 for item in waiting: 

294 self._store(replace(item, state=Closed("discarded", now))) 

295 return len(waiting) 

296 

297 def _expire(self, now: dt.datetime) -> None: 

298 for item in list(self._proposals.values()): 

299 if isinstance(item.state, Pending) and now >= item.expires_at: 

300 self._store(replace(item, state=Closed("expired", now))) 

301 elif ( 

302 isinstance(item.state, Running) 

303 and item.kind in APP_PERFORMED 

304 and now - item.state.approved_at >= APP_REPORT_WINDOW 

305 ): 

306 self._store( 

307 replace( 

308 item, 

309 state=Finished("outcome_unknown", "app_did_not_report", now), 

310 ) 

311 ) 

312 elif isinstance(item.state, Finished | Closed) and now - item.created_at > RETENTION: 

313 del self._proposals[item.proposal_id] 

314 

315 def _store(self, proposal: Proposal) -> Proposal: 

316 self._proposals[proposal.proposal_id] = proposal 

317 return proposal