Coverage for src/copytrading_engine/diagnostics/capture.py: 75%

89 statements  

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

1"""Caller-owned diagnostics ports and workflow/store composition.""" 

2 

3from collections.abc import Callable 

4from dataclasses import dataclass 

5from typing import Literal, Protocol 

6 

7from copytrading_engine.host.self_test.model import ( 

8 DestinationOutcome, 

9 ParsedSelfTest, 

10 ParseRejected, 

11 Stage, 

12 SubmitSelfTest, 

13 WorkflowAcceptance, 

14 WorkflowView, 

15) 

16from copytrading_engine.host.self_test.ports import WorkflowStore 

17from copytrading_engine.host.status import ( 

18 DiagnosticCaptureProjection, 

19 EngineQueries, 

20 EngineState, 

21 EngineStatus, 

22 TelemetryState, 

23) 

24 

25type DiagnosticState = Literal["healthy", "degraded"] 

26type JsonScalar = bool | int | float | str | None 

27type JsonValue = JsonScalar | list[JsonValue] | dict[str, JsonValue] 

28 

29 

30@dataclass(frozen=True) 

31class DiagnosticHealth: 

32 state: DiagnosticState 

33 dropped_records: int 

34 last_error_code: str | None 

35 

36 

37@dataclass(frozen=True) 

38class DiagnosticCaptureHealth: 

39 """How many source and model payloads reached the journal, and how many were gaps.""" 

40 

41 source_events: int 

42 source_event_gaps: int 

43 model_requests: int 

44 model_request_gaps: int 

45 model_responses: int 

46 model_response_gaps: int 

47 

48 

49class DiagnosticSink(Protocol): 

50 """Caller-owned diagnostics interface used after durable workflow changes.""" 

51 

52 def record_stage( 

53 self, 

54 *, 

55 command_id: str, 

56 trace_id: str, 

57 stage: Stage, 

58 outcome: str, 

59 payload: JsonValue, 

60 previous_stage: Stage | None = None, 

61 anchor_exported: bool | None = None, 

62 ) -> None: ... 

63 

64 def snapshot(self) -> DiagnosticHealth: ... 

65 

66 def capture_health(self) -> DiagnosticCaptureHealth: ... 

67 

68 def set_anchor_export_callback(self, callback: Callable[[str], None]) -> None: ... 

69 

70 

71class DiagnosticWorkflowStore: 

72 """Decorate committed workflow changes with best-effort diagnostic records.""" 

73 

74 def __init__(self, store: WorkflowStore, sink: DiagnosticSink) -> None: 

75 self._store = store 

76 self._sink = sink 

77 self._sink.set_anchor_export_callback(self._store.mark_trace_anchor_exported) 

78 

79 async def accept_async(self, command: SubmitSelfTest) -> WorkflowAcceptance: 

80 acceptance = await self._store.accept_async(command) 

81 workflow = acceptance.workflow 

82 if acceptance.newly_accepted: 

83 self._record( 

84 workflow, 

85 stage=Stage.CAPTURED, 

86 outcome="accepted", 

87 anchor_exported=False, 

88 payload={ 

89 "request": { 

90 "command_id": command.command_id, 

91 "text": command.text, 

92 "destination_ids": list(command.destination_ids), 

93 }, 

94 "response": { 

95 "command_id": workflow.command_id, 

96 "stage": workflow.stage.value, 

97 }, 

98 }, 

99 ) 

100 return acceptance 

101 

102 async def get_async(self, command_id: str) -> WorkflowView: 

103 return await self._store.get_async(command_id) 

104 

105 async def pending_async(self, limit: int | None = None) -> tuple[str, ...]: 

106 return await self._store.pending_async(limit=limit) 

107 

108 async def advance_async( 

109 self, 

110 command_id: str, 

111 expected: Stage, 

112 next_stage: Stage, 

113 outcomes: tuple[DestinationOutcome, ...], 

114 *, 

115 parsed: ParsedSelfTest | None = None, 

116 parse_rejection: ParseRejected | None = None, 

117 ) -> WorkflowView: 

118 try: 

119 workflow = await self._store.advance_async( 

120 command_id, 

121 expected, 

122 next_stage, 

123 outcomes, 

124 parsed=parsed, 

125 parse_rejection=parse_rejection, 

126 ) 

127 except Exception as exc: 

128 await self._record_error(command_id, expected, exc) 

129 raise 

130 

131 anchor_exported = await self._anchor_exported(workflow.command_id) 

132 

133 payload: dict[str, JsonValue] = { 

134 "response": { 

135 "command_id": workflow.command_id, 

136 "stage": workflow.stage.value, 

137 "outcomes": [ 

138 {"account_id": outcome.account_id, "result": outcome.result} 

139 for outcome in workflow.outcomes 

140 ], 

141 } 

142 } 

143 if parsed is not None: 

144 payload["parsed"] = { 

145 "symbol": parsed.symbol, 

146 "action": parsed.action, 

147 "quantity": str(parsed.quantity), 

148 "unit_price": str(parsed.unit_price), 

149 } 

