Coverage for src/copytrading_engine/trading/adapters/telemetry.py: 91%
70 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
1"""Private observations for explicitly activated trading work, recorded in the local journal."""
3import re
4import traceback
5from collections.abc import Generator, Iterable, Mapping
6from contextlib import AbstractContextManager, contextmanager
7from hashlib import sha256
9from copytrading_engine.diagnostics.redaction import MAX_DIAGNOSTIC_PAYLOAD_BYTES, JsonValue
10from copytrading_engine.diagnostics.telemetry.events import safe_ledger_event
11from copytrading_engine.diagnostics.telemetry.local import LocalTelemetry
12from copytrading_engine.shared.correlation import WorkflowAttempt, current_workflow_attempt
13from copytrading_engine.shared.payload_capture import CaptureKind, CaptureStatus, ProviderName
16class TradingTelemetry:
17 """Record finite operation outcomes without credentials, message text, or prompts."""
19 def __init__(self, *, sink: LocalTelemetry | None = None) -> None:
20 self._sink = sink
22 @contextmanager
23 def _scope(
24 self,
25 operation: str,
26 *,
27 signal_ref: str | None = None,
28 ledger_event: str | None = None,
29 correlation: WorkflowAttempt | None = None,
30 ) -> Generator[None]:
31 outcome = "returned"
32 try:
33 yield
34 except BaseException:
35 outcome = "raised"
36 raise
37 finally:
38 self._record(operation, outcome, signal_ref, ledger_event, correlation)
40 def span(self, name: str, message_id: str) -> AbstractContextManager[None]:
41 operation = (
42 name if name in {"risk_checks", "order_submission", "quote_snapshot"} else "unknown"
43 )
44 return self._scope(
45 f"execution.{operation}",
46 signal_ref=signal_reference(message_id),
47 correlation=current_workflow_attempt(),
48 )
50 def workflow_span(self, correlation: WorkflowAttempt) -> AbstractContextManager[None]:
51 return self._scope("workflow", correlation=correlation)
53 def model_span(self, message_id: str) -> AbstractContextManager[None]:
54 return self._scope(
55 "model.parse",
56 signal_ref=signal_reference(message_id),
57 correlation=current_workflow_attempt(),
58 )
60 def destination_span(
61 self, message_id: str, correlation: WorkflowAttempt
62 ) -> AbstractContextManager[None]:
63 return self._scope(
64 "destination.receive",
65 signal_ref=signal_reference(message_id),
66 correlation=correlation,
67 )
69 def source_span(self) -> AbstractContextManager[None]:
70 return self._scope("source.forward")
72 def event(self, name: str, facts: Mapping[str, object] | None = None) -> None:
73 """A ledger event, with the plain trading facts that say what it was about (the stock,
74 side, shares, prices, order status, skip reason); the journal keeps only those."""
75 self._record(
76 "execution.ledger_event",
77 "returned",
78 None,
79 safe_ledger_event(name),
80 current_workflow_attempt(),
81 facts,
82 )
84 def account_failed(self, error: BaseException) -> None:
85 """An account stopped on an error: the error's type and the engine function it was raised
86 in, so the journal says why without its message, which may carry broker or post text."""
87 frames = [frame for frame, _ in traceback.walk_tb(error.__traceback__)]
88 frame = frames[-1] if frames else None
89 self._record(
90 "account.failed",
91 "raised",
92 None,
93 None,
94 None,
95 {
96 "reason": _snake(type(error).__name__),
97 "status": frame.f_code.co_name.strip("_") if frame is not None else None,
98 },
99 )
101 def _record(
102 self,
103 operation: str,
104 outcome: str,
105 signal_ref: str | None,
106 ledger_event: str | None,
107 correlation: WorkflowAttempt | None,
108 facts: Mapping[str, object] | None = None,
109 ) -> None:
110 if self._sink is None:
111 return
112 try:
113 self._sink.record_trading_operation(
114 operation=operation,
115 outcome="observed" if ledger_event is not None else outcome,
116 trace_id=correlation.trace_id.replace("-", "") if correlation else None,
117 signal_ref=signal_ref,
118 ledger_event=ledger_event,
119 workflow_id=correlation.workflow_id if correlation else None,
120 destination_id=correlation.destination_id if correlation else None,
121 attempt=correlation.attempt if correlation else None,
122 facts=facts,
123 )
124 except Exception: # noqa: BLE001 - observer failure must not reach trading
125 self._report_observer_failure()
127 def _report_observer_failure(self) -> None:
128 if self._sink is not None: 128 ↛ exitline 128 didn't return from function '_report_observer_failure' because the condition on line 128 was always true
129 try:
130 self._sink.report_trading_observer_failure()
131 except Exception: # noqa: BLE001 - observer failure must not reach trading
132 pass
134 @property
135 def diagnostic_sink(self) -> LocalTelemetry | None:
136 """Expose the capture port for provider/source adapters without coupling them here."""
137 return self._sink
139 def register_secrets(self, values: Iterable[str]) -> bool:
140 """Register runtime credentials before source or provider work can emit diagnostics."""
141 if self._sink is None:
142 return True
143 return self._sink.register_secrets(values)
145 def record_payload(
146 self,
147 *,
148 capture_kind: CaptureKind,
149 workflow_id: str | None,
150 trace_id: str | None,
151 destination_id: str | None,
152 attempt: int | None,
153 provider: ProviderName,
154 payload: JsonValue | None,
155 source_bytes: int | None = None,
156 max_bytes: int = MAX_DIAGNOSTIC_PAYLOAD_BYTES,
157 status: CaptureStatus = "complete",
158 ) -> None:
159 if self._sink is None: 159 ↛ 160line 159 didn't jump to line 160 because the condition on line 159 was never true
160 return
161 try:
162 self._sink.record_payload(
163 capture_kind=capture_kind,
164 workflow_id=workflow_id,
165 trace_id=trace_id,
166 destination_id=destination_id,
167 attempt=attempt,
168 provider=provider,
169 payload=payload,
170 source_bytes=source_bytes,
171 max_bytes=max_bytes,
172 status=status,
173 )
174 except Exception: # noqa: BLE001 - observer failure must not reach trading
175 self._report_observer_failure()
178def signal_reference(message_id: str) -> str:
179 return sha256(message_id.encode("utf-8", errors="replace")).hexdigest()[:32]
182def _snake(name: str) -> str:
183 """ "OperationalError" becomes "operational_error"."""
184 return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()