multi-agent-observability 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of multi-agent-observability might be problematic. Click here for more details.

ma_trace/replay.py ADDED
@@ -0,0 +1,398 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Deterministic replay of recorded episodes.
3
+
4
+ Replay re-runs the workflow's entrypoint with the episode's seed while every
5
+ recorded LLM/tool call is served from the episode instead of being executed.
6
+ Environment contracts are verified against their recorded pre/post-state hashes.
7
+ Any difference between the live run and the recording is reported as a
8
+ :class:`Divergence`; a replay with no divergences is *deterministic*.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import importlib
15
+ import inspect
16
+ import time
17
+ from collections import deque
18
+ from collections.abc import Callable
19
+ from dataclasses import asdict, dataclass, field
20
+ from typing import TYPE_CHECKING, Any
21
+
22
+ from .context import _current_replay
23
+ from .contracts import Contract, ContractCheck
24
+ from .episode import Episode
25
+ from .events import CallEvent, ContractEvent
26
+
27
+ if TYPE_CHECKING: # pragma: no cover
28
+ from .tracer import MATrace
29
+
30
+
31
+ class ReplayError(RuntimeError):
32
+ """Replay could not be started (missing entrypoint, unknown episode, ...)."""
33
+
34
+
35
+ @dataclass
36
+ class Divergence:
37
+ """One difference between the live run and the recording.
38
+
39
+ ``kind`` is one of ``input_mismatch``, ``unexpected_call``, ``missing_call``,
40
+ ``output_unavailable``, ``unexpected_contract``, ``missing_contract``,
41
+ ``contract_pre_mismatch``, ``contract_post_mismatch``, ``action_sequence_mismatch``,
42
+ ``coordination_mismatch`` or ``error``.
43
+ """
44
+
45
+ kind: str
46
+ agent: str | None = None
47
+ name: str | None = None
48
+ index: int | None = None
49
+ expected: str | None = None
50
+ actual: str | None = None
51
+ detail: str | None = None
52
+
53
+ def describe(self) -> str:
54
+ where = " ".join(p for p in (self.agent, self.name) if p)
55
+ parts = [self.kind, where]
56
+ if self.expected or self.actual:
57
+ parts.append(f"expected={_short(self.expected)} actual={_short(self.actual)}")
58
+ if self.detail:
59
+ parts.append(self.detail)
60
+ return " ".join(p for p in parts if p)
61
+
62
+
63
+ class ReplayDivergenceError(ReplayError):
64
+ def __init__(self, divergence: Divergence) -> None:
65
+ super().__init__(divergence.describe())
66
+ self.divergence = divergence
67
+
68
+
69
+ def _short(h: str | None) -> str:
70
+ if not h:
71
+ return "-"
72
+ return h[:12] if len(h) > 16 else h
73
+
74
+
75
+ class ReplaySession:
76
+ """Serves recorded calls and contracts to the tracer during a replay."""
77
+
78
+ def __init__(self, recorded: Episode, *, strict: bool = False) -> None:
79
+ self.recorded = recorded
80
+ self.strict = strict
81
+ self.divergences: list[Divergence] = []
82
+ self.matched_calls = 0
83
+ self.executed_live = 0
84
+ self.contracts_checked = 0
85
+ self.contracts_passed = 0
86
+ self._calls: dict[tuple[str | None, str, str], deque[CallEvent]] = {}
87
+ for c in sorted(recorded.calls, key=lambda e: e.seq):
88
+ self._calls.setdefault((c.agent, c.call_type.value, c.name), deque()).append(c)
89
+ self._contracts: dict[tuple[str | None, str], deque[ContractEvent]] = {}
90
+ for ce in sorted(recorded.contract_events, key=lambda e: e.seq):
91
+ self._contracts.setdefault((ce.agent, ce.action), deque()).append(ce)
92
+
93
+ # -- calls ----------------------------------------------------------------
94
+
95
+ def consume_call(self, live: CallEvent) -> tuple[CallEvent | None, Divergence | None]:
96
+ key = (live.agent, live.call_type.value, live.name)
97
+ queue = self._calls.get(key)
98
+ if not queue:
99
+ self.executed_live += 1
100
+ return None, Divergence(
101
+ "unexpected_call",
102
+ live.agent,
103
+ live.name,
104
+ live.index,
105
+ detail="no recorded call left for this agent/name",
106
+ )
107
+ rec = queue.popleft()
108
+ self.matched_calls += 1
109
+ if (
110
+ rec.input_fingerprint
111
+ and live.input_fingerprint
112
+ and rec.input_fingerprint != live.input_fingerprint
113
+ ):
114
+ return rec, Divergence(
115
+ "input_mismatch",
116
+ live.agent,
117
+ live.name,
118
+ rec.index,
119
+ rec.input_fingerprint,
120
+ live.input_fingerprint,
121
+ )
122
+ return rec, None
123
+
124
+ def report_output_unavailable(self, rec: CallEvent) -> None:
125
+ self.executed_live += 1
126
+ self.report(
127
+ Divergence(
128
+ "output_unavailable",
129
+ rec.agent,
130
+ rec.name,
131
+ rec.index,
132
+ detail="recorded output was not JSON-serialisable; executing live",
133
+ )
134
+ )
135
+
136
+ # -- contracts ------------------------------------------------------------
137
+
138
+ def consume_contract(self, live: Contract) -> tuple[ContractEvent | None, Divergence | None]:
139
+ key = (live.agent, live.action)
140
+ queue = self._contracts.get(key)
141
+ if not queue:
142
+ return None, Divergence(
143
+ "unexpected_contract",
144
+ live.agent,
145
+ live.action,
146
+ detail="no recorded contract left for this agent/action",
147
+ )
148
+ rec = queue.popleft()
149
+ self.contracts_checked += 1
150
+ if rec.pre_hash != live.pre_hash:
151
+ return rec, Divergence(
152
+ "contract_pre_mismatch", live.agent, live.action, None, rec.pre_hash, live.pre_hash
153
+ )
154
+ return rec, None
155
+
156
+ def report_contract_mismatch(self, live: Contract, check: ContractCheck) -> None:
157
+ if check.post_match is False:
158
+ self.report(
159
+ Divergence(
160
+ "contract_post_mismatch",
161
+ live.agent,
162
+ live.action,
163
+ None,
164
+ check.recorded_post,
165
+ check.actual_post,
166
+ )
167
+ )
168
+
169
+ # -- bookkeeping ----------------------------------------------------------
170
+
171
+ def report(self, divergence: Divergence) -> None:
172
+ self.divergences.append(divergence)
173
+ if self.strict:
174
+ raise ReplayDivergenceError(divergence)
175
+
176
+ def finish(self) -> None:
177
+ for (agent, _ctype, name), queue in self._calls.items():
178
+ for rec in queue:
179
+ self.divergences.append(
180
+ Divergence(
181
+ "missing_call",
182
+ agent,
183
+ name,
184
+ rec.index,
185
+ detail="recorded call was never made during replay",
186
+ )
187
+ )
188
+ for (agent, action), cqueue in self._contracts.items():
189
+ for _rec in cqueue:
190
+ self.divergences.append(
191
+ Divergence(
192
+ "missing_contract",
193
+ agent,
194
+ action,
195
+ detail="recorded contract was never opened during replay",
196
+ )
197
+ )
198
+ if self.strict and self.divergences:
199
+ raise ReplayDivergenceError(self.divergences[0])
200
+
201
+ @property
202
+ def deterministic(self) -> bool:
203
+ return not self.divergences
204
+
205
+
206
+ @dataclass
207
+ class ReplayReport:
208
+ recorded_episode_id: str
209
+ replay_episode_id: str | None
210
+ entrypoint: str | None
211
+ deterministic: bool
212
+ matched_calls: int
213
+ executed_live: int
214
+ contracts_checked: int
215
+ contracts_passed: int
216
+ divergences: list[Divergence] = field(default_factory=list)
217
+ recorded_metrics: dict[str, Any] = field(default_factory=dict)
218
+ replayed_metrics: dict[str, Any] = field(default_factory=dict)
219
+ duration_s: float = 0.0
220
+ error: str | None = None
221
+ result: Any = field(default=None, repr=False)
222
+
223
+ def to_dict(self) -> dict[str, Any]:
224
+ d = asdict(self)
225
+ d.pop("result", None)
226
+ return d
227
+
228
+ def summary(self) -> str:
229
+ status = "DETERMINISTIC" if self.deterministic else f"{len(self.divergences)} DIVERGENCE(S)"
230
+ lines = [
231
+ f"replay of {self.recorded_episode_id} -> {self.replay_episode_id}: {status}",
232
+ f" entrypoint : {self.entrypoint}",
233
+ f" calls replayed : {self.matched_calls} (executed live: {self.executed_live})",
234
+ f" contracts checked : {self.contracts_checked} (passed: {self.contracts_passed})",
235
+ f" duration : {self.duration_s:.3f}s",
236
+ ]
237
+ if self.error:
238
+ lines.append(f" error : {self.error}")
239
+ for key in ("coordination_overhead", "redundant_action_rate", "oscillation_rate", "memory_hit_ratio"):
240
+ a = self.recorded_metrics.get(key)
241
+ b = self.replayed_metrics.get(key)
242
+ if a is not None and b is not None:
243
+ lines.append(f" {key:<18}: recorded={a:.3f} replayed={b:.3f}")
244
+ for d in self.divergences:
245
+ lines.append(f" ! {d.describe()}")
246
+ return "\n".join(lines)
247
+
248
+
249
+ def structural_divergences(recorded: Episode, replayed: Episode) -> list[Divergence]:
250
+ """Compare the action sequence and the coordination-edge sequence of two episodes."""
251
+ out: list[Divergence] = []
252
+ rec_actions = [(a.agent, a.name, a.args_fingerprint) for a in recorded.actions]
253
+ rep_actions = [(a.agent, a.name, a.args_fingerprint) for a in replayed.actions]
254
+ if rec_actions != rep_actions:
255
+ idx = _first_difference(rec_actions, rep_actions)
256
+ at = rec_actions[idx] if idx < len(rec_actions) else rep_actions[idx]
257
+ out.append(
258
+ Divergence(
259
+ "action_sequence_mismatch",
260
+ agent=at[0],
261
+ name=at[1],
262
+ index=idx,
263
+ expected=f"{len(rec_actions)} actions",
264
+ actual=f"{len(rep_actions)} actions",
265
+ detail=f"first difference at action #{idx}",
266
+ )
267
+ )
268
+ rec_edges = [(e.source, e.target, e.kind.value) for e in recorded.coordination_events]
269
+ rep_edges = [(e.source, e.target, e.kind.value) for e in replayed.coordination_events]
270
+ if rec_edges != rep_edges:
271
+ idx = _first_difference(rec_edges, rep_edges)
272
+ at = rec_edges[idx] if idx < len(rec_edges) else rep_edges[idx]
273
+ out.append(
274
+ Divergence(
275
+ "coordination_mismatch",
276
+ agent=at[0],
277
+ name=f"{at[0]}->{at[1]}",
278
+ index=idx,
279
+ expected=f"{len(rec_edges)} edges",
280
+ actual=f"{len(rep_edges)} edges",
281
+ detail=f"first difference at edge #{idx}",
282
+ )
283
+ )
284
+ return out
285
+
286
+
287
+ def _first_difference(a: list[Any], b: list[Any]) -> int:
288
+ for i, (x, y) in enumerate(zip(a, b)):
289
+ if x != y:
290
+ return i
291
+ return min(len(a), len(b))
292
+
293
+
294
+ def resolve_entrypoint(spec: str | Callable[..., Any] | None) -> Callable[..., Any]:
295
+ if spec is None:
296
+ raise ReplayError("no entrypoint: pass one to replay() or record the episode with entrypoint=...")
297
+ if callable(spec):
298
+ return spec
299
+ if ":" not in spec:
300
+ raise ReplayError(f"entrypoint must look like 'package.module:function', got {spec!r}")
301
+ module_name, _, attr = spec.partition(":")
302
+ try:
303
+ module = importlib.import_module(module_name)
304
+ except ImportError as e:
305
+ raise ReplayError(f"cannot import {module_name!r}: {e}") from e
306
+ target: Any = module
307
+ for part in attr.split("."):
308
+ try:
309
+ target = getattr(target, part)
310
+ except AttributeError as e:
311
+ raise ReplayError(f"{spec!r} not found") from e
312
+ if not callable(target):
313
+ raise ReplayError(f"{spec!r} is not callable")
314
+ return target
315
+
316
+
317
+ def run_replay(
318
+ tracer: MATrace,
319
+ episode: Episode | str,
320
+ entrypoint: str | Callable[..., Any] | None = None,
321
+ *,
322
+ strict: bool = False,
323
+ entrypoint_args: dict[str, Any] | None = None,
324
+ ) -> ReplayReport:
325
+ """Replay ``episode`` (an :class:`Episode` or a store reference) with ``tracer``.
326
+
327
+ The entrypoint is called with ``entrypoint_args`` (default: the arguments recorded
328
+ with the episode). With ``strict=True`` the first divergence raises
329
+ :class:`ReplayDivergenceError`; otherwise all divergences are collected in the report.
330
+ """
331
+ if isinstance(episode, str):
332
+ if tracer.store is None:
333
+ raise ReplayError("tracer has no episode store; pass an Episode object")
334
+ try:
335
+ recorded = tracer.store.load(episode)
336
+ except KeyError as e:
337
+ raise ReplayError(str(e)) from e
338
+ else:
339
+ recorded = episode
340
+ fn = resolve_entrypoint(entrypoint or recorded.entrypoint)
341
+ args = dict(recorded.entrypoint_args if entrypoint_args is None else entrypoint_args)
342
+ session = ReplaySession(recorded, strict=strict)
343
+ token = _current_replay.set(session)
344
+ start = time.perf_counter()
345
+ error: str | None = None
346
+ result: Any = None
347
+ replay_ep: Episode | None = None
348
+ try:
349
+ with tracer.episode(
350
+ f"replay:{recorded.name}",
351
+ seed=recorded.seed,
352
+ entrypoint=recorded.entrypoint,
353
+ entrypoint_args=args,
354
+ attributes={"replay_of": recorded.id},
355
+ record=True,
356
+ replay_of=recorded.id,
357
+ ) as ep:
358
+ replay_ep = ep
359
+ try:
360
+ if inspect.iscoroutinefunction(fn):
361
+ result = asyncio.run(fn(**args))
362
+ else:
363
+ result = fn(**args)
364
+ except ReplayDivergenceError:
365
+ raise
366
+ except Exception as exc:
367
+ error = f"{type(exc).__name__}: {exc}"
368
+ session.report(Divergence("error", detail=error))
369
+ if replay_ep is not None:
370
+ session.divergences.extend(structural_divergences(recorded, replay_ep))
371
+ session.finish()
372
+ finally:
373
+ _current_replay.reset(token)
374
+ for ce in replay_ep.contract_events if replay_ep else []:
375
+ if ce.verified:
376
+ session.contracts_passed += 1
377
+ return ReplayReport(
378
+ recorded_episode_id=recorded.id,
379
+ replay_episode_id=replay_ep.id if replay_ep else None,
380
+ entrypoint=recorded.entrypoint
381
+ if entrypoint is None
382
+ else (
383
+ entrypoint
384
+ if isinstance(entrypoint, str)
385
+ else getattr(entrypoint, "__qualname__", repr(entrypoint))
386
+ ),
387
+ deterministic=session.deterministic and error is None,
388
+ matched_calls=session.matched_calls,
389
+ executed_live=session.executed_live,
390
+ contracts_checked=session.contracts_checked,
391
+ contracts_passed=session.contracts_passed,
392
+ divergences=list(session.divergences),
393
+ recorded_metrics=recorded.metrics().to_dict(),
394
+ replayed_metrics=replay_ep.metrics().to_dict() if replay_ep else {},
395
+ duration_s=time.perf_counter() - start,
396
+ error=error,
397
+ result=result,
398
+ )
ma_trace/sampling.py ADDED
@@ -0,0 +1,117 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Adaptive sampling: a low baseline sample rate that escalates to full capture after anomalies."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import random
7
+ import threading
8
+ from collections.abc import Sequence
9
+ from typing import Any
10
+
11
+ from opentelemetry import trace
12
+ from opentelemetry.context import Context
13
+ from opentelemetry.sdk.trace.sampling import Decision, Sampler, SamplingResult
14
+ from opentelemetry.trace import Link, SpanKind, TraceState
15
+
16
+ from .semconv import SemConv
17
+
18
+ _MAX_TRACE_ID = (1 << 64) - 1
19
+
20
+
21
+ class AdaptiveSampler(Sampler):
22
+ """OpenTelemetry sampler with an episode-level decision and anomaly escalation.
23
+
24
+ * ``base_ratio`` - fraction of episodes captured in full during normal operation
25
+ (a typical production setting is 0.10; the library default is 1.0 so that a
26
+ developer sees everything until they opt in to sampling).
27
+ * ``anomaly_ratio`` - fraction captured while in anomaly mode (default 1.0).
28
+ * ``escalation_episodes`` - how many subsequent episodes stay in anomaly mode after
29
+ :meth:`escalate` is called.
30
+
31
+ The tracer calls :meth:`decide_episode` when an episode starts and stamps the
32
+ decision on the root span as the ``<ns>.episode.sampled`` attribute; the sampler
33
+ honours that attribute for root spans and follows the parent for child spans, so
34
+ OTel export and episode recording always agree.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ base_ratio: float = 1.0,
40
+ anomaly_ratio: float = 1.0,
41
+ escalation_episodes: int = 20,
42
+ *,
43
+ rng: random.Random | None = None,
44
+ sampled_attribute: str | None = None,
45
+ ) -> None:
46
+ if not 0.0 <= base_ratio <= 1.0 or not 0.0 <= anomaly_ratio <= 1.0:
47
+ raise ValueError("ratios must be within [0, 1]")
48
+ self.base_ratio = base_ratio
49
+ self.anomaly_ratio = anomaly_ratio
50
+ self.escalation_episodes = escalation_episodes
51
+ self.sampled_attribute = sampled_attribute or SemConv().EPISODE_SAMPLED
52
+ self._rng = rng or random.Random()
53
+ self._remaining = 0
54
+ self._lock = threading.Lock()
55
+ self.escalations: list[str | None] = []
56
+ self.decisions: int = 0
57
+ self.sampled_episodes: int = 0
58
+
59
+ # -- episode level ------------------------------------------------------
60
+
61
+ @property
62
+ def in_anomaly_mode(self) -> bool:
63
+ return self._remaining > 0
64
+
65
+ @property
66
+ def current_ratio(self) -> float:
67
+ return self.anomaly_ratio if self.in_anomaly_mode else self.base_ratio
68
+
69
+ def escalate(self, reason: str | None = None) -> None:
70
+ """Switch to ``anomaly_ratio`` for the next ``escalation_episodes`` episodes."""
71
+ with self._lock:
72
+ self._remaining = self.escalation_episodes
73
+ self.escalations.append(reason)
74
+
75
+ def decide_episode(self) -> bool:
76
+ with self._lock:
77
+ ratio = self.current_ratio
78
+ if self._remaining > 0:
79
+ self._remaining -= 1
80
+ self.decisions += 1
81
+ sampled = ratio >= 1.0 or self._rng.random() < ratio
82
+ if sampled:
83
+ self.sampled_episodes += 1
84
+ return sampled
85
+
86
+ # -- OpenTelemetry Sampler API -----------------------------------------
87
+
88
+ def should_sample(
89
+ self,
90
+ parent_context: Context | None,
91
+ trace_id: int,
92
+ name: str,
93
+ kind: SpanKind | None = None,
94
+ attributes: Any = None,
95
+ links: Sequence[Link] | None = None,
96
+ trace_state: TraceState | None = None,
97
+ ) -> SamplingResult:
98
+ parent_span = trace.get_current_span(parent_context)
99
+ psc = parent_span.get_span_context()
100
+ if psc.is_valid:
101
+ decision = Decision.RECORD_AND_SAMPLE if psc.trace_flags.sampled else Decision.DROP
102
+ return SamplingResult(
103
+ decision, attributes if decision != Decision.DROP else None, psc.trace_state
104
+ )
105
+ if attributes and self.sampled_attribute in attributes:
106
+ flag = bool(attributes[self.sampled_attribute])
107
+ decision = Decision.RECORD_AND_SAMPLE if flag else Decision.DROP
108
+ else:
109
+ bound = round(self.current_ratio * _MAX_TRACE_ID)
110
+ decision = Decision.RECORD_AND_SAMPLE if (trace_id & _MAX_TRACE_ID) < bound else Decision.DROP
111
+ return SamplingResult(decision, attributes if decision != Decision.DROP else None, trace_state)
112
+
113
+ def get_description(self) -> str:
114
+ return (
115
+ f"AdaptiveSampler(base={self.base_ratio}, anomaly={self.anomaly_ratio}, "
116
+ f"escalation={self.escalation_episodes})"
117
+ )
ma_trace/semconv.py ADDED
@@ -0,0 +1,140 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Span attribute names and well-known values.
3
+
4
+ MA-Trace emits two families of attributes:
5
+
6
+ * the standard OpenTelemetry GenAI attributes that already exist in the
7
+ semantic conventions (operation name, agent name, tool name, provider,
8
+ model), and
9
+ * MA-Trace *extension* attributes for coordination edges, memory operations,
10
+ environment contracts, recorded calls and episodes.
11
+
12
+ Extension attributes are emitted under the ``ma_trace.`` namespace by default
13
+ so that they never collide with future official names. ``docs/semantic-conventions.md``
14
+ in the repository documents the proposed ``gen_ai.*`` spelling of every
15
+ extension attribute; pass ``namespace="gen_ai"`` to :class:`ma_trace.MATrace`
16
+ to emit those instead.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ # --- Standard OpenTelemetry GenAI attribute names -----------------------------
22
+ GEN_AI_OPERATION_NAME = "gen_ai.operation.name"
23
+ GEN_AI_AGENT_NAME = "gen_ai.agent.name"
24
+ GEN_AI_AGENT_ID = "gen_ai.agent.id"
25
+ GEN_AI_PROVIDER_NAME = "gen_ai.provider.name"
26
+ GEN_AI_REQUEST_MODEL = "gen_ai.request.model"
27
+ GEN_AI_TOOL_NAME = "gen_ai.tool.name"
28
+ GEN_AI_TOOL_CALL_ID = "gen_ai.tool.call.id"
29
+ GEN_AI_CONVERSATION_ID = "gen_ai.conversation.id"
30
+ ERROR_TYPE = "error.type"
31
+
32
+ # --- Well-known ``gen_ai.operation.name`` values -------------------------------
33
+ OP_INVOKE_AGENT = "invoke_agent"
34
+ OP_INVOKE_WORKFLOW = "invoke_workflow"
35
+ OP_CHAT = "chat"
36
+ OP_EXECUTE_TOOL = "execute_tool"
37
+ # Extension operation values introduced by MA-Trace.
38
+ OP_COORDINATE = "coordinate"
39
+ OP_MEMORY_ACCESS = "memory_access"
40
+ OP_ENVIRONMENT_CONTRACT = "environment_contract"
41
+
42
+ DEFAULT_NAMESPACE = "ma_trace"
43
+ PROPOSED_NAMESPACE = "gen_ai"
44
+
45
+ # Relative names of the extension attributes (joined with the namespace).
46
+ _EXTENSION_KEYS: dict[str, str] = {
47
+ "EPISODE_ID": "episode.id",
48
+ "EPISODE_NAME": "episode.name",
49
+ "EPISODE_SEED": "episode.seed",
50
+ "EPISODE_SAMPLED": "episode.sampled",
51
+ "EPISODE_REPLAY_OF": "episode.replay_of",
52
+ "COORD_SOURCE": "coordination.source",
53
+ "COORD_TARGET": "coordination.target",
54
+ "COORD_KIND": "coordination.kind",
55
+ "COORD_MESSAGE": "coordination.message",
56
+ "COORD_CONFIDENCE": "coordination.confidence",
57
+ "COORD_MESSAGE_ID": "coordination.message_id",
58
+ "COORD_IN_REPLY_TO": "coordination.in_reply_to",
59
+ "MEMORY_AGENT": "memory.agent",
60
+ "MEMORY_OPERATION": "memory.operation",
61
+ "MEMORY_TYPE": "memory.type",
62
+ "MEMORY_KEY": "memory.key",
63
+ "MEMORY_CONFIDENCE": "memory.confidence",
64
+ "MEMORY_HIT": "memory.hit",
65
+ "MEMORY_EVICTION_REASON": "memory.eviction_reason",
66
+ "CONTRACT_ACTION": "contract.action",
67
+ "CONTRACT_PRE_STATE_HASH": "contract.pre_state_hash",
68
+ "CONTRACT_POST_STATE_HASH": "contract.post_state_hash",
69
+ "CONTRACT_SEED": "contract.seed",
70
+ "CONTRACT_RESULT": "contract.result",
71
+ "CONTRACT_VERIFIED": "contract.verified",
72
+ "CALL_INDEX": "call.index",
73
+ "CALL_INPUT_FINGERPRINT": "call.input_fingerprint",
74
+ "CALL_OUTPUT_FINGERPRINT": "call.output_fingerprint",
75
+ "CALL_REPLAYED": "call.replayed",
76
+ "ACTION_NAME": "action.name",
77
+ "ACTION_FINGERPRINT": "action.fingerprint",
78
+ "ACTION_NOOP": "action.noop",
79
+ "STATE_HASH": "state.hash",
80
+ "STATE_LABEL": "state.label",
81
+ }
82
+
83
+
84
+ class SemConv:
85
+ """Resolved attribute names for one namespace.
86
+
87
+ >>> SemConv().COORD_SOURCE
88
+ 'ma_trace.coordination.source'
89
+ >>> SemConv("gen_ai").COORD_SOURCE
90
+ 'gen_ai.coordination.source'
91
+ """
92
+
93
+ EPISODE_ID: str
94
+ EPISODE_NAME: str
95
+ EPISODE_SEED: str
96
+ EPISODE_SAMPLED: str
97
+ EPISODE_REPLAY_OF: str
98
+ COORD_SOURCE: str
99
+ COORD_TARGET: str
100
+ COORD_KIND: str
101
+ COORD_MESSAGE: str
102
+ COORD_CONFIDENCE: str
103
+ COORD_MESSAGE_ID: str
104
+ COORD_IN_REPLY_TO: str
105
+ MEMORY_AGENT: str
106
+ MEMORY_OPERATION: str
107
+ MEMORY_TYPE: str
108
+ MEMORY_KEY: str
109
+ MEMORY_CONFIDENCE: str
110
+ MEMORY_HIT: str
111
+ MEMORY_EVICTION_REASON: str
112
+ CONTRACT_ACTION: str
113
+ CONTRACT_PRE_STATE_HASH: str
114
+ CONTRACT_POST_STATE_HASH: str
115
+ CONTRACT_SEED: str
116
+ CONTRACT_RESULT: str
117
+ CONTRACT_VERIFIED: str
118
+ CALL_INDEX: str
119
+ CALL_INPUT_FINGERPRINT: str
120
+ CALL_OUTPUT_FINGERPRINT: str
121
+ CALL_REPLAYED: str
122
+ ACTION_NAME: str
123
+ ACTION_FINGERPRINT: str
124
+ ACTION_NOOP: str
125
+ STATE_HASH: str
126
+ STATE_LABEL: str
127
+
128
+ def __init__(self, namespace: str = DEFAULT_NAMESPACE) -> None:
129
+ if not namespace or not namespace.replace("_", "").replace(".", "").isalnum():
130
+ raise ValueError(f"invalid attribute namespace: {namespace!r}")
131
+ self.namespace = namespace
132
+ for const, rel in _EXTENSION_KEYS.items():
133
+ setattr(self, const, f"{namespace}.{rel}")
134
+
135
+ def all_attributes(self) -> dict[str, str]:
136
+ """Return ``{CONSTANT_NAME: fully.qualified.name}`` for every extension attribute."""
137
+ return {k: getattr(self, k) for k in _EXTENSION_KEYS}
138
+
139
+ def __repr__(self) -> str: # pragma: no cover - trivial
140
+ return f"SemConv(namespace={self.namespace!r})"