agentflight-sdk 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.
Files changed (49) hide show
  1. agentflight/__init__.py +59 -0
  2. agentflight/_queue.py +234 -0
  3. agentflight/_spool.py +280 -0
  4. agentflight/attributes.py +68 -0
  5. agentflight/exporter.py +272 -0
  6. agentflight/integrations/__init__.py +5 -0
  7. agentflight/integrations/langgraph.py +369 -0
  8. agentflight/integrations/openai.py +172 -0
  9. agentflight/py.typed +0 -0
  10. agentflight/replayer.py +436 -0
  11. agentflight/sdk.py +803 -0
  12. agentflight/server/__init__.py +5 -0
  13. agentflight/server/app.py +176 -0
  14. agentflight/server/auth.py +87 -0
  15. agentflight/server/cli.py +95 -0
  16. agentflight/server/db.py +41 -0
  17. agentflight/server/limits.py +115 -0
  18. agentflight/server/main.py +5 -0
  19. agentflight/server/migrations/env.py +38 -0
  20. agentflight/server/migrations/script.py.mako +22 -0
  21. agentflight/server/migrations/versions/0001_initial.py +58 -0
  22. agentflight/server/migrations/versions/0002_event_columns_run_totals.py +168 -0
  23. agentflight/server/migrations/versions/0003_unset_status_unknown.py +47 -0
  24. agentflight/server/migrations/versions/0004_run_dropped_spans.py +29 -0
  25. agentflight/server/models.py +81 -0
  26. agentflight/server/schemas.py +91 -0
  27. agentflight/server/service.py +483 -0
  28. agentflight/server/settings.py +198 -0
  29. agentflight/server/viewer/__init__.py +11 -0
  30. agentflight/server/viewer/format.py +180 -0
  31. agentflight/server/viewer/routes.py +293 -0
  32. agentflight/server/viewer/session.py +120 -0
  33. agentflight/server/viewer/static/VENDORED.md +32 -0
  34. agentflight/server/viewer/static/htmx-2.0.11.min.js +1 -0
  35. agentflight/server/viewer/static/viewer.css +104 -0
  36. agentflight/server/viewer/templates/_event.html +36 -0
  37. agentflight/server/viewer/templates/_runs_table.html +35 -0
  38. agentflight/server/viewer/templates/_timeline_rows.html +25 -0
  39. agentflight/server/viewer/templates/base.html +26 -0
  40. agentflight/server/viewer/templates/event.html +6 -0
  41. agentflight/server/viewer/templates/login.html +14 -0
  42. agentflight/server/viewer/templates/not_found.html +6 -0
  43. agentflight/server/viewer/templates/run.html +45 -0
  44. agentflight/server/viewer/templates/runs.html +31 -0
  45. agentflight_sdk-0.1.0.dist-info/METADATA +836 -0
  46. agentflight_sdk-0.1.0.dist-info/RECORD +49 -0
  47. agentflight_sdk-0.1.0.dist-info/WHEEL +4 -0
  48. agentflight_sdk-0.1.0.dist-info/entry_points.txt +2 -0
  49. agentflight_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,59 @@