150 if parse_rejection is not None: 150 ↛ 151line 150 didn't jump to line 151 because the condition on line 150 was never true

151 payload["error"] = {"code": parse_rejection.reason} 

152 self._record( 

153 workflow, 

154 stage=next_stage, 

155 outcome=next_stage.value, 

156 previous_stage=expected, 

157 anchor_exported=anchor_exported, 

158 payload=payload, 

159 ) 

160 return workflow 

161 

162 async def load_command_async(self, command_id: str) -> SubmitSelfTest: 

163 return await self._store.load_command_async(command_id) 

164 

165 async def load_parsed_async(self, command_id: str) -> ParsedSelfTest: 

166 return await self._store.load_parsed_async(command_id) 

167 

168 async def counts_async(self) -> tuple[int, int, int]: 

169 return await self._store.counts_async() 

170 

171 async def trace_anchor_exported_async(self, command_id: str) -> bool: 

172 return await self._store.trace_anchor_exported_async(command_id) 

173 

174 def mark_trace_anchor_exported(self, command_id: str) -> None: 

175 self._store.mark_trace_anchor_exported(command_id) 

176 

177 def _record( 

178 self, 

179 workflow: WorkflowView, 

180 *, 

181 stage: Stage, 

182 outcome: str, 

183 payload: JsonValue, 

184 previous_stage: Stage | None = None, 

185 anchor_exported: bool | None = None, 

186 ) -> None: 

187 try: 

188 self._sink.record_stage( 

189 command_id=workflow.command_id, 

190 trace_id=workflow.trace_id, 

191 stage=stage, 

192 outcome=outcome, 

193 payload=payload, 

194 previous_stage=previous_stage, 

195 anchor_exported=anchor_exported, 

196 ) 

197 except Exception: # noqa: BLE001 - diagnostics must not alter the operational result 

198 # Diagnostics are a best-effort side effect after the store commit. 

199 pass 

200 

201 async def _record_error(self, command_id: str, stage: Stage, error: Exception) -> None: 

202 try: 

203 workflow = await self._store.get_async(command_id) 

204 except Exception: # noqa: BLE001 - diagnostics must not alter the operational result 

205 return 

206 anchor_exported = await self._anchor_exported(command_id) 

207 self._record( 

208 workflow, 

209 stage=stage, 

210 outcome="error", 

211 previous_stage=stage, 

212 anchor_exported=anchor_exported, 

213 payload={"error": {"code": _error_code(error)}}, 

214 ) 

215 

216 async def _anchor_exported(self, command_id: str) -> bool | None: 

217 try: 

218 return await self._store.trace_anchor_exported_async(command_id) 

219 except Exception: # noqa: BLE001 - diagnostics must not alter the operational result 

220 return None 

221 

222 

223class DiagnosticEngineQueries(EngineQueries): 

224 """Expose journal health without letting a diagnostics failure break status.""" 

225 

226 def __init__(self, store: WorkflowStore, instance_id: str, sink: DiagnosticSink) -> None: 

227 super().__init__(store, instance_id) 

228 self._sink = sink 

229 

230 async def status( 

231 self, 

232 state: EngineState, 

233 *, 

234 telemetry_state: TelemetryState = "degraded", 

235 telemetry_dropped: int = 0, 

236 telemetry_error_code: str | None = None, 

237 diagnostic_capture: DiagnosticCaptureProjection | None = None, 

238 ) -> EngineStatus: 

239 try: 

240 health = self._sink.snapshot() 

241 except Exception: # noqa: BLE001 - diagnostics must not alter the operational result 

242 health = DiagnosticHealth( 

243 telemetry_state, 

244 telemetry_dropped, 

245 telemetry_error_code or "health_unavailable", 

246 ) 

247 capture = diagnostic_capture or DiagnosticCaptureProjection() 

248 try: 

249 observed = self._sink.capture_health() 

250 capture = DiagnosticCaptureProjection( 

251 source_events=observed.source_events, 

252 source_event_gaps=observed.source_event_gaps, 

253 model_requests=observed.model_requests, 

254 model_request_gaps=observed.model_request_gaps, 

255 model_responses=observed.model_responses, 

256 model_response_gaps=observed.model_response_gaps, 

257 ) 

258 except Exception: # noqa: BLE001 - diagnostics must not alter the operational result 

259 health = DiagnosticHealth("degraded", health.dropped_records, "health_unavailable") 

260 return await super().status( 

261 state, 

262 telemetry_state=health.state, 

263 telemetry_dropped=health.dropped_records, 

264 telemetry_error_code=health.last_error_code, 

265 diagnostic_capture=capture, 

266 ) 

267 

268 

269def _error_code(error: Exception) -> str: 

270 name = type(error).__name__ 

271 return { 

272 "StoreUnavailable": "store_unavailable", 

273 "IdentityConflict": "identity_conflict", 

274 "InvalidTransition": "invalid_transition", 

275 "WorkflowNotFound": "not_found", 

276 }.get(name, "stage_transition_failed")