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/__init__.py +204 -0
- ma_trace/_version.py +2 -0
- ma_trace/adapters/__init__.py +9 -0
- ma_trace/adapters/autogen.py +159 -0
- ma_trace/adapters/crewai.py +337 -0
- ma_trace/adapters/langchain.py +395 -0
- ma_trace/adapters/langgraph.py +100 -0
- ma_trace/cli.py +349 -0
- ma_trace/context.py +29 -0
- ma_trace/contracts.py +107 -0
- ma_trace/episode.py +208 -0
- ma_trace/events.py +291 -0
- ma_trace/exporters.py +154 -0
- ma_trace/graph.py +211 -0
- ma_trace/memory.py +174 -0
- ma_trace/metrics.py +340 -0
- ma_trace/py.typed +0 -0
- ma_trace/replay.py +398 -0
- ma_trace/sampling.py +117 -0
- ma_trace/semconv.py +140 -0
- ma_trace/store.py +185 -0
- ma_trace/tracer.py +779 -0
- multi_agent_observability-0.1.0.dist-info/METADATA +365 -0
- multi_agent_observability-0.1.0.dist-info/RECORD +27 -0
- multi_agent_observability-0.1.0.dist-info/WHEEL +4 -0
- multi_agent_observability-0.1.0.dist-info/entry_points.txt +2 -0
- multi_agent_observability-0.1.0.dist-info/licenses/LICENSE +201 -0
ma_trace/cli.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""``ma-trace`` command line interface (distribution ``multi-agent-observability``)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from ._version import __version__
|
|
14
|
+
from .episode import Episode
|
|
15
|
+
from .metrics import SLOThresholds, evaluate
|
|
16
|
+
from .store import EpisodeStore
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _fmt_time(t: float) -> str:
|
|
20
|
+
return datetime.fromtimestamp(t, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _parse_kv(items: list[str] | None) -> dict[str, Any]:
|
|
24
|
+
out: dict[str, Any] = {}
|
|
25
|
+
for item in items or []:
|
|
26
|
+
if "=" not in item:
|
|
27
|
+
raise SystemExit(f"--arg expects key=value, got {item!r}")
|
|
28
|
+
k, _, v = item.partition("=")
|
|
29
|
+
try:
|
|
30
|
+
out[k] = json.loads(v)
|
|
31
|
+
except json.JSONDecodeError:
|
|
32
|
+
out[k] = v
|
|
33
|
+
return out
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def cmd_list(store: EpisodeStore, args: argparse.Namespace) -> int:
|
|
37
|
+
rows = store.list(limit=args.limit)
|
|
38
|
+
if args.json:
|
|
39
|
+
print(json.dumps([r.__dict__ for r in rows], indent=2))
|
|
40
|
+
return 0
|
|
41
|
+
if not rows:
|
|
42
|
+
print(f"no episodes in {store.root}")
|
|
43
|
+
return 0
|
|
44
|
+
print(f"{'EPISODE':<28} {'STARTED (UTC)':<20} {'DURATION':>9} {'EVENTS':>7} {'AGENTS':>6} NAME")
|
|
45
|
+
for r in rows:
|
|
46
|
+
flag = "" if r.sampled else " (unsampled)"
|
|
47
|
+
replay = f" replay_of={r.replay_of}" if r.replay_of else ""
|
|
48
|
+
print(
|
|
49
|
+
f"{r.id:<28} {_fmt_time(r.started_at):<20} {r.duration_s:>8.3f}s "
|
|
50
|
+
f"{r.events:>7} {r.agents:>6} {r.name}{flag}{replay}"
|
|
51
|
+
)
|
|
52
|
+
return 0
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def cmd_show(store: EpisodeStore, args: argparse.Namespace) -> int:
|
|
56
|
+
ep = store.load(args.episode)
|
|
57
|
+
if args.json:
|
|
58
|
+
print(ep.to_json(indent=2))
|
|
59
|
+
return 0
|
|
60
|
+
print(ep.summary())
|
|
61
|
+
print(f" entrypoint: {ep.entrypoint or '-'} args={json.dumps(ep.entrypoint_args)}")
|
|
62
|
+
if ep.attributes:
|
|
63
|
+
print(f" attributes: {json.dumps(ep.attributes)}")
|
|
64
|
+
print()
|
|
65
|
+
print(ep.metrics().format())
|
|
66
|
+
if args.events:
|
|
67
|
+
print()
|
|
68
|
+
t0 = ep.started_at
|
|
69
|
+
for e in ep.events:
|
|
70
|
+
d = e.to_dict()
|
|
71
|
+
d.pop("seq", None)
|
|
72
|
+
t = d.pop("t", 0.0)
|
|
73
|
+
typ = d.pop("type")
|
|
74
|
+
agent = d.pop("agent", None)
|
|
75
|
+
fields = ", ".join(f"{k}={_short(v)}" for k, v in d.items() if _visible(k, v))
|
|
76
|
+
print(f" {t - t0:8.3f}s #{e.seq:<4} {typ:<12} {agent or '-':<14} {fields}")
|
|
77
|
+
return 0
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _short(v: Any) -> str:
|
|
81
|
+
s = v if isinstance(v, str) else json.dumps(v, default=str)
|
|
82
|
+
return s if len(s) <= 60 else s[:57] + "..."
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
_HIDDEN_WHEN_FALSE = frozenset({"noop", "replayed"})
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _visible(key: str, value: Any) -> bool:
|
|
89
|
+
"""Hide empty values in the event timeline but keep meaningful ``False`` flags (``hit``,
|
|
90
|
+
``verified``, ``output_recorded``) and zero-valued numbers such as ``index=0``."""
|
|
91
|
+
if value is None or value == "" or value == {} or value == []:
|
|
92
|
+
return False
|
|
93
|
+
return not (value is False and key in _HIDDEN_WHEN_FALSE)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def cmd_graph(store: EpisodeStore, args: argparse.Namespace) -> int:
|
|
97
|
+
g = store.load(args.episode).coordination_graph()
|
|
98
|
+
if args.format == "dot":
|
|
99
|
+
print(g.to_dot())
|
|
100
|
+
elif args.format == "json":
|
|
101
|
+
print(g.to_json())
|
|
102
|
+
else:
|
|
103
|
+
print(g.to_mermaid())
|
|
104
|
+
return 0
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def cmd_metrics(store: EpisodeStore, args: argparse.Namespace) -> int:
|
|
108
|
+
ep = store.load(args.episode)
|
|
109
|
+
m = ep.metrics()
|
|
110
|
+
thresholds = SLOThresholds(
|
|
111
|
+
coordination_overhead_max=args.co_max,
|
|
112
|
+
redundant_action_rate_max=args.rar_max,
|
|
113
|
+
oscillation_rate_max=args.or_max,
|
|
114
|
+
memory_hit_ratio_min=args.mhr_min,
|
|
115
|
+
)
|
|
116
|
+
violations = evaluate(m, thresholds)
|
|
117
|
+
if args.json:
|
|
118
|
+
print(json.dumps({"metrics": m.to_dict(), "violations": [v.__dict__ for v in violations]}, indent=2))
|
|
119
|
+
else:
|
|
120
|
+
print(m.format())
|
|
121
|
+
if violations:
|
|
122
|
+
print("\nSLO violations:")
|
|
123
|
+
for v in violations:
|
|
124
|
+
print(f" ! {v}")
|
|
125
|
+
else:
|
|
126
|
+
print("\nall SLOs within thresholds")
|
|
127
|
+
return 1 if violations and args.fail_on_violation else 0
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def cmd_memory(store: EpisodeStore, args: argparse.Namespace) -> int:
|
|
131
|
+
trace = store.load(args.episode).memory_trace()
|
|
132
|
+
summary = trace.summary()
|
|
133
|
+
if args.json:
|
|
134
|
+
print(json.dumps(summary, indent=2))
|
|
135
|
+
return 0
|
|
136
|
+
for k, v in summary.items():
|
|
137
|
+
print(f"{k:<22} {v}")
|
|
138
|
+
per_agent = trace.by_agent()
|
|
139
|
+
if per_agent:
|
|
140
|
+
print("\nper agent:")
|
|
141
|
+
for agent, t in per_agent.items():
|
|
142
|
+
s = t.summary()
|
|
143
|
+
print(
|
|
144
|
+
f" {agent:<16} accesses={s['accesses']:<4} "
|
|
145
|
+
f"hit_ratio={s['hit_ratio']:.3f} evictions={s['evictions']}"
|
|
146
|
+
)
|
|
147
|
+
return 0
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def cmd_replay(store: EpisodeStore, args: argparse.Namespace) -> int:
|
|
151
|
+
from .tracer import MATrace
|
|
152
|
+
|
|
153
|
+
sys.path.insert(0, os.getcwd())
|
|
154
|
+
tracer = MATrace(store=store)
|
|
155
|
+
if args.exporter and args.exporter != "none":
|
|
156
|
+
from .exporters import build_tracer_provider
|
|
157
|
+
|
|
158
|
+
tracer = MATrace(
|
|
159
|
+
store=store,
|
|
160
|
+
tracer_provider=build_tracer_provider(
|
|
161
|
+
"ma-trace-replay", args.exporter, simple=True, set_global=False
|
|
162
|
+
),
|
|
163
|
+
)
|
|
164
|
+
overrides = _parse_kv(args.arg)
|
|
165
|
+
ep = store.load(args.episode)
|
|
166
|
+
entry_args = dict(ep.entrypoint_args)
|
|
167
|
+
entry_args.update(overrides)
|
|
168
|
+
try:
|
|
169
|
+
report = tracer.replay(ep, args.entrypoint, strict=args.strict, entrypoint_args=entry_args)
|
|
170
|
+
except Exception as exc:
|
|
171
|
+
print(f"replay failed: {exc}", file=sys.stderr)
|
|
172
|
+
return 2
|
|
173
|
+
if args.json:
|
|
174
|
+
print(json.dumps(report.to_dict(), indent=2))
|
|
175
|
+
else:
|
|
176
|
+
print(report.summary())
|
|
177
|
+
return 0 if report.deterministic else 1
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def cmd_diff(store: EpisodeStore, args: argparse.Namespace) -> int:
|
|
181
|
+
a = store.load(args.a)
|
|
182
|
+
b = store.load(args.b)
|
|
183
|
+
ma, mb = a.metrics().to_dict(), b.metrics().to_dict()
|
|
184
|
+
print(f"{'metric':<32} {a.id:<28} {b.id:<28}")
|
|
185
|
+
for key in (
|
|
186
|
+
"coordination_overhead",
|
|
187
|
+
"redundant_action_rate",
|
|
188
|
+
"oscillation_rate",
|
|
189
|
+
"memory_hit_ratio",
|
|
190
|
+
"wall_time_s",
|
|
191
|
+
"llm_calls",
|
|
192
|
+
"tool_calls",
|
|
193
|
+
"coordination_events",
|
|
194
|
+
"agents",
|
|
195
|
+
):
|
|
196
|
+
va, vb = ma[key], mb[key]
|
|
197
|
+
mark = "" if va == vb else " <-- differs"
|
|
198
|
+
fa = f"{va:.3f}" if isinstance(va, float) else str(va)
|
|
199
|
+
fb = f"{vb:.3f}" if isinstance(vb, float) else str(vb)
|
|
200
|
+
print(f"{key:<32} {fa:<28} {fb:<28}{mark}")
|
|
201
|
+
ea = {(s.source, s.target): s.count for s in a.coordination_graph().edge_summaries()}
|
|
202
|
+
eb = {(s.source, s.target): s.count for s in b.coordination_graph().edge_summaries()}
|
|
203
|
+
print("\ncoordination edges:")
|
|
204
|
+
for edge in sorted(set(ea) | set(eb)):
|
|
205
|
+
ca, cb = ea.get(edge, 0), eb.get(edge, 0)
|
|
206
|
+
mark = "" if ca == cb else " <-- differs"
|
|
207
|
+
print(f" {edge[0]} -> {edge[1]:<20} {ca:<6} {cb:<6}{mark}")
|
|
208
|
+
print("\nfirst differing recorded call:")
|
|
209
|
+
for ca_, cb_ in zip(a.calls, b.calls):
|
|
210
|
+
if (ca_.agent, ca_.name, ca_.input_fingerprint, ca_.output_fingerprint) != (
|
|
211
|
+
cb_.agent,
|
|
212
|
+
cb_.name,
|
|
213
|
+
cb_.input_fingerprint,
|
|
214
|
+
cb_.output_fingerprint,
|
|
215
|
+
):
|
|
216
|
+
print(
|
|
217
|
+
f" #{ca_.index} {ca_.agent}/{ca_.name}: "
|
|
218
|
+
f"in {ca_.input_fingerprint[:12]}->{cb_.input_fingerprint[:12]} "
|
|
219
|
+
f"out {str(ca_.output_fingerprint)[:12]}->{str(cb_.output_fingerprint)[:12]}"
|
|
220
|
+
)
|
|
221
|
+
break
|
|
222
|
+
else:
|
|
223
|
+
if len(a.calls) != len(b.calls):
|
|
224
|
+
print(f" call counts differ: {len(a.calls)} vs {len(b.calls)}")
|
|
225
|
+
else:
|
|
226
|
+
print(" none")
|
|
227
|
+
return 0
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def cmd_export(store: EpisodeStore, args: argparse.Namespace) -> int:
|
|
231
|
+
ep = store.load(args.episode)
|
|
232
|
+
text = ep.to_json(indent=2)
|
|
233
|
+
if args.out:
|
|
234
|
+
with open(args.out, "w", encoding="utf-8") as fh:
|
|
235
|
+
fh.write(text)
|
|
236
|
+
print(f"wrote {args.out}")
|
|
237
|
+
else:
|
|
238
|
+
print(text)
|
|
239
|
+
return 0
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def cmd_import(store: EpisodeStore, args: argparse.Namespace) -> int:
|
|
243
|
+
with open(args.file, encoding="utf-8") as fh:
|
|
244
|
+
ep = Episode.from_json(fh.read())
|
|
245
|
+
path = store.save(ep)
|
|
246
|
+
print(f"imported {ep.id} -> {path}")
|
|
247
|
+
return 0
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def cmd_delete(store: EpisodeStore, args: argparse.Namespace) -> int:
|
|
251
|
+
episode_id = store.resolve(args.episode)
|
|
252
|
+
if not args.yes:
|
|
253
|
+
answer = input(f"delete {episode_id}? [y/N] ").strip().lower()
|
|
254
|
+
if answer not in ("y", "yes"):
|
|
255
|
+
print("aborted")
|
|
256
|
+
return 1
|
|
257
|
+
store.delete(episode_id)
|
|
258
|
+
print(f"deleted {episode_id}")
|
|
259
|
+
return 0
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
263
|
+
p = argparse.ArgumentParser(prog="ma-trace", description="Inspect, analyse and replay MA-Trace episodes.")
|
|
264
|
+
p.add_argument(
|
|
265
|
+
"--store", help="episode store directory (default: $MA_TRACE_STORE or ./.ma-trace/episodes)"
|
|
266
|
+
)
|
|
267
|
+
p.add_argument("--version", action="version", version=f"ma-trace {__version__}")
|
|
268
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
269
|
+
|
|
270
|
+
s = sub.add_parser("list", help="list recorded episodes")
|
|
271
|
+
s.add_argument("--limit", type=int, default=None)
|
|
272
|
+
s.add_argument("--json", action="store_true")
|
|
273
|
+
s.set_defaults(func=cmd_list)
|
|
274
|
+
|
|
275
|
+
s = sub.add_parser("show", help="show an episode's summary, metrics and (optionally) events")
|
|
276
|
+
s.add_argument("episode", help="episode id, unique prefix, or 'latest'")
|
|
277
|
+
s.add_argument("--events", action="store_true", help="print the event timeline")
|
|
278
|
+
s.add_argument("--json", action="store_true", help="dump the full episode as JSON")
|
|
279
|
+
s.set_defaults(func=cmd_show)
|
|
280
|
+
|
|
281
|
+
s = sub.add_parser("graph", help="print the coordination graph")
|
|
282
|
+
s.add_argument("episode")
|
|
283
|
+
s.add_argument("--format", choices=["mermaid", "dot", "json"], default="mermaid")
|
|
284
|
+
s.set_defaults(func=cmd_graph)
|
|
285
|
+
|
|
286
|
+
s = sub.add_parser("metrics", help="compute the SLO metrics and check thresholds")
|
|
287
|
+
s.add_argument("episode")
|
|
288
|
+
s.add_argument("--json", action="store_true")
|
|
289
|
+
s.add_argument("--co-max", type=float, default=SLOThresholds.coordination_overhead_max)
|
|
290
|
+
s.add_argument("--rar-max", type=float, default=SLOThresholds.redundant_action_rate_max)
|
|
291
|
+
s.add_argument("--or-max", type=float, default=SLOThresholds.oscillation_rate_max)
|
|
292
|
+
s.add_argument("--mhr-min", type=float, default=None)
|
|
293
|
+
s.add_argument("--fail-on-violation", action="store_true", help="exit 1 if any SLO is violated")
|
|
294
|
+
s.set_defaults(func=cmd_metrics)
|
|
295
|
+
|
|
296
|
+
s = sub.add_parser("memory", help="summarise memory operations")
|
|
297
|
+
s.add_argument("episode")
|
|
298
|
+
s.add_argument("--json", action="store_true")
|
|
299
|
+
s.set_defaults(func=cmd_memory)
|
|
300
|
+
|
|
301
|
+
s = sub.add_parser("replay", help="deterministically re-execute an episode")
|
|
302
|
+
s.add_argument("episode")
|
|
303
|
+
s.add_argument(
|
|
304
|
+
"--entrypoint", help="'package.module:function' (default: the episode's recorded entrypoint)"
|
|
305
|
+
)
|
|
306
|
+
s.add_argument(
|
|
307
|
+
"--arg", action="append", help="override an entrypoint argument: key=value (JSON values accepted)"
|
|
308
|
+
)
|
|
309
|
+
s.add_argument("--strict", action="store_true", help="stop at the first divergence")
|
|
310
|
+
s.add_argument(
|
|
311
|
+
"--exporter", choices=["none", "console"], default="none", help="also export the replay's spans"
|
|
312
|
+
)
|
|
313
|
+
s.add_argument("--json", action="store_true")
|
|
314
|
+
s.set_defaults(func=cmd_replay)
|
|
315
|
+
|
|
316
|
+
s = sub.add_parser("diff", help="compare two episodes")
|
|
317
|
+
s.add_argument("a")
|
|
318
|
+
s.add_argument("b")
|
|
319
|
+
s.set_defaults(func=cmd_diff)
|
|
320
|
+
|
|
321
|
+
s = sub.add_parser("export", help="write an episode as a JSON file")
|
|
322
|
+
s.add_argument("episode")
|
|
323
|
+
s.add_argument("-o", "--out")
|
|
324
|
+
s.set_defaults(func=cmd_export)
|
|
325
|
+
|
|
326
|
+
s = sub.add_parser("import", help="import an exported episode JSON file into the store")
|
|
327
|
+
s.add_argument("file")
|
|
328
|
+
s.set_defaults(func=cmd_import)
|
|
329
|
+
|
|
330
|
+
s = sub.add_parser("delete", help="delete an episode")
|
|
331
|
+
s.add_argument("episode")
|
|
332
|
+
s.add_argument("--yes", "-y", action="store_true")
|
|
333
|
+
s.set_defaults(func=cmd_delete)
|
|
334
|
+
return p
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def main(argv: list[str] | None = None) -> int:
|
|
338
|
+
parser = build_parser()
|
|
339
|
+
args = parser.parse_args(argv)
|
|
340
|
+
store = EpisodeStore(args.store)
|
|
341
|
+
try:
|
|
342
|
+
return int(args.func(store, args))
|
|
343
|
+
except KeyError as exc:
|
|
344
|
+
print(f"error: {exc.args[0] if exc.args else exc}", file=sys.stderr)
|
|
345
|
+
return 2
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
if __name__ == "__main__": # pragma: no cover
|
|
349
|
+
sys.exit(main())
|
ma_trace/context.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Context variables shared between the tracer, decorators and replay engine."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from contextvars import ContextVar
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
10
|
+
from .episode import Episode
|
|
11
|
+
from .replay import ReplaySession
|
|
12
|
+
|
|
13
|
+
_current_episode: ContextVar[Episode | None] = ContextVar("ma_trace_episode", default=None)
|
|
14
|
+
_current_agent: ContextVar[str | None] = ContextVar("ma_trace_agent", default=None)
|
|
15
|
+
_current_replay: ContextVar[ReplaySession | None] = ContextVar("ma_trace_replay", default=None)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def current_episode() -> Episode | None:
|
|
19
|
+
"""The episode open in the current context (thread / task), if any."""
|
|
20
|
+
return _current_episode.get()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def current_agent() -> str | None:
|
|
24
|
+
"""The innermost agent whose span is active in the current context."""
|
|
25
|
+
return _current_agent.get()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def current_replay() -> ReplaySession | None:
|
|
29
|
+
return _current_replay.get()
|
ma_trace/contracts.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Environment contracts: seed-controlled, verifiable pre/post-conditions for actions."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .events import ContractEvent, fingerprint
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def state_fingerprint(state: Any) -> str:
|
|
13
|
+
"""Stable SHA-256 fingerprint of an environment/agent state (see :func:`ma_trace.events.fingerprint`)."""
|
|
14
|
+
return fingerprint(state)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class ContractCheck:
|
|
19
|
+
"""Outcome of verifying a live contract against a recorded one during replay."""
|
|
20
|
+
|
|
21
|
+
agent: str
|
|
22
|
+
action: str
|
|
23
|
+
pre_match: bool
|
|
24
|
+
post_match: bool | None
|
|
25
|
+
recorded_pre: str
|
|
26
|
+
recorded_post: str | None
|
|
27
|
+
actual_pre: str
|
|
28
|
+
actual_post: str | None
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def ok(self) -> bool:
|
|
32
|
+
return self.pre_match and (self.post_match is None or self.post_match)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Contract:
|
|
37
|
+
"""A live contract handle yielded by ``tracer.contract(...)``.
|
|
38
|
+
|
|
39
|
+
Capture the state before the action, run the action, then call
|
|
40
|
+
:meth:`set_post_state` (and optionally :meth:`set_result`). The tracer records a
|
|
41
|
+
:class:`~ma_trace.events.ContractEvent` on exit. Under replay the pre- and
|
|
42
|
+
post-state hashes are compared with the recorded ones.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
agent: str
|
|
46
|
+
action: str
|
|
47
|
+
pre_hash: str
|
|
48
|
+
seed: int | None = None
|
|
49
|
+
post_hash: str | None = None
|
|
50
|
+
result: str | None = None
|
|
51
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
52
|
+
recorded: ContractEvent | None = None # the recorded counterpart under replay
|
|
53
|
+
check: ContractCheck | None = None
|
|
54
|
+
|
|
55
|
+
@classmethod
|
|
56
|
+
def begin(
|
|
57
|
+
cls, agent: str, action: str, pre_state: Any, *, seed: int | None = None, **metadata: Any
|
|
58
|
+
) -> Contract:
|
|
59
|
+
return cls(
|
|
60
|
+
agent=agent, action=action, pre_hash=state_fingerprint(pre_state), seed=seed, metadata=metadata
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
def set_post_state(self, state: Any) -> None:
|
|
64
|
+
self.post_hash = state_fingerprint(state)
|
|
65
|
+
|
|
66
|
+
def set_result(self, result: Any) -> None:
|
|
67
|
+
self.result = result if isinstance(result, str) else repr(result)
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def expected_post_hash(self) -> str | None:
|
|
71
|
+
"""Under replay: the post-state hash the recorded run produced."""
|
|
72
|
+
return self.recorded.post_hash if self.recorded is not None else None
|
|
73
|
+
|
|
74
|
+
def verify(self) -> ContractCheck | None:
|
|
75
|
+
if self.recorded is None:
|
|
76
|
+
return None
|
|
77
|
+
post_match: bool | None
|
|
78
|
+
if self.post_hash is None or self.recorded.post_hash is None:
|
|
79
|
+
post_match = None
|
|
80
|
+
else:
|
|
81
|
+
post_match = self.post_hash == self.recorded.post_hash
|
|
82
|
+
self.check = ContractCheck(
|
|
83
|
+
agent=self.agent,
|
|
84
|
+
action=self.action,
|
|
85
|
+
pre_match=self.pre_hash == self.recorded.pre_hash,
|
|
86
|
+
post_match=post_match,
|
|
87
|
+
recorded_pre=self.recorded.pre_hash,
|
|
88
|
+
recorded_post=self.recorded.post_hash,
|
|
89
|
+
actual_pre=self.pre_hash,
|
|
90
|
+
actual_post=self.post_hash,
|
|
91
|
+
)
|
|
92
|
+
return self.check
|
|
93
|
+
|
|
94
|
+
def to_event(self) -> ContractEvent:
|
|
95
|
+
verified: bool | None = None
|
|
96
|
+
if self.check is not None:
|
|
97
|
+
verified = self.check.ok
|
|
98
|
+
return ContractEvent(
|
|
99
|
+
agent=self.agent,
|
|
100
|
+
action=self.action,
|
|
101
|
+
pre_hash=self.pre_hash,
|
|
102
|
+
post_hash=self.post_hash,
|
|
103
|
+
seed=self.seed,
|
|
104
|
+
result=self.result,
|
|
105
|
+
verified=verified,
|
|
106
|
+
metadata=dict(self.metadata),
|
|
107
|
+
)
|
ma_trace/episode.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""The :class:`Episode` container: one traced run of a multi-agent workflow."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import random
|
|
8
|
+
import secrets
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from typing import TYPE_CHECKING, Any, TypeVar
|
|
14
|
+
|
|
15
|
+
from .events import (
|
|
16
|
+
ActionEvent,
|
|
17
|
+
AgentEvent,
|
|
18
|
+
CallEvent,
|
|
19
|
+
ContractEvent,
|
|
20
|
+
CoordinationEvent,
|
|
21
|
+
Event,
|
|
22
|
+
MemoryEvent,
|
|
23
|
+
StateEvent,
|
|
24
|
+
event_from_dict,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
28
|
+
from .graph import CoordinationGraph
|
|
29
|
+
from .memory import MemoryTrace
|
|
30
|
+
from .metrics import SLOMetrics
|
|
31
|
+
|
|
32
|
+
SCHEMA_VERSION = 1
|
|
33
|
+
E = TypeVar("E", bound=Event)
|
|
34
|
+
|
|
35
|
+
_clock_lock = threading.Lock()
|
|
36
|
+
_last_wall_time = 0.0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _wall_time() -> float:
|
|
40
|
+
"""``time.time()``, but strictly increasing within the process.
|
|
41
|
+
|
|
42
|
+
Wall clocks can advance in coarse steps (about 16 ms on Windows before Python 3.13), so
|
|
43
|
+
episodes and events recorded back to back would otherwise share a timestamp, and the order
|
|
44
|
+
of ``latest`` and ``ma-trace list`` would depend on the random part of the episode id.
|
|
45
|
+
"""
|
|
46
|
+
global _last_wall_time
|
|
47
|
+
with _clock_lock:
|
|
48
|
+
now = time.time()
|
|
49
|
+
_last_wall_time = now if now > _last_wall_time else _last_wall_time + 1e-6
|
|
50
|
+
return _last_wall_time
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class Episode:
|
|
55
|
+
"""An ordered record of everything that happened during one workflow run."""
|
|
56
|
+
|
|
57
|
+
id: str
|
|
58
|
+
name: str
|
|
59
|
+
seed: int | None = None
|
|
60
|
+
started_at: float = field(default_factory=_wall_time)
|
|
61
|
+
ended_at: float | None = None
|
|
62
|
+
entrypoint: str | None = None
|
|
63
|
+
entrypoint_args: dict[str, Any] = field(default_factory=dict)
|
|
64
|
+
attributes: dict[str, Any] = field(default_factory=dict)
|
|
65
|
+
events: list[Event] = field(default_factory=list)
|
|
66
|
+
sampled: bool = True
|
|
67
|
+
replay_of: str | None = None
|
|
68
|
+
schema_version: int = SCHEMA_VERSION
|
|
69
|
+
rng: random.Random | None = field(default=None, repr=False, compare=False)
|
|
70
|
+
|
|
71
|
+
# -- construction -------------------------------------------------------
|
|
72
|
+
|
|
73
|
+
@staticmethod
|
|
74
|
+
def new_id(now: float | None = None) -> str:
|
|
75
|
+
stamp = datetime.fromtimestamp(now or time.time(), tz=timezone.utc).strftime("%Y%m%d-%H%M%S")
|
|
76
|
+
return f"ep-{stamp}-{secrets.token_hex(3)}"
|
|
77
|
+
|
|
78
|
+
# -- accessors ----------------------------------------------------------
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def duration_s(self) -> float:
|
|
82
|
+
end = self.ended_at if self.ended_at is not None else time.time()
|
|
83
|
+
return max(0.0, end - self.started_at)
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def finished(self) -> bool:
|
|
87
|
+
return self.ended_at is not None
|
|
88
|
+
|
|
89
|
+
def events_of(self, cls: type[E]) -> list[E]:
|
|
90
|
+
return [e for e in self.events if isinstance(e, cls)]
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def coordination_events(self) -> list[CoordinationEvent]:
|
|
94
|
+
return self.events_of(CoordinationEvent)
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def memory_events(self) -> list[MemoryEvent]:
|
|
98
|
+
return self.events_of(MemoryEvent)
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def contract_events(self) -> list[ContractEvent]:
|
|
102
|
+
return self.events_of(ContractEvent)
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def calls(self) -> list[CallEvent]:
|
|
106
|
+
return self.events_of(CallEvent)
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def actions(self) -> list[ActionEvent]:
|
|
110
|
+
return self.events_of(ActionEvent)
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def states(self) -> list[StateEvent]:
|
|
114
|
+
return self.events_of(StateEvent)
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def agents(self) -> list[str]:
|
|
118
|
+
"""Agents that appear anywhere in the episode, in first-seen order."""
|
|
119
|
+
seen: dict[str, None] = {}
|
|
120
|
+
for e in self.events:
|
|
121
|
+
if e.agent:
|
|
122
|
+
seen.setdefault(e.agent, None)
|
|
123
|
+
if isinstance(e, CoordinationEvent):
|
|
124
|
+
seen.setdefault(e.source, None)
|
|
125
|
+
seen.setdefault(e.target, None)
|
|
126
|
+
return list(seen)
|
|
127
|
+
|
|
128
|
+
def agent_durations(self) -> dict[str, float]:
|
|
129
|
+
totals: dict[str, float] = {}
|
|
130
|
+
for e in self.events_of(AgentEvent):
|
|
131
|
+
if e.phase == "end" and e.agent and e.duration_s is not None:
|
|
132
|
+
totals[e.agent] = totals.get(e.agent, 0.0) + e.duration_s
|
|
133
|
+
return totals
|
|
134
|
+
|
|
135
|
+
# -- derived views ------------------------------------------------------
|
|
136
|
+
|
|
137
|
+
def coordination_graph(self) -> CoordinationGraph:
|
|
138
|
+
from .graph import CoordinationGraph
|
|
139
|
+
|
|
140
|
+
return CoordinationGraph.from_events(self.coordination_events)
|
|
141
|
+
|
|
142
|
+
def memory_trace(self) -> MemoryTrace:
|
|
143
|
+
from .memory import MemoryTrace
|
|
144
|
+
|
|
145
|
+
return MemoryTrace(self.memory_events)
|
|
146
|
+
|
|
147
|
+
def metrics(self) -> SLOMetrics:
|
|
148
|
+
from .metrics import compute_metrics
|
|
149
|
+
|
|
150
|
+
return compute_metrics(self)
|
|
151
|
+
|
|
152
|
+
# -- (de)serialisation --------------------------------------------------
|
|
153
|
+
|
|
154
|
+
def to_dict(self) -> dict[str, Any]:
|
|
155
|
+
return {
|
|
156
|
+
"schema_version": self.schema_version,
|
|
157
|
+
"id": self.id,
|
|
158
|
+
"name": self.name,
|
|
159
|
+
"seed": self.seed,
|
|
160
|
+
"started_at": self.started_at,
|
|
161
|
+
"ended_at": self.ended_at,
|
|
162
|
+
"entrypoint": self.entrypoint,
|
|
163
|
+
"entrypoint_args": self.entrypoint_args,
|
|
164
|
+
"attributes": self.attributes,
|
|
165
|
+
"sampled": self.sampled,
|
|
166
|
+
"replay_of": self.replay_of,
|
|
167
|
+
"events": [e.to_dict() for e in self.events],
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
@classmethod
|
|
171
|
+
def from_dict(cls, data: dict[str, Any]) -> Episode:
|
|
172
|
+
ep = cls(
|
|
173
|
+
id=data["id"],
|
|
174
|
+
name=data.get("name", ""),
|
|
175
|
+
seed=data.get("seed"),
|
|
176
|
+
started_at=data.get("started_at", 0.0),
|
|
177
|
+
ended_at=data.get("ended_at"),
|
|
178
|
+
entrypoint=data.get("entrypoint"),
|
|
179
|
+
entrypoint_args=dict(data.get("entrypoint_args") or {}),
|
|
180
|
+
attributes=dict(data.get("attributes") or {}),
|
|
181
|
+
sampled=bool(data.get("sampled", True)),
|
|
182
|
+
replay_of=data.get("replay_of"),
|
|
183
|
+
schema_version=int(data.get("schema_version", SCHEMA_VERSION)),
|
|
184
|
+
)
|
|
185
|
+
ep.events = [event_from_dict(e) for e in data.get("events", [])]
|
|
186
|
+
if ep.seed is not None:
|
|
187
|
+
ep.rng = random.Random(ep.seed)
|
|
188
|
+
return ep
|
|
189
|
+
|
|
190
|
+
def to_json(self, indent: int | None = None) -> str:
|
|
191
|
+
return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False)
|
|
192
|
+
|
|
193
|
+
@classmethod
|
|
194
|
+
def from_json(cls, text: str) -> Episode:
|
|
195
|
+
return cls.from_dict(json.loads(text))
|
|
196
|
+
|
|
197
|
+
def summary(self) -> str:
|
|
198
|
+
counts: dict[str, int] = {}
|
|
199
|
+
for e in self.events:
|
|
200
|
+
counts[e.type] = counts.get(e.type, 0) + 1
|
|
201
|
+
parts = ", ".join(f"{k}={v}" for k, v in sorted(counts.items()))
|
|
202
|
+
started = datetime.fromtimestamp(self.started_at, tz=timezone.utc).isoformat(timespec="seconds")
|
|
203
|
+
seed = f" seed={self.seed}" if self.seed is not None else ""
|
|
204
|
+
replay = f" replay_of={self.replay_of}" if self.replay_of else ""
|
|
205
|
+
return (
|
|
206
|
+
f"{self.id} {self.name!r} started={started} duration={self.duration_s:.3f}s"
|
|
207
|
+
f"{seed}{replay} agents={len(self.agents)} events[{parts}]"
|
|
208
|
+
)
|