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/tracer.py ADDED
@@ -0,0 +1,779 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """The :class:`MATrace` facade: episodes, agent spans, recorded calls, coordination edges,
3
+ memory operations, environment contracts and SLO export."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import functools
8
+ import inspect
9
+ import itertools
10
+ import logging
11
+ import random
12
+ import threading
13
+ import time
14
+ from collections.abc import Callable, Iterator
15
+ from contextlib import contextmanager
16
+ from typing import Any
17
+
18
+ from opentelemetry import context as otel_context
19
+ from opentelemetry import trace
20
+ from opentelemetry.trace import SpanKind, Status, StatusCode
21
+
22
+ from . import semconv as sc
23
+ from ._version import __version__
24
+ from .context import _current_agent, _current_episode, current_agent, current_episode, current_replay
25
+ from .contracts import Contract
26
+ from .episode import Episode, _wall_time
27
+ from .events import (
28
+ ActionEvent,
29
+ AgentEvent,
30
+ CallEvent,
31
+ CallType,
32
+ CoordinationEvent,
33
+ CoordinationKind,
34
+ Event,
35
+ EvictionReason,
36
+ LogEvent,
37
+ MemoryEvent,
38
+ MemoryOp,
39
+ MemoryType,
40
+ StateEvent,
41
+ fingerprint,
42
+ json_safe,
43
+ truncate,
44
+ )
45
+ from .metrics import OTelMetricsExporter, SLOMetrics, compute_metrics
46
+ from .sampling import AdaptiveSampler
47
+ from .semconv import SemConv
48
+ from .store import EpisodeStore, InMemoryEpisodeStore
49
+
50
+ log = logging.getLogger("ma_trace")
51
+
52
+ F = Callable[..., Any]
53
+
54
+
55
+ class CallHandle:
56
+ """Handle yielded by :meth:`MATrace.llm_call` / :meth:`MATrace.tool_call`.
57
+
58
+ Inside the ``with`` block check :attr:`should_execute`; when it is ``False`` the
59
+ call is being replayed and :attr:`recorded_output` holds the recorded result.
60
+ Call :meth:`set_output` with whatever the call produced (or the recorded output).
61
+ """
62
+
63
+ def __init__(self, event: CallEvent) -> None:
64
+ self.event = event
65
+ self.should_execute = True
66
+ self.recorded_output: Any = None
67
+ self.matched: CallEvent | None = None
68
+ self.output: Any = None
69
+ self.output_set = False
70
+
71
+ def set_output(self, output: Any) -> None:
72
+ self.output = output
73
+ self.output_set = True
74
+
75
+ @property
76
+ def replayed(self) -> bool:
77
+ return not self.should_execute
78
+
79
+
80
+ class MATrace:
81
+ """Central object of MA-Trace. One instance per process is typical (see :func:`configure`).
82
+
83
+ Parameters
84
+ ----------
85
+ service_name:
86
+ Reported as the OpenTelemetry ``service.name`` when this object builds providers.
87
+ tracer_provider / meter_provider:
88
+ Explicit OpenTelemetry providers. Defaults to the global ones (no-op until configured).
89
+ store:
90
+ Where sampled episodes are persisted: an :class:`EpisodeStore`, an
91
+ :class:`InMemoryEpisodeStore`, a directory path, ``"memory"`` or ``None``
92
+ (default: :class:`EpisodeStore` under ``$MA_TRACE_STORE`` or ``./.ma-trace/episodes``).
93
+ sampler:
94
+ An :class:`AdaptiveSampler` deciding which episodes are captured in full.
95
+ namespace:
96
+ Attribute namespace for the extension attributes (``"ma_trace"`` or ``"gen_ai"``).
97
+ record_outputs:
98
+ Store LLM/tool outputs inside episodes so they can be replayed.
99
+ max_message_chars:
100
+ Coordination messages are truncated to this length before being stored.
101
+ metrics_exporters:
102
+ Objects with an ``export(SLOMetrics)`` method, called at the end of every episode
103
+ (for example :class:`ma_trace.metrics.PrometheusExporter`).
104
+ """
105
+
106
+ def __init__(
107
+ self,
108
+ service_name: str = "ma-trace",
109
+ *,
110
+ tracer_provider: Any = None,
111
+ meter_provider: Any = None,
112
+ store: EpisodeStore | InMemoryEpisodeStore | str | None = None,
113
+ sampler: AdaptiveSampler | None = None,
114
+ namespace: str = sc.DEFAULT_NAMESPACE,
115
+ record_outputs: bool = True,
116
+ max_message_chars: int = 512,
117
+ metrics_exporters: list[Any] | None = None,
118
+ otel_metrics: bool = True,
119
+ ) -> None:
120
+ self.service_name = service_name
121
+ self.semconv = SemConv(namespace)
122
+ self._otel = trace.get_tracer("ma_trace", __version__, tracer_provider=tracer_provider)
123
+ self.record_outputs = record_outputs
124
+ self.max_message_chars = max_message_chars
125
+ self.sampler = sampler or AdaptiveSampler(
126
+ base_ratio=1.0, sampled_attribute=self.semconv.EPISODE_SAMPLED
127
+ )
128
+ if isinstance(self.sampler, AdaptiveSampler):
129
+ self.sampler.sampled_attribute = self.semconv.EPISODE_SAMPLED
130
+ if store is None:
131
+ self.store: EpisodeStore | InMemoryEpisodeStore | None = EpisodeStore()
132
+ elif isinstance(store, str):
133
+ self.store = InMemoryEpisodeStore() if store == "memory" else EpisodeStore(store)
134
+ else:
135
+ self.store = store
136
+ self.metrics_exporters: list[Any] = list(metrics_exporters or [])
137
+ if otel_metrics:
138
+ self.metrics_exporters.append(OTelMetricsExporter(meter_provider, namespace=namespace))
139
+ self.on_episode_end: list[Callable[[Episode, SLOMetrics], None]] = []
140
+ self.last_metrics: SLOMetrics | None = None
141
+ self.last_episode: Episode | None = None
142
+ self._fallback_episode: Episode | None = None
143
+ self._seq: dict[str, itertools.count[int]] = {}
144
+ self._call_index: dict[str, itertools.count[int]] = {}
145
+ self._lock = threading.Lock()
146
+
147
+ # ------------------------------------------------------------------ episodes
148
+
149
+ @contextmanager
150
+ def episode(
151
+ self,
152
+ name: str,
153
+ *,
154
+ seed: int | None = None,
155
+ entrypoint: str | Callable[..., Any] | None = None,
156
+ entrypoint_args: dict[str, Any] | None = None,
157
+ attributes: dict[str, Any] | None = None,
158
+ record: bool | None = None,
159
+ replay_of: str | None = None,
160
+ ) -> Iterator[Episode]:
161
+ """Open an episode. Everything recorded inside the block belongs to it.
162
+
163
+ ``seed`` seeds :mod:`random` and ``episode.rng`` so that seeded randomness is
164
+ reproducible under replay. ``entrypoint`` (``"pkg.module:function"`` or a
165
+ callable) plus ``entrypoint_args`` let ``ma-trace replay <id>`` re-execute the
166
+ episode without further arguments.
167
+ """
168
+ sampled = self.sampler.decide_episode() if record is None else bool(record)
169
+ ep = Episode(
170
+ id=Episode.new_id(),
171
+ name=name,
172
+ seed=seed,
173
+ entrypoint=_entrypoint_name(entrypoint),
174
+ entrypoint_args=dict(entrypoint_args or {}),
175
+ attributes=dict(attributes or {}),
176
+ sampled=sampled,
177
+ replay_of=replay_of,
178
+ )
179
+ if seed is not None:
180
+ ep.rng = random.Random(seed)
181
+ random.seed(seed)
182
+ s = self.semconv
183
+ attrs: dict[str, Any] = {
184
+ sc.GEN_AI_OPERATION_NAME: sc.OP_INVOKE_WORKFLOW,
185
+ s.EPISODE_ID: ep.id,
186
+ s.EPISODE_NAME: name,
187
+ s.EPISODE_SAMPLED: sampled,
188
+ }
189
+ if seed is not None:
190
+ attrs[s.EPISODE_SEED] = seed
191
+ if replay_of:
192
+ attrs[s.EPISODE_REPLAY_OF] = replay_of
193
+ span = self._otel.start_span(f"{sc.OP_INVOKE_WORKFLOW} {name}", attributes=attrs)
194
+ ctx_token = otel_context.attach(trace.set_span_in_context(span))
195
+ ep_token = _current_episode.set(ep)
196
+ try:
197
+ yield ep
198
+ except BaseException as exc:
199
+ span.record_exception(exc)
200
+ span.set_status(Status(StatusCode.ERROR, str(exc)))
201
+ ep.attributes["error"] = f"{type(exc).__name__}: {exc}"
202
+ raise
203
+ finally:
204
+ ep.ended_at = _wall_time()
205
+ try:
206
+ self._finish_episode(ep, span)
207
+ finally:
208
+ _current_episode.reset(ep_token)
209
+ otel_context.detach(ctx_token)
210
+ span.end()
211
+ self._seq.pop(ep.id, None)
212
+ self._call_index.pop(ep.id, None)
213
+
214
+ def _finish_episode(self, ep: Episode, span: trace.Span) -> None:
215
+ m = compute_metrics(ep)
216
+ self.last_metrics = m
217
+ self.last_episode = ep
218
+ prefix = f"{self.semconv.namespace}.slo."
219
+ span.set_attribute(prefix + "coordination_overhead", m.coordination_overhead)
220
+ span.set_attribute(prefix + "redundant_action_rate", m.redundant_action_rate)
221
+ span.set_attribute(prefix + "oscillation_rate", m.oscillation_rate)
222
+ span.set_attribute(prefix + "memory_hit_ratio", m.memory_hit_ratio)
223
+ for exporter in self.metrics_exporters:
224
+ try:
225
+ exporter.export(m)
226
+ except Exception as exc: # pragma: no cover - never let telemetry break the app
227
+ log.warning("metrics exporter %r failed: %s", exporter, exc)
228
+ if ep.sampled and self.store is not None:
229
+ try:
230
+ self.store.save(ep)
231
+ except Exception as exc: # pragma: no cover
232
+ log.warning("could not persist episode %s: %s", ep.id, exc)
233
+ for cb in self.on_episode_end:
234
+ try:
235
+ cb(ep, m)
236
+ except Exception as exc: # pragma: no cover
237
+ log.warning("on_episode_end callback failed: %s", exc)
238
+
239
+ def bind_episode(self, episode: Episode | None) -> None:
240
+ """Set a process-wide fallback episode for callbacks that run outside the
241
+ context in which the episode was opened (multi-threaded frameworks)."""
242
+ self._fallback_episode = episode
243
+
244
+ def current_episode(self) -> Episode | None:
245
+ return current_episode() or self._fallback_episode
246
+
247
+ # ------------------------------------------------------------------ recording
248
+
249
+ def _record(self, event: Event, episode: Episode | None = None) -> Event:
250
+ ep = episode or self.current_episode()
251
+ if ep is None:
252
+ return event
253
+ with self._lock:
254
+ counter = self._seq.setdefault(ep.id, itertools.count())
255
+ event.seq = next(counter)
256
+ event.t = _wall_time()
257
+ ep.events.append(event)
258
+ return event
259
+
260
+ def _next_call_index(self, ep: Episode | None) -> int:
261
+ if ep is None:
262
+ return 0
263
+ with self._lock:
264
+ return next(self._call_index.setdefault(ep.id, itertools.count()))
265
+
266
+ # ------------------------------------------------------------------ agents
267
+
268
+ @contextmanager
269
+ def agent_span(
270
+ self, name: str, *, agent_id: str | None = None, attributes: dict[str, Any] | None = None
271
+ ) -> Iterator[trace.Span]:
272
+ """Context manager marking an agent invocation (``invoke_agent`` span)."""
273
+ token = _current_agent.set(name)
274
+ start = time.perf_counter()
275
+ self._record(AgentEvent(agent=name, phase="start"))
276
+ attrs: dict[str, Any] = {sc.GEN_AI_OPERATION_NAME: sc.OP_INVOKE_AGENT, sc.GEN_AI_AGENT_NAME: name}
277
+ if agent_id:
278
+ attrs[sc.GEN_AI_AGENT_ID] = agent_id
279
+ if attributes:
280
+ attrs.update(attributes)
281
+ error: str | None = None
282
+ with self._otel.start_as_current_span(
283
+ f"{sc.OP_INVOKE_AGENT} {name}", attributes=attrs, kind=SpanKind.CLIENT
284
+ ) as span:
285
+ try:
286
+ yield span
287
+ except BaseException as exc:
288
+ error = f"{type(exc).__name__}: {exc}"
289
+ span.record_exception(exc)
290
+ span.set_status(Status(StatusCode.ERROR, str(exc)))
291
+ span.set_attribute(sc.ERROR_TYPE, type(exc).__name__)
292
+ raise
293
+ finally:
294
+ self._record(
295
+ AgentEvent(agent=name, phase="end", duration_s=time.perf_counter() - start, error=error)
296
+ )
297
+ _current_agent.reset(token)
298
+
299
+ def agent(self, name: str, *, agent_id: str | None = None) -> Callable[[F], F]:
300
+ """Decorator: run the function inside an agent span."""
301
+
302
+ def decorate(fn: F) -> F:
303
+ if inspect.iscoroutinefunction(fn):
304
+
305
+ @functools.wraps(fn)
306
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
307
+ with self.agent_span(name, agent_id=agent_id):
308
+ return await fn(*args, **kwargs)
309
+
310
+ return async_wrapper # type: ignore[return-value]
311
+
312
+ @functools.wraps(fn)
313
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
314
+ with self.agent_span(name, agent_id=agent_id):
315
+ return fn(*args, **kwargs)
316
+
317
+ return wrapper # type: ignore[return-value]
318
+
319
+ return decorate
320
+
321
+ # ------------------------------------------------------------------ calls
322
+
323
+ @contextmanager
324
+ def call(
325
+ self,
326
+ call_type: CallType | str,
327
+ name: str,
328
+ *,
329
+ agent: str | None = None,
330
+ provider: str | None = None,
331
+ model: str | None = None,
332
+ inputs: Any = None,
333
+ record_output: bool | None = None,
334
+ encode: Callable[[Any], Any] | None = None,
335
+ decode: Callable[[Any], Any] | None = None,
336
+ call_id: str | None = None,
337
+ ) -> Iterator[CallHandle]:
338
+ """Record one non-deterministic call (LLM or tool). Replay-aware."""
339
+ ctype = CallType(call_type)
340
+ agent_name = agent or current_agent() or "unknown"
341
+ ep = self.current_episode()
342
+ ev = CallEvent(
343
+ agent=agent_name,
344
+ call_type=ctype,
345
+ name=name,
346
+ provider=provider,
347
+ model=model,
348
+ index=self._next_call_index(ep),
349
+ input_fingerprint=fingerprint(inputs) if inputs is not None else "",
350
+ )
351
+ handle = CallHandle(ev)
352
+ session = current_replay()
353
+ if session is not None:
354
+ matched, divergence = session.consume_call(ev)
355
+ if divergence is not None:
356
+ session.report(divergence)
357
+ if matched is not None:
358
+ if matched.output_recorded:
359
+ handle.should_execute = False
360
+ handle.matched = matched
361
+ handle.recorded_output = decode(matched.output) if decode else matched.output
362
+ ev.replayed = True
363
+ else:
364
+ session.report_output_unavailable(matched)
365
+ s = self.semconv
366
+ attrs: dict[str, Any] = {
367
+ sc.GEN_AI_AGENT_NAME: agent_name,
368
+ sc.GEN_AI_PROVIDER_NAME: provider or ("unknown" if ctype == CallType.LLM else "tool"),
369
+ s.CALL_INDEX: ev.index,
370
+ s.CALL_REPLAYED: ev.replayed,
371
+ }
372
+ if ev.input_fingerprint:
373
+ attrs[s.CALL_INPUT_FINGERPRINT] = ev.input_fingerprint
374
+ if ctype == CallType.LLM:
375
+ attrs[sc.GEN_AI_OPERATION_NAME] = sc.OP_CHAT
376
+ if model:
377
+ attrs[sc.GEN_AI_REQUEST_MODEL] = model
378
+ span_name = f"{sc.OP_CHAT} {model}" if model else sc.OP_CHAT
379
+ else:
380
+ attrs[sc.GEN_AI_OPERATION_NAME] = sc.OP_EXECUTE_TOOL
381
+ attrs[sc.GEN_AI_TOOL_NAME] = name
382
+ if call_id:
383
+ attrs[sc.GEN_AI_TOOL_CALL_ID] = call_id
384
+ span_name = f"{sc.OP_EXECUTE_TOOL} {name}"
385
+ start = time.perf_counter()
386
+ with self._otel.start_as_current_span(span_name, attributes=attrs, kind=SpanKind.CLIENT) as span:
387
+ try:
388
+ yield handle
389
+ except BaseException as exc:
390
+ ev.error = f"{type(exc).__name__}: {exc}"
391
+ span.record_exception(exc)
392
+ span.set_status(Status(StatusCode.ERROR, str(exc)))
393
+ span.set_attribute(sc.ERROR_TYPE, type(exc).__name__)
394
+ raise
395
+ finally:
396
+ ev.duration_s = time.perf_counter() - start
397
+ if handle.output_set:
398
+ should_record = self.record_outputs if record_output is None else record_output
399
+ if should_record and ep is not None and ep.sampled:
400
+ stored = encode(handle.output) if encode else handle.output
401
+ value, ok = json_safe(stored)
402
+ ev.output = value
403
+ ev.output_recorded = ok
404
+ ev.output_fingerprint = fingerprint(handle.output)
405
+ span.set_attribute(s.CALL_OUTPUT_FINGERPRINT, ev.output_fingerprint)
406
+ self._record(ev, ep)
407
+
408
+ def llm_call(
409
+ self,
410
+ agent: str | None = None,
411
+ *,
412
+ provider: str | None = None,
413
+ model: str | None = None,
414
+ name: str = "chat",
415
+ **kw: Any,
416
+ ): # type: ignore[no-untyped-def]
417
+ """Context-manager form of :meth:`llm` for inline calls."""
418
+ return self.call(CallType.LLM, name, agent=agent, provider=provider, model=model, **kw)
419
+
420
+ def tool_call(self, name: str, agent: str | None = None, **kw: Any): # type: ignore[no-untyped-def]
421
+ """Context-manager form of :meth:`tool` for inline calls."""
422
+ return self.call(CallType.TOOL, name, agent=agent, **kw)
423
+
424
+ def _wrap_call(
425
+ self,
426
+ call_type: CallType,
427
+ name: str,
428
+ agent: str | None,
429
+ provider: str | None,
430
+ model: str | None,
431
+ inputs: Callable[..., Any] | None,
432
+ kw: dict[str, Any],
433
+ ) -> Callable[[F], F]:
434
+ def decorate(fn: F) -> F:
435
+ call_name = name or getattr(fn, "__name__", "call")
436
+
437
+ def _inputs(args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
438
+ if inputs is not None:
439
+ return inputs(*args, **kwargs)
440
+ return {"args": list(args), "kwargs": kwargs}
441
+
442
+ if inspect.iscoroutinefunction(fn):
443
+
444
+ @functools.wraps(fn)
445
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
446
+ with self.call(
447
+ call_type,
448
+ call_name,
449
+ agent=agent,
450
+ provider=provider,
451
+ model=model,
452
+ inputs=_inputs(args, kwargs),
453
+ **kw,
454
+ ) as h:
455
+ out = await fn(*args, **kwargs) if h.should_execute else h.recorded_output
456
+ h.set_output(out)
457
+ return out
458
+
459
+ return async_wrapper # type: ignore[return-value]
460
+
461
+ @functools.wraps(fn)
462
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
463
+ with self.call(
464
+ call_type,
465
+ call_name,
466
+ agent=agent,
467
+ provider=provider,
468
+ model=model,
469
+ inputs=_inputs(args, kwargs),
470
+ **kw,
471
+ ) as h:
472
+ out = fn(*args, **kwargs) if h.should_execute else h.recorded_output
473
+ h.set_output(out)
474
+ return out
475
+
476
+ return wrapper # type: ignore[return-value]
477
+
478
+ return decorate
479
+
480
+ def llm(
481
+ self,
482
+ agent: str | None = None,
483
+ *,
484
+ provider: str | None = None,
485
+ model: str | None = None,
486
+ name: str = "chat",
487
+ inputs: Callable[..., Any] | None = None,
488
+ **kw: Any,
489
+ ) -> Callable[[F], F]:
490
+ """Decorator for a function that performs an LLM call.
491
+
492
+ The wrapped function's arguments are fingerprinted and its return value is
493
+ recorded. Under replay the function is *not* executed when a recorded output
494
+ with a matching fingerprint exists; the recorded output is returned instead.
495
+ ``inputs`` may be a function that maps the call arguments to the value that
496
+ should be fingerprinted (use it to exclude clients, callbacks, timestamps...).
497
+ """
498
+ return self._wrap_call(CallType.LLM, name, agent, provider, model, inputs, kw)
499
+
500
+ def tool(
501
+ self,
502
+ name: str | None = None,
503
+ agent: str | None = None,
504
+ *,
505
+ inputs: Callable[..., Any] | None = None,
506
+ **kw: Any,
507
+ ) -> Callable[[F], F]:
508
+ """Decorator for a tool function (same replay semantics as :meth:`llm`)."""
509
+ return self._wrap_call(CallType.TOOL, name or "", agent, None, None, inputs, kw)
510
+
511
+ # ------------------------------------------------------------------ coordination / memory / contracts
512
+
513
+ def coordination(
514
+ self,
515
+ source: str,
516
+ target: str,
517
+ message: Any = "",
518
+ *,
519
+ kind: CoordinationKind | str = CoordinationKind.MESSAGE,
520
+ confidence: float | None = None,
521
+ message_id: str | None = None,
522
+ in_reply_to: str | None = None,
523
+ **metadata: Any,
524
+ ) -> CoordinationEvent:
525
+ """Record a coordination edge ``source -> target``."""
526
+ k = CoordinationKind(kind)
527
+ ev = CoordinationEvent(
528
+ agent=source,
529
+ source=source,
530
+ target=target,
531
+ message=truncate(message, self.max_message_chars),
532
+ kind=k,
533
+ confidence=confidence,
534
+ message_id=message_id,
535
+ in_reply_to=in_reply_to,
536
+ metadata=dict(metadata),
537
+ )
538
+ self._record(ev)
539
+ s = self.semconv
540
+ attrs: dict[str, Any] = {
541
+ sc.GEN_AI_OPERATION_NAME: sc.OP_COORDINATE,
542
+ sc.GEN_AI_AGENT_NAME: source,
543
+ s.COORD_SOURCE: source,
544
+ s.COORD_TARGET: target,
545
+ s.COORD_KIND: k.value,
546
+ s.COORD_MESSAGE: ev.message,
547
+ }
548
+ if confidence is not None:
549
+ attrs[s.COORD_CONFIDENCE] = confidence
550
+ if message_id:
551
+ attrs[s.COORD_MESSAGE_ID] = message_id
552
+ if in_reply_to:
553
+ attrs[s.COORD_IN_REPLY_TO] = in_reply_to
554
+ span = self._otel.start_span(
555
+ f"{sc.OP_COORDINATE} {source}->{target}", attributes=attrs, kind=SpanKind.PRODUCER
556
+ )
557
+ span.end()
558
+ return ev
559
+
560
+ def memory(
561
+ self,
562
+ agent: str,
563
+ op: MemoryOp | str,
564
+ memory_type: MemoryType | str,
565
+ key: str,
566
+ *,
567
+ confidence: float | None = None,
568
+ hit: bool | None = None,
569
+ eviction_reason: EvictionReason | str | None = None,
570
+ **metadata: Any,
571
+ ) -> MemoryEvent:
572
+ """Record a memory operation (read / write / evict / delete)."""
573
+ ev = MemoryEvent(
574
+ agent=agent,
575
+ op=MemoryOp(op),
576
+ memory_type=MemoryType(memory_type),
577
+ key=key,
578
+ confidence=confidence,
579
+ hit=hit,
580
+ eviction_reason=EvictionReason(eviction_reason) if eviction_reason is not None else None,
581
+ metadata=dict(metadata),
582
+ )
583
+ self._record(ev)
584
+ s = self.semconv
585
+ attrs: dict[str, Any] = {
586
+ sc.GEN_AI_OPERATION_NAME: sc.OP_MEMORY_ACCESS,
587
+ sc.GEN_AI_AGENT_NAME: agent,
588
+ s.MEMORY_AGENT: agent,
589
+ s.MEMORY_OPERATION: ev.op.value,
590
+ s.MEMORY_TYPE: ev.memory_type.value,
591
+ s.MEMORY_KEY: key,
592
+ }
593
+ if confidence is not None:
594
+ attrs[s.MEMORY_CONFIDENCE] = confidence
595
+ if hit is not None:
596
+ attrs[s.MEMORY_HIT] = hit
597
+ if ev.eviction_reason is not None:
598
+ attrs[s.MEMORY_EVICTION_REASON] = ev.eviction_reason.value
599
+ span = self._otel.start_span(f"{sc.OP_MEMORY_ACCESS} {ev.op.value} {key}", attributes=attrs)
600
+ span.end()
601
+ return ev
602
+
603
+ @contextmanager
604
+ def contract(
605
+ self, agent: str, action: str, pre_state: Any, *, seed: int | None = None, **metadata: Any
606
+ ) -> Iterator[Contract]:
607
+ """Record an environment contract around an action.
608
+
609
+ If ``seed`` is omitted and the episode has a seed, a per-action seed is derived
610
+ from the episode's RNG so that replays reproduce the same sequence of seeds.
611
+ """
612
+ ep = self.current_episode()
613
+ if seed is None and ep is not None and ep.rng is not None:
614
+ seed = ep.rng.randrange(1 << 31)
615
+ c = Contract.begin(agent, action, pre_state, seed=seed, **metadata)
616
+ session = current_replay()
617
+ if session is not None:
618
+ recorded, divergence = session.consume_contract(c)
619
+ c.recorded = recorded
620
+ if divergence is not None:
621
+ session.report(divergence)
622
+ s = self.semconv
623
+ attrs: dict[str, Any] = {
624
+ sc.GEN_AI_OPERATION_NAME: sc.OP_ENVIRONMENT_CONTRACT,
625
+ sc.GEN_AI_AGENT_NAME: agent,
626
+ s.CONTRACT_ACTION: action,
627
+ s.CONTRACT_PRE_STATE_HASH: c.pre_hash,
628
+ }
629
+ if seed is not None:
630
+ attrs[s.CONTRACT_SEED] = seed
631
+ with self._otel.start_as_current_span(
632
+ f"{sc.OP_ENVIRONMENT_CONTRACT} {action}", attributes=attrs
633
+ ) as span:
634
+ try:
635
+ yield c
636
+ finally:
637
+ if c.recorded is not None:
638
+ check = c.verify()
639
+ if check is not None and not check.ok and session is not None:
640
+ session.report_contract_mismatch(c, check)
641
+ ev = c.to_event()
642
+ if ev.post_hash:
643
+ span.set_attribute(s.CONTRACT_POST_STATE_HASH, ev.post_hash)
644
+ if ev.result is not None:
645
+ span.set_attribute(s.CONTRACT_RESULT, ev.result)
646
+ if ev.verified is not None:
647
+ span.set_attribute(s.CONTRACT_VERIFIED, ev.verified)
648
+ self._record(ev, ep)
649
+
650
+ def action(
651
+ self,
652
+ agent: str,
653
+ name: str,
654
+ args: Any = None,
655
+ *,
656
+ noop: bool = False,
657
+ state_before: Any = None,
658
+ state_after: Any = None,
659
+ ) -> ActionEvent:
660
+ """Record a discrete action (feeds the redundant-action and oscillation SLOs)."""
661
+ ev = ActionEvent(
662
+ agent=agent,
663
+ name=name,
664
+ args_fingerprint=fingerprint(args),
665
+ noop=noop,
666
+ state_before=fingerprint(state_before) if state_before is not None else None,
667
+ state_after=fingerprint(state_after) if state_after is not None else None,
668
+ )
669
+ self._record(ev)
670
+ return ev
671
+
672
+ def state(self, agent: str, state: Any, label: str | None = None) -> StateEvent:
673
+ """Record a snapshot of an agent's state (feeds the oscillation SLO)."""
674
+ ev = StateEvent(agent=agent, state_hash=fingerprint(state), label=label)
675
+ self._record(ev)
676
+ return ev
677
+
678
+ def log(self, message: str, *, level: str = "info", agent: str | None = None, **data: Any) -> LogEvent:
679
+ ev = LogEvent(agent=agent or current_agent(), level=level, message=message, data=dict(data))
680
+ self._record(ev)
681
+ return ev
682
+
683
+ # ------------------------------------------------------------------ anomalies / replay
684
+
685
+ def flag_anomaly(self, reason: str | None = None) -> None:
686
+ """Escalate the adaptive sampler to full capture for the next episodes."""
687
+ if isinstance(self.sampler, AdaptiveSampler):
688
+ self.sampler.escalate(reason)
689
+ self.log(f"anomaly flagged: {reason}", level="warning", reason=reason)
690
+
691
+ def replay(
692
+ self,
693
+ episode: Episode | str,
694
+ entrypoint: str | Callable[..., Any] | None = None,
695
+ *,
696
+ strict: bool = False,
697
+ entrypoint_args: dict[str, Any] | None = None,
698
+ ): # type: ignore[no-untyped-def]
699
+ """Deterministically re-execute a recorded episode. See :func:`ma_trace.replay.run_replay`."""
700
+ from .replay import run_replay
701
+
702
+ return run_replay(self, episode, entrypoint, strict=strict, entrypoint_args=entrypoint_args)
703
+
704
+
705
+ def _entrypoint_name(entrypoint: str | Callable[..., Any] | None) -> str | None:
706
+ if entrypoint is None:
707
+ return None
708
+ if isinstance(entrypoint, str):
709
+ return entrypoint
710
+ module = getattr(entrypoint, "__module__", None)
711
+ qualname = getattr(entrypoint, "__qualname__", getattr(entrypoint, "__name__", None))
712
+ if module and qualname:
713
+ return f"{module}:{qualname}"
714
+ return repr(entrypoint)
715
+
716
+
717
+ # ---------------------------------------------------------------------- module-level API
718
+
719
+ _default: MATrace | None = None
720
+ _default_lock = threading.Lock()
721
+
722
+
723
+ def get_tracer() -> MATrace:
724
+ """The process-wide default :class:`MATrace` (created lazily)."""
725
+ global _default
726
+ with _default_lock:
727
+ if _default is None:
728
+ _default = MATrace()
729
+ return _default
730
+
731
+
732
+ def set_tracer(tracer: MATrace | None) -> None:
733
+ global _default
734
+ with _default_lock:
735
+ _default = tracer
736
+
737
+
738
+ def configure(
739
+ service_name: str = "ma-trace",
740
+ *,
741
+ exporter: str | Any | None = None,
742
+ endpoint: str | None = None,
743
+ metrics_exporter: str | Any | None = None,
744
+ store: EpisodeStore | InMemoryEpisodeStore | str | None = None,
745
+ sampler: AdaptiveSampler | None = None,
746
+ namespace: str = sc.DEFAULT_NAMESPACE,
747
+ **kwargs: Any,
748
+ ) -> MATrace:
749
+ """Create the default tracer, optionally wiring OpenTelemetry export.
750
+
751
+ ``exporter``: ``"console"``, ``"otlp"``, a ``SpanExporter`` or ``None`` (no export).
752
+ ``metrics_exporter``: ``"console"``, ``"otlp"``, ``"prometheus"``, a ``MetricExporter``
753
+ or ``None``.
754
+ """
755
+ from .exporters import build_meter_provider, build_tracer_provider
756
+
757
+ tracer_provider = None
758
+ meter_provider = None
759
+ metrics_exporters: list[Any] = list(kwargs.pop("metrics_exporters", []) or [])
760
+ if exporter is not None:
761
+ tracer_provider = build_tracer_provider(service_name, exporter, endpoint=endpoint, sampler=sampler)
762
+ if metrics_exporter == "prometheus":
763
+ from .metrics import PrometheusExporter
764
+
765
+ metrics_exporters.append(PrometheusExporter())
766
+ elif metrics_exporter is not None:
767
+ meter_provider = build_meter_provider(service_name, metrics_exporter, endpoint=endpoint)
768
+ tracer = MATrace(
769
+ service_name,
770
+ tracer_provider=tracer_provider,
771
+ meter_provider=meter_provider,
772
+ store=store,
773
+ sampler=sampler,
774
+ namespace=namespace,
775
+ metrics_exporters=metrics_exporters,
776
+ **kwargs,
777
+ )
778
+ set_tracer(tracer)
779
+ return tracer