1
+ """AgentFlight: a black box recorder for AI agents."""
2
+
3
+ from agentflight.exporter import AgentFlightExporter
4
+ from agentflight.replayer import (
5
+ ForkSession,
6
+ Recording,
7
+ ReplayDivergence,
8
+ ReplayedError,
9
+ ReplayError,
10
+ ReplaySession,
11
+ fork,
12
+ replay,
13
+ )
14
+ from agentflight.sdk import (
15
+ LLMCall,
16
+ Recorder,
17
+ RunHandle,
18
+ configure,
19
+ decision,
20
+ error,
21
+ failure_id,
22
+ flush,
23
+ get_recorder,
24
+ llm_call,
25
+ redact_fields,
26
+ run,
27
+ shutdown,
28
+ state_change,
29
+ tool,
30
+ )
31
+
32
+ __all__ = [
33
+ "AgentFlightExporter",
34
+ "ForkSession",
35
+ "LLMCall",
36
+ "Recorder",
37
+ "Recording",
38
+ "ReplayDivergence",
39
+ "ReplayError",
40
+ "ReplaySession",
41
+ "ReplayedError",
42
+ "RunHandle",
43
+ "configure",
44
+ "decision",
45
+ "error",
46
+ "failure_id",
47
+ "flush",
48
+ "fork",
49
+ "get_recorder",
50
+ "llm_call",
51
+ "redact_fields",
52
+ "replay",
53
+ "run",
54
+ "shutdown",
55
+ "state_change",
56
+ "tool",
57
+ ]
58
+
59
+ __version__ = "0.1.0"
agentflight/_queue.py ADDED
@@ -0,0 +1,234 @@
1
+ """Admission control in front of OpenTelemetry's batch span processor.
2
+
3
+ OpenTelemetry drops spans silently-ish when its queue is full (and, in 1.45, drops the
4
+ *oldest* queued span, which can belong to another run). AgentFlight keeps its own count
5
+ of spans waiting for export and refuses new ones itself before that queue can overflow,
6
+ so every drop is known: it is counted per run (recorded on the run span when the run
7
+ ends) and in total.
8
+
9
+ Run spans don't use that queue at all. They go to a small lane of their own, sent by a
10
+ dedicated thread as soon as they end, so a run whose other spans were dropped still
11
+ closes on the server and carries its drop count.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import logging
17
+ import os
18
+ import threading
19
+ import weakref
20
+ from collections import deque
21
+ from collections.abc import Callable, Sequence
22
+ from typing import Any
23
+
24
+ from opentelemetry.context import Context
25
+ from opentelemetry.sdk.trace import ReadableSpan, Span, SpanProcessor
26
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor, SpanExporter, SpanExportResult
27
+
28
+ from agentflight import attributes as A
29
+
30
+ logger = logging.getLogger("agentflight")
31
+
32
+ RUN_LANE_SIZE = 1024
33
+ """Run spans waiting to be sent before new ones are dropped (each is one ended run)."""
34
+
35
+ RUN_LANE_BATCH = 512
36
+ """Run spans sent in one request when several are waiting."""
37
+
38
+
39
+ class _Counted(SpanExporter):
40
+ """Wraps the real exporter: a batch handed to it has left the queue."""
41
+
42
+ def __init__(self, inner: SpanExporter, left_queue: Any, lock: threading.Lock) -> None:
43
+ self._inner = inner
44
+ self._left_queue = left_queue
45
+ self._lock = lock
46
+
47
+ def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
48
+ self._left_queue(len(spans))
49
+ with self._lock:
50
+ return self._inner.export(spans)
51
+
52
+ def shutdown(self) -> None:
53
+ self._inner.shutdown()
54
+
55
+ def force_flush(self, timeout_millis: int = 30_000) -> bool:
56
+ return self._inner.force_flush(timeout_millis)
57
+
58
+
59
+ class _RunLane:
60
+ """A bounded lane for run spans with its own sender thread.
61
+
62
+ ``submit`` only appends under a lock, so the agent thread never waits on the network
63
+ here. The thread starts with the first run span (and again in a forked child).
64
+ """
65
+
66
+ def __init__(self, send: Callable[[list[ReadableSpan]], None], *, capacity: int) -> None:
67
+ self._send = send
68
+ self._capacity = capacity
69
+ self._reset()
70
+ _lanes.add(self)
71
+
72
+ def _reset(self) -> None:
73
+ self._items: deque[ReadableSpan] = deque()
74
+ self._cond = threading.Condition()
75
+ self._busy = False
76
+ self._closed = False
77
+ self._thread: threading.Thread | None = None
78
+
79
+ def submit(self, span: ReadableSpan) -> bool:
80
+ """Queue ``span`` for sending; False if the lane is full or shut down."""
81
+ with self._cond:
82
+ if self._closed or len(self._items) >= self._capacity:
83
+ return False
84
+ self._items.append(span)
85
+ if self._thread is None:
86
+ self._thread = threading.Thread(
87
+ target=self._worker, name="agentflight-run-spans", daemon=True
88
+ )
89
+ self._thread.start()
90
+ self._cond.notify()
91
+ return True
92
+
93
+ def _worker(self) -> None:
94
+ while True:
95
+ with self._cond:
96
+ while not self._items and not self._closed:
97
+ self._cond.wait()
98
+ if not self._items:
99
+ return
100
+ batch = [
101
+ self._items.popleft() for _ in range(min(RUN_LANE_BATCH, len(self._items)))
102
+ ]
103
+ self._busy = True
104
+ try:
105
+ self._send(batch)
106
+ except Exception:
107
+ logger.warning(
108
+ "agentflight: failed to send %d run spans", len(batch), exc_info=True
109
+ )
110
+ finally:
111
+ with self._cond:
112
+ self._busy = False
113
+ self._cond.notify_all()
114
+
115
+ def flush(self, timeout_s: float) -> bool:
116
+ """Wait at most ``timeout_s`` until every queued run span has been sent."""
117
+ with self._cond:
118
+ return self._cond.wait_for(lambda: not self._items and not self._busy, timeout_s)
119
+
120
+ def shutdown(self, timeout_s: float) -> None:
121
+ with self._cond:
122
+ self._closed = True
123
+ self._cond.notify_all()
124
+ thread = self._thread
125
+ if thread is not None:
126
+ thread.join(timeout_s)
127
+
128
+
129
+ _lanes: weakref.WeakSet[_RunLane] = weakref.WeakSet()
130
+
131
+
132
+ def _reset_lanes_after_fork() -> None:
133
+ for lane in list(_lanes):
134
+ lane._reset()
135
+
136
+
137
+ if hasattr(os, "register_at_fork"):
138
+ os.register_at_fork(after_in_child=_reset_lanes_after_fork)
139
+
140
+
141
+ class DropCountingBatchProcessor(SpanProcessor):
142
+ """A ``BatchSpanProcessor`` that never overflows and counts what it refuses.
143
+
144
+ Run spans skip the batch queue and go to their own lane (see the module docstring),
145
+ so the span that carries a run's drop count isn't competing with the spans it counts.
146
+ The wrapped exporter is only ever called by one thread at a time.
147
+ """
148
+
149
+ def __init__(
150
+ self,
151
+ exporter: SpanExporter,
152
+ *,
153
+ max_queue_size: int,
154
+ max_export_batch_size: int,
155
+ run_span_deadline_s: float = 5.0,
156
+ ) -> None:
157
+ self.max_queue_size = max_queue_size
158
+ self.run_span_deadline_s = run_span_deadline_s
159
+ self.dropped_total = 0
160
+ self._exporter = exporter
161
+ self._export_lock = threading.Lock()
162
+ self._pending = 0
163
+ self._lock = threading.Lock()
164
+ self._open_runs: dict[int, int] = {} # trace id -> spans dropped so far
165
+ self._warned = False
166
+ self.inner = BatchSpanProcessor(
167
+ _Counted(exporter, self._left_queue, self._export_lock),
168
+ max_queue_size=max_queue_size,
169
+ max_export_batch_size=max_export_batch_size,
170
+ )
171
+ self.runs = _RunLane(self._send_run_spans, capacity=RUN_LANE_SIZE)
172
+
173
+ def _left_queue(self, n: int) -> None:
174
+ with self._lock:
175
+ self._pending = max(0, self._pending - n)
176
+
177
+ def _send_run_spans(self, spans: list[ReadableSpan]) -> None:
178
+ within = getattr(self._exporter, "export_within", None)
179
+ with self._export_lock:
180
+ if callable(within):
181
+ within(spans, self.run_span_deadline_s)
182
+ else:
183
+ self._exporter.export(spans)
184
+
185
+ def open_run(self, trace_id: int) -> None:
186
+ with self._lock:
187
+ self._open_runs.setdefault(trace_id, 0)
188
+
189
+ def close_run(self, trace_id: int) -> int:
190
+ """Stop counting for a run; returns the spans of it dropped so far."""
191
+ with self._lock:
192
+ return self._open_runs.pop(trace_id, 0)
193
+
194
+ def on_start(self, span: Span, parent_context: Context | None = None) -> None:
195
+ self.inner.on_start(span, parent_context=parent_context)
196
+
197
+ def on_end(self, span: ReadableSpan) -> None:
198
+ if (span.attributes or {}).get(A.KIND) == A.RUN:
199
+ if self.runs.submit(span):
200
+ return
201
+ self._dropped(span) # the run lane is full: very many runs ending at once
202
+ return
203
+ with self._lock:
204
+ admit = self._pending < self.max_queue_size
205
+ if admit:
206
+ self._pending += 1
207
+ if admit:
208
+ self.inner.on_end(span)
209
+ else:
210
+ self._dropped(span)
211
+
212
+ def _dropped(self, span: ReadableSpan) -> None:
213
+ with self._lock:
214
+ self.dropped_total += 1
215
+ ctx = span.get_span_context()
216
+ trace_id = ctx.trace_id if ctx is not None else 0
217
+ if trace_id in self._open_runs:
218
+ self._open_runs[trace_id] += 1
219
+ warn = not self._warned
220
+ self._warned = True
221
+ if warn:
222
+ logger.warning(
223
+ "agentflight: export queue full (%d spans); dropping spans. Runs record "
224
+ "how many they lost; raise max_queue_size or check the server.",
225
+ self.max_queue_size,
226
+ )
227
+
228
+ def shutdown(self) -> None:
229
+ self.runs.shutdown(30.0)
230
+ self.inner.shutdown() # type: ignore[no-untyped-call]
231
+
232
+ def force_flush(self, timeout_millis: int = 30_000) -> bool:
233
+ runs_sent = self.runs.flush(timeout_millis / 1000)
234
+ return self.inner.force_flush(timeout_millis) and runs_sent
agentflight/_spool.py ADDED
@@ -0,0 +1,280 @@
1
+ """A bounded on-disk spool for spans that couldn't be exported.
2
+
3
+ When an export fails in a way that may work later (server down, timeout, 5xx, 429,
4
+ credentials), the spans that weren't stored are written to the spool directory, one file
5
+ per failed batch, and sent again at the start of a later export, oldest first. The spool
6
+ is bounded by total size and by age; when it is full, the oldest files are deleted.
7
+
8
+ Files are JSON (``{"v": 1, "spans": [...]}``), the same span JSON ``POST /v1/spans``
9
+ accepts, so they hold recorded payloads after ``redact``. The directory is created
10
+ ``0700`` and files ``0600``. Every operation is fail-open: a full disk, a directory that
11
+ can't be written or a corrupt file loses those spans (counted in ``dropped`` and logged
12
+ once per kind of problem) and never raises.
13
+
14
+ Spool I/O happens on the exporter's thread only; the agent's thread never touches it.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import contextlib
20
+ import errno
21
+ import itertools
22
+ import json
23
+ import logging
24
+ import os
25
+ import stat
26
+ import threading
27
+ import time
28
+ from collections.abc import Generator
29
+ from dataclasses import dataclass
30
+ from pathlib import Path
31
+ from typing import Any
32
+
33
+ logger = logging.getLogger("agentflight")
34
+
35
+ DEFAULT_SPOOL_MAX_BYTES = 64 * 1024 * 1024
36
+ DEFAULT_SPOOL_MAX_AGE_SECONDS = 24 * 3600
37
+ MAX_FILES = 10_000
38
+ """A hard cap on files, so listing the directory stays cheap whatever their size."""
39
+
40
+ SUFFIX = ".spool.json"
41
+ _TMP_PREFIX = ".tmp-"
42
+ _FORMAT = 1
43
+ _NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class SpoolFile:
48
+ """One spooled batch. ``born_ns`` (from the name) orders files and ages them."""
49
+
50
+ path: Path
51
+ born_ns: int
52
+ count: int
53
+ size: int
54
+
55
+
56
+ def _parse_name(name: str) -> tuple[int, int] | None:
57
+ """``<born_ns>-<pid>-<seq>-<count>.spool.json`` -> (born_ns, count)."""
58
+ if not name.endswith(SUFFIX):
59
+ return None
60
+ parts = name[: -len(SUFFIX)].split("-")
61
+ if len(parts) != 4 or not all(p.isdigit() for p in parts):
62
+ return None
63
+ return int(parts[0]), int(parts[3])
64
+
65
+
66
+ class Spool:
67
+ def __init__(
68
+ self,
69
+ directory: str | os.PathLike[str],
70
+ *,
71
+ max_bytes: int = DEFAULT_SPOOL_MAX_BYTES,
72
+ max_age_s: float = DEFAULT_SPOOL_MAX_AGE_SECONDS,
73
+ ) -> None:
74
+ if max_bytes < 1:
75
+ raise ValueError("spool max_bytes must be at least 1")
76
+ if max_age_s <= 0:
77
+ raise ValueError("spool max_age_s must be positive")
78
+ self.directory = Path(directory)
79
+ self.max_bytes = max_bytes
80
+ self.max_age_s = max_age_s
81
+ self.dropped = 0
82
+ """Spans the spool gave up on: over its caps, I/O errors or corrupt files."""
83
+ self._lock = threading.Lock() # file operations
84
+ self._replaying = threading.Lock() # one replay at a time
85
+ self._seq = itertools.count()
86
+ self._warned: set[str] = set()
87
+
88
+ def __repr__(self) -> str:
89
+ return f"Spool({str(self.directory)!r})"
90
+
91
+ # -- helpers -------------------------------------------------------------------
92
+
93
+ def _warn(self, kind: str, message: str, *args: Any) -> None:
94
+ if kind not in self._warned:
95
+ self._warned.add(kind)
96
+ logger.warning("agentflight: spool %s: " + message, self.directory, *args)
97
+
98
+ def _lose(self, n: int) -> None:
99
+ self.dropped += n
100
+
101
+ def _ensure_dir(self) -> bool:
102
+ try:
103
+ self.directory.mkdir(mode=0o700, parents=True, exist_ok=True)
104
+ st = os.lstat(self.directory)
105
+ if not stat.S_ISDIR(st.st_mode):
106
+ self._warn("notdir", "not a directory (a symlink?); spans are not spooled")
107
+ return False
108
+ if hasattr(os, "getuid") and st.st_uid != os.getuid():
109
+ self._warn("owner", "owned by another user; spans are not spooled")
110
+ return False
111
+ if st.st_mode & 0o077:
112
+ os.chmod(self.directory, 0o700)
113
+ return True
114
+ except OSError as exc:
115
+ self._warn("mkdir", "can't be used (%s); spans are not spooled", exc)
116
+ return False
117
+
118
+ def files(self) -> list[SpoolFile]:
119
+ """Spooled batches, oldest first."""
120
+ out: list[SpoolFile] = []
121
+ try:
122
+ entries = list(os.scandir(self.directory))
123
+ except OSError:
124
+ return out
125
+ for entry in entries:
126
+ parsed = _parse_name(entry.name)
127
+ if parsed is None:
128
+ continue
129
+ try:
130
+ size = entry.stat(follow_symlinks=False).st_size
131
+ except OSError:
132
+ continue
133
+ out.append(SpoolFile(Path(entry.path), parsed[0], parsed[1], size))
134
+ out.sort(key=lambda f: (f.born_ns, f.path.name))
135
+ return out
136
+
137
+ def pending_spans(self) -> int:
138
+ return sum(f.count for f in self.files())
139
+
140
+ def _remove(self, f: SpoolFile, *, lost: bool) -> None:
141
+ try:
142
+ f.path.unlink()
143
+ except FileNotFoundError:
144
+ return # another process got there first
145
+ except OSError as exc:
146
+ self._warn("unlink", "can't delete spooled files (%s)", exc)
147
+ return
148
+ if lost:
149
+ self._lose(f.count)
150
+
151
+ def _sweep(self, incoming: int) -> None:
152
+ """Delete expired files, stale temporary files and, to fit ``incoming`` more bytes,
153
+ the oldest files."""
154
+ now_ns = time.time_ns()
155
+ max_age_ns = int(self.max_age_s * 1e9)
156
+ try:
157
+ for entry in os.scandir(self.directory):
158
+ if entry.name.startswith(_TMP_PREFIX):
159
+ try: # left behind by a crash mid-write
160
+ if now_ns - entry.stat(follow_symlinks=False).st_mtime_ns > 3600e9:
161
+ os.unlink(entry.path)
162
+ except OSError:
163
+ pass
164
+ except OSError:
165
+ pass
166
+ files = self.files()
167
+ keep: list[SpoolFile] = []
168
+ expired = 0
169
+ for f in files:
170
+ if now_ns - f.born_ns > max_age_ns:
171
+ self._remove(f, lost=True)
172
+ expired += f.count
173
+ else:
174
+ keep.append(f)
175
+ if expired:
176
+ self._warn("age", "spans older than %gs were deleted unsent", self.max_age_s)
177
+ total = sum(f.size for f in keep)
178
+ evicted = 0
179
+ while keep and (total + incoming > self.max_bytes or len(keep) >= MAX_FILES):
180
+ oldest = keep.pop(0)
181
+ self._remove(oldest, lost=True)
182
+ total -= oldest.size
183
+ evicted += oldest.count
184
+ if evicted:
185
+ self._warn(
186
+ "full", "full (%d bytes); the oldest spooled spans were deleted", self.max_bytes
187
+ )
188
+
189
+ def _write(self, spans: list[dict[str, Any]], born_ns: int) -> Path | None:
190
+ data = json.dumps({"v": _FORMAT, "spans": spans}, separators=(",", ":")).encode()
191
+ if len(data) > self.max_bytes:
192
+ self._warn("big", "a batch of %d bytes is over the spool's cap", len(data))
193
+ return None
194
+ self._sweep(len(data))
195
+ name = f"{born_ns:020d}-{os.getpid()}-{next(self._seq):06d}-{len(spans)}{SUFFIX}"
196
+ final = self.directory / name
197
+ tmp = self.directory / f"{_TMP_PREFIX}{name}"
198
+ try:
199
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _NOFOLLOW, 0o600)
200
+ try:
201
+ view = memoryview(data)
202
+ while view:
203
+ view = view[os.write(fd, view) :]
204
+ finally:
205
+ os.close(fd)
206
+ os.replace(tmp, final)
207
+ return final
208
+ except OSError as exc:
209
+ kind = "nospace" if exc.errno in (errno.ENOSPC, errno.EDQUOT) else "write"
210
+ self._warn(kind, "can't write (%s); spans are lost", exc)
211
+ with contextlib.suppress(OSError):
212
+ tmp.unlink()
213
+ return None
214
+
215
+ # -- public --------------------------------------------------------------------
216
+
217
+ def put(self, spans: list[dict[str, Any]]) -> bool:
218
+ """Spool a batch for a later export. Never raises; False if it was lost."""
219
+ if not spans:
220
+ return True
221
+ try:
222
+ with self._lock:
223
+ ok = self._ensure_dir() and self._write(spans, time.time_ns()) is not None
224
+ except Exception as exc: # pragma: no cover - defensive: fail open
225
+ self._warn("bug", "unexpected error (%r)", exc)
226
+ ok = False
227
+ if not ok:
228
+ self._lose(len(spans))
229
+ return ok
230
+
231
+ def replay(self) -> Generator[tuple[SpoolFile, list[dict[str, Any]]], None, None]:
232
+ """Yield spooled batches oldest first; the caller must ``settle`` each one.
233
+
234
+ Yields nothing if another thread is already replaying. Unreadable or corrupt files
235
+ are deleted (and counted) instead of being yielded.
236
+ """
237
+ if not self._replaying.acquire(blocking=False):
238
+ return
239
+ try:
240
+ with self._lock:
241
+ if not self.directory.is_dir():
242
+ return
243
+ self._sweep(0)
244
+ files = self.files()
245
+ for f in files:
246
+ spans = self._read(f)
247
+ if spans is not None:
248
+ yield f, spans
249
+ finally:
250
+ self._replaying.release()
251
+
252
+ def _read(self, f: SpoolFile) -> list[dict[str, Any]] | None:
253
+ try:
254
+ fd = os.open(f.path, os.O_RDONLY | _NOFOLLOW)
255
+ with os.fdopen(fd, "rb") as fh:
256
+ doc = json.loads(fh.read())
257
+ spans = doc["spans"] if isinstance(doc, dict) and doc.get("v") == _FORMAT else None
258
+ if not isinstance(spans, list) or not all(isinstance(s, dict) for s in spans):
259
+ raise ValueError("not a spool file")
260
+ return spans
261
+ except FileNotFoundError:
262
+ return None # sent and deleted by another process meanwhile
263
+ except (OSError, ValueError, KeyError, TypeError) as exc:
264
+ self._warn("corrupt", "skipping a corrupt or unreadable file (%r)", exc)
265
+ with self._lock:
266
+ self._remove(f, lost=True)
267
+ return None
268
+
269
+ def settle(self, f: SpoolFile, total: int, unsent: list[dict[str, Any]]) -> None:
270
+ """After replaying ``f`` (``total`` spans): delete it, or keep only ``unsent`` in
271
+ its place in line."""
272
+ if len(unsent) == total:
273
+ return # nothing went through; leave the file as it is
274
+ try:
275
+ with self._lock:
276
+ self._remove(f, lost=False)
277
+ if unsent and self._write(unsent, f.born_ns) is None:
278
+ self._lose(len(unsent))
279
+ except Exception as exc: # pragma: no cover - defensive: fail open
280
+ self._warn("bug", "unexpected error (%r)", exc)
@@ -0,0 +1,68 @@
1
+ """Span attribute keys used by the AgentFlight SDK and server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ PREFIX = "agentflight."
6
+
7
+ KIND = "agentflight.kind"
8
+ RUN_NAME = "agentflight.run.name"
9
+ RUN_METADATA = "agentflight.run.metadata"
10
+ # On the run span: spans of this run the SDK dropped because its export queue was full,
11
+ # counted up to the moment the run ended (best effort; see the README).
12
+ RUN_DROPPED_SPANS = "agentflight.run.dropped_spans"
13
+
14
+ LLM_MODEL = "agentflight.llm.model"
15
+ LLM_MESSAGES = "agentflight.llm.messages"
16
+ LLM_RESPONSE = "agentflight.llm.response"
17
+ LLM_TOKENS_IN = "agentflight.llm.tokens_in"
18
+ LLM_TOKENS_OUT = "agentflight.llm.tokens_out"
19
+ LLM_COST_USD = "agentflight.llm.cost_usd"
20
+ LLM_PARAMS = "agentflight.llm.params"
21
+
22
+ # Which integration produced a span (e.g. "openai", "langgraph"); unset for manual calls.
23
+ INTEGRATION = "agentflight.integration"
24
+
25
+ TOOL_NAME = "agentflight.tool.name"
26
+ TOOL_ARGS = "agentflight.tool.args"
27
+ TOOL_RESULT = "agentflight.tool.result"
28
+
29
+ DECISION_NAME = "agentflight.decision.name"
30
+ DECISION_CHOICE = "agentflight.decision.choice"
31
+ DECISION_REASON = "agentflight.decision.reason"
32
+
33
+ STATE_KEY = "agentflight.state.key"
34
+ STATE_OLD = "agentflight.state.old"
35
+ STATE_NEW = "agentflight.state.new"
36
+
37
+ NODE_NAME = "agentflight.node.name"
38
+ NODE_STEP = "agentflight.node.step"
39
+ NODE_INPUT = "agentflight.node.input"
40
+ NODE_OUTPUT = "agentflight.node.output"
41
+
42
+ ERROR_TYPE = "agentflight.error.type"
43
+ ERROR_MESSAGE = "agentflight.error.message"
44
+ # Same id on every event caused by one underlying exception (tool span, agent log, run).
45
+ FAILURE_ID = "agentflight.failure.id"
46
+
47
+ # Replay and fork (see agentflight.replayer)
48
+ REPLAY_SOURCE_RUN = "agentflight.replay.source_run" # on the run: the recording it replays
49
+ REPLAY_MODE = "agentflight.replay.mode" # on the run: "replay" or "fork"
50
+ REPLAY_FORK_STEP = "agentflight.replay.fork_step" # on the run, for forks
51
+ # On the run, with on_divergence="live": first step that didn't match, and why
52
+ REPLAY_DIVERGED_AT = "agentflight.replay.diverged_at"
53
+ REPLAY_DIVERGENCE = "agentflight.replay.divergence"
54
+ REPLAY_STEP = "agentflight.replay.step" # on llm/tool spans: step index in the recording
55
+ # On llm/tool spans: "cached" (served from the recording), "override" (fork output) or "live"
56
+ REPLAY_SOURCE = "agentflight.replay.source"
57
+
58
+ # JSON object: attribute key -> {original_length, stored_length, reason}
59
+ TRUNCATED = "agentflight.truncated"
60
+
61
+ # Event kinds
62
+ RUN = "run"
63
+ LLM = "llm"
64
+ TOOL = "tool"
65
+ DECISION = "decision"
66
+ STATE = "state"
67
+ ERROR = "error"
68
+ NODE = "node" # a graph or graph node (LangGraph)