aid-runtime-python 0.1.54__tar.gz → 0.1.56__tar.gz

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 (96) hide show
  1. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/PKG-INFO +1 -1
  2. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/pyproject.toml +1 -1
  3. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/__init__.py +4 -1
  4. aid_runtime_python-0.1.56/src/aid_runtime/local_trace.py +230 -0
  5. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/tracing.py +23 -5
  6. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime_python.egg-info/PKG-INFO +1 -1
  7. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime_python.egg-info/SOURCES.txt +2 -0
  8. aid_runtime_python-0.1.56/tests/test_local_trace.py +155 -0
  9. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/README.md +0 -0
  10. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/setup.cfg +0 -0
  11. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/agents/__init__.py +0 -0
  12. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/agents/chat_model.py +0 -0
  13. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/agents/deep_agents.py +0 -0
  14. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/agents/engine.py +0 -0
  15. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/agents/guardrails.py +0 -0
  16. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/agents/ir.py +0 -0
  17. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/agents/loop.py +0 -0
  18. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/agents/memory.py +0 -0
  19. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/agents/policy.py +0 -0
  20. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/agents/state.py +0 -0
  21. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/cache.py +0 -0
  22. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/concurrency.py +0 -0
  23. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/control.py +0 -0
  24. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/cost.py +0 -0
  25. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/errors.py +0 -0
  26. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/evals/__init__.py +0 -0
  27. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/evals/dataset.py +0 -0
  28. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/evals/gate.py +0 -0
  29. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/evals/metrics.py +0 -0
  30. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/evals/predicate.py +0 -0
  31. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/evals/runner.py +0 -0
  32. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/gateway.py +0 -0
  33. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/pipeline.py +0 -0
  34. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/prompts.py +0 -0
  35. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/providers/__init__.py +0 -0
  36. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/providers/base.py +0 -0
  37. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/providers/fake.py +0 -0
  38. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/providers/http.py +0 -0
  39. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/py.typed +0 -0
  40. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/retrieval/__init__.py +0 -0
  41. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/retrieval/chunking.py +0 -0
  42. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/retrieval/citations.py +0 -0
  43. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/retrieval/connectors.py +0 -0
  44. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/retrieval/embedding.py +0 -0
  45. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/retrieval/gate.py +0 -0
  46. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/retrieval/hybrid.py +0 -0
  47. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/retrieval/metrics.py +0 -0
  48. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/retrieval/pgvector.py +0 -0
  49. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/retrieval/rerank.py +0 -0
  50. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/retrieval/retriever.py +0 -0
  51. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/retrieval/stores.py +0 -0
  52. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/retrieval/types.py +0 -0
  53. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/steps.py +0 -0
  54. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/structured.py +0 -0
  55. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/tools.py +0 -0
  56. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime/types.py +0 -0
  57. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime_python.egg-info/dependency_links.txt +0 -0
  58. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime_python.egg-info/requires.txt +0 -0
  59. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/src/aid_runtime_python.egg-info/top_level.txt +0 -0
  60. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_agents_budget.py +0 -0
  61. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_agents_deep_agents.py +0 -0
  62. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_agents_hitl.py +0 -0
  63. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_agents_loop.py +0 -0
  64. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_agents_memory.py +0 -0
  65. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_cache.py +0 -0
  66. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_concurrency.py +0 -0
  67. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_control.py +0 -0
  68. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_cost.py +0 -0
  69. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_dataset.py +0 -0
  70. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_evals.py +0 -0
  71. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_evals_assert_gate.py +0 -0
  72. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_evals_gate.py +0 -0
  73. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_evals_predicate.py +0 -0
  74. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_gateway.py +0 -0
  75. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_guardrails.py +0 -0
  76. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_http_provider.py +0 -0
  77. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_package.py +0 -0
  78. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_pipeline.py +0 -0
  79. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_prompts.py +0 -0
  80. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_retrieval_chunking.py +0 -0
  81. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_retrieval_citations.py +0 -0
  82. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_retrieval_connectors.py +0 -0
  83. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_retrieval_embedding.py +0 -0
  84. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_retrieval_gate.py +0 -0
  85. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_retrieval_hybrid.py +0 -0
  86. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_retrieval_metrics.py +0 -0
  87. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_retrieval_rerank.py +0 -0
  88. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_retrieval_stores.py +0 -0
  89. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_retrieval_types.py +0 -0
  90. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_steps.py +0 -0
  91. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_streaming.py +0 -0
  92. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_structured.py +0 -0
  93. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_tool_permissions.py +0 -0
  94. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_tools.py +0 -0
  95. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_tracing.py +0 -0
  96. {aid_runtime_python-0.1.54 → aid_runtime_python-0.1.56}/tests/test_types.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.54
3
+ Version: 0.1.56
4
4
  Summary: The AID Framework Python runtime: model gateway with pinning and cost budgets, prompt registry, tool executor, OTel GenAI tracing, plain-async pipeline, and an eval harness that gates on statistical regression against a stored baseline.
5
5
  Author: The AID Framework authors
6
6
  License-Expression: Apache-2.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "aid-runtime-python"
7
- version = "0.1.54"
7
+ version = "0.1.56"
8
8
  description = "The AID Framework Python runtime: model gateway with pinning and cost budgets, prompt registry, tool executor, OTel GenAI tracing, plain-async pipeline, and an eval harness that gates on statistical regression against a stored baseline."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -128,6 +128,7 @@ from aid_runtime.evals import (
128
128
  z_critical,
129
129
  )
130
130
  from aid_runtime.gateway import ModelGateway, estimate_usage
131
+ from aid_runtime.local_trace import TRACE_DIR_ENV, local_trace_enabled
131
132
  from aid_runtime.pipeline import (
132
133
  STEPS_KEY,
133
134
  Pipeline,
@@ -268,7 +269,7 @@ from aid_runtime.types import (
268
269
  )
269
270
 
270
271
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
271
- __version__ = "0.1.54"
272
+ __version__ = "0.1.56"
272
273
 
273
274
  __all__ = [
274
275
  "ATTRIBUTES",
@@ -285,6 +286,7 @@ __all__ = [
285
286
  "REDUCED_KEY",
286
287
  "RESERVED_KEYS",
287
288
  "STEPS_KEY",
289
+ "TRACE_DIR_ENV",
288
290
  "AgentBudgetDegradedError",
289
291
  "AgentCheckpoint",
290
292
  "AgentDefinition",
@@ -471,6 +473,7 @@ __all__ = [
471
473
  "lexical_ranking",
472
474
  "lexical_score",
473
475
  "llm_span",
476
+ "local_trace_enabled",
474
477
  "map_step",
475
478
  "metric_names",
476
479
  "normalize",
@@ -0,0 +1,230 @@
1
+ """A local JSONL trace sink, enabled by ``AID_TRACE_DIR``.
2
+
3
+ The OpenTelemetry path is unchanged: with no provider installed, spans are no-ops and
4
+ tracing costs nothing. This module exists for the other case -- the CLI needs trace
5
+ data on disk, without the application installing an exporter, an SDK or a collector.
6
+ Setting ``AID_TRACE_DIR`` is that explicit request, and nothing here runs otherwise.
7
+
8
+ It is deliberately *not* an OpenTelemetry ``SpanExporter``: exporting one would mean
9
+ depending on the SDK, and the runtime deliberately depends only on the API so it never
10
+ decides a host application's telemetry. Instead it mirrors the span surface the
11
+ runtime itself uses (attributes, events, status) and writes one JSON line per span.
12
+
13
+ Writing must never fail a request, so every failure to record is swallowed.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import contextlib
19
+ import functools
20
+ import json
21
+ import math
22
+ import os
23
+ import secrets
24
+ import threading
25
+ import time
26
+ from contextvars import ContextVar
27
+ from datetime import UTC, datetime
28
+ from pathlib import Path
29
+ from typing import TYPE_CHECKING, Any, cast
30
+
31
+ if TYPE_CHECKING:
32
+ from collections.abc import Mapping
33
+
34
+ from opentelemetry.trace import Span, Status
35
+
36
+ __all__ = ["TRACE_DIR_ENV", "finish_span", "local_trace_enabled", "wrap_span"]
37
+
38
+ TRACE_DIR_ENV = "AID_TRACE_DIR"
39
+
40
+ #: ``(span_id, trace_id)`` for the spans currently open in this context. A tuple, so
41
+ #: a context cannot see a sibling's stack, and a span that ends out of order removes
42
+ #: only its own entry.
43
+ _OPEN: ContextVar[tuple[tuple[str, str], ...]] = ContextVar("aid_local_trace_open", default=())
44
+
45
+ _lock = threading.Lock()
46
+
47
+
48
+ def local_trace_enabled() -> bool:
49
+ """Whether ``AID_TRACE_DIR`` names a directory to write to."""
50
+ return bool(_configured_dir())
51
+
52
+
53
+ def wrap_span(
54
+ span: Span,
55
+ *,
56
+ name: str,
57
+ kind: str,
58
+ attributes: Mapping[str, Any] | None = None,
59
+ ) -> Span:
60
+ """Return ``span`` itself unless a local trace is requested, else a recording proxy."""
61
+ if not local_trace_enabled():
62
+ return span
63
+ return cast("Span", _LocalSpan(span, name=name, kind=kind, attributes=attributes or {}))
64
+
65
+
66
+ def finish_span(span: Span) -> None:
67
+ """End a wrapped span. A no-op for an ordinary OpenTelemetry span."""
68
+ if isinstance(span, _LocalSpan):
69
+ span.end()
70
+
71
+
72
+ def _configured_dir() -> str:
73
+ return os.environ.get(TRACE_DIR_ENV, "").strip()
74
+
75
+
76
+ def _now() -> str:
77
+ return datetime.now(UTC).isoformat(timespec="microseconds").replace("+00:00", "Z")
78
+
79
+
80
+ def _jsonable(value: Any) -> Any:
81
+ """Coerce an attribute value to something ``json`` can always serialise.
82
+
83
+ OpenTelemetry accepts attribute types that JSON does not (tuples, arbitrary
84
+ objects), and a value that failed to serialise would cost the whole record.
85
+ """
86
+ if value is None or isinstance(value, str | bool | int):
87
+ return value
88
+ if isinstance(value, float):
89
+ return value if math.isfinite(value) else str(value)
90
+ if isinstance(value, list | tuple):
91
+ return [_jsonable(item) for item in value]
92
+ return str(value)
93
+
94
+
95
+ @functools.lru_cache(maxsize=4)
96
+ def _sink_path_for(configured: str) -> Path:
97
+ """The file for one configured directory, created on first use.
98
+
99
+ Cached per directory so one process writes one file, while a caller that
100
+ points ``AID_TRACE_DIR`` somewhere else still gets a fresh file.
101
+ """
102
+ directory = Path(configured)
103
+ with contextlib.suppress(OSError):
104
+ directory.mkdir(parents=True, exist_ok=True)
105
+ stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%S%fZ")
106
+ return directory / f"trace-{stamp}-{os.getpid()}.jsonl"
107
+
108
+
109
+ def _sink_path() -> Path | None:
110
+ configured = _configured_dir()
111
+ if not configured:
112
+ return None
113
+ return _sink_path_for(configured)
114
+
115
+
116
+ def _write(record: dict[str, Any]) -> None:
117
+ path = _sink_path()
118
+ if path is None:
119
+ return
120
+ line = json.dumps(record, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
121
+ # A trace that could not be written is a lost trace, not a failed request.
122
+ with (
123
+ contextlib.suppress(OSError, TypeError, ValueError),
124
+ _lock,
125
+ path.open("a", encoding="utf-8") as handle,
126
+ ):
127
+ handle.write(f"{line}\n")
128
+
129
+
130
+ class _LocalSpan:
131
+ """Mirrors the span methods this runtime calls, then writes one JSON line."""
132
+
133
+ def __init__(
134
+ self,
135
+ span: Span,
136
+ *,
137
+ name: str,
138
+ kind: str,
139
+ attributes: Mapping[str, Any],
140
+ ) -> None:
141
+ self._span = span
142
+ self._name = name
143
+ self._kind = kind
144
+ self._attributes: dict[str, Any] = {
145
+ key: _jsonable(value) for key, value in attributes.items()
146
+ }
147
+ self._events: list[dict[str, Any]] = []
148
+ self._status: dict[str, Any] | None = None
149
+ self._monotonic = time.monotonic()
150
+ self._started_at = _now()
151
+ self._ended = False
152
+
153
+ open_spans = _OPEN.get()
154
+ parent = open_spans[-1] if open_spans else None
155
+ self._trace_id = parent[1] if parent is not None else secrets.token_hex(16)
156
+ self._span_id = secrets.token_hex(8)
157
+ self._parent_span_id = parent[0] if parent is not None else None
158
+ _OPEN.set((*open_spans, (self._span_id, self._trace_id)))
159
+
160
+ def set_attribute(self, key: str, value: Any) -> None:
161
+ self._attributes[key] = _jsonable(value)
162
+ self._span.set_attribute(key, value)
163
+
164
+ def set_attributes(self, attributes: Mapping[str, Any]) -> None:
165
+ for key, value in attributes.items():
166
+ self.set_attribute(key, value)
167
+
168
+ def add_event(
169
+ self,
170
+ name: str,
171
+ attributes: Mapping[str, Any] | None = None,
172
+ timestamp: int | None = None,
173
+ ) -> None:
174
+ self._events.append(
175
+ {
176
+ "name": name,
177
+ "at": _now(),
178
+ "attributes": {key: _jsonable(value) for key, value in (attributes or {}).items()},
179
+ }
180
+ )
181
+ self._span.add_event(name, attributes, timestamp)
182
+
183
+ def record_exception(
184
+ self,
185
+ exception: BaseException,
186
+ attributes: Mapping[str, Any] | None = None,
187
+ *,
188
+ escaped: bool = True,
189
+ timestamp: int | None = None,
190
+ ) -> None:
191
+ recorded = {
192
+ "exception.type": f"{type(exception).__module__}.{type(exception).__qualname__}",
193
+ "exception.message": str(exception),
194
+ **{key: _jsonable(value) for key, value in (attributes or {}).items()},
195
+ }
196
+ self._events.append({"name": "exception", "at": _now(), "attributes": recorded})
197
+ self._span.record_exception(exception, attributes, escaped=escaped, timestamp=timestamp)
198
+
199
+ def set_status(self, status: Status) -> None:
200
+ self._status = {"code": status.status_code.name, "message": status.description}
201
+ self._span.set_status(status)
202
+
203
+ def update_name(self, name: str) -> None:
204
+ self._name = name
205
+ self._span.update_name(name)
206
+
207
+ def end(self, end_time: int | None = None) -> None:
208
+ if self._ended:
209
+ return
210
+ self._ended = True
211
+ _OPEN.set(tuple(entry for entry in _OPEN.get() if entry[0] != self._span_id))
212
+ self._span.end(end_time)
213
+ _write(
214
+ {
215
+ "trace_id": self._trace_id,
216
+ "span_id": self._span_id,
217
+ "parent_span_id": self._parent_span_id,
218
+ "name": self._name,
219
+ "kind": self._kind,
220
+ "started_at": self._started_at,
221
+ "ended_at": _now(),
222
+ "duration_ms": round((time.monotonic() - self._monotonic) * 1000, 3),
223
+ "attributes": self._attributes,
224
+ "events": self._events,
225
+ "status": self._status,
226
+ }
227
+ )
228
+
229
+ def __getattr__(self, name: str) -> Any:
230
+ return getattr(self._span, name)
@@ -20,6 +20,7 @@ from typing import TYPE_CHECKING, Any
20
20
  from opentelemetry import trace
21
21
  from opentelemetry.trace import Span, SpanKind, Status, StatusCode
22
22
 
23
+ from aid_runtime.local_trace import finish_span, wrap_span
23
24
  from aid_runtime.types import TokenUsage
24
25
 
25
26
  if TYPE_CHECKING:
@@ -130,11 +131,19 @@ def llm_span(
130
131
  record_exception=False,
131
132
  set_status_on_exception=False,
132
133
  ) as span:
134
+ recorded = wrap_span(
135
+ span,
136
+ name=f"{operation} {model}",
137
+ kind=SpanKind.CLIENT.name,
138
+ attributes=attributes,
139
+ )
133
140
  try:
134
- yield span
141
+ yield recorded
135
142
  except BaseException as exc:
136
- record_exception(span, exc)
143
+ record_exception(recorded, exc)
137
144
  raise
145
+ finally:
146
+ finish_span(recorded)
138
147
 
139
148
 
140
149
  def record_usage(span: Span, usage: TokenUsage) -> None:
@@ -166,18 +175,27 @@ def agent_span(
166
175
  makes open their own CLIENT child spans.
167
176
  """
168
177
  active = tracer or get_tracer()
178
+ attributes = aid_attributes(agent_id=agent_id, agent_engine=engine)
169
179
  with active.start_as_current_span(
170
180
  f"invoke_agent {agent_id}",
171
181
  kind=SpanKind.INTERNAL,
172
- attributes=aid_attributes(agent_id=agent_id, agent_engine=engine),
182
+ attributes=attributes,
173
183
  record_exception=False,
174
184
  set_status_on_exception=False,
175
185
  ) as span:
186
+ recorded = wrap_span(
187
+ span,
188
+ name=f"invoke_agent {agent_id}",
189
+ kind=SpanKind.INTERNAL.name,
190
+ attributes=attributes,
191
+ )
176
192
  try:
177
- yield span
193
+ yield recorded
178
194
  except BaseException as exc:
179
- record_exception(span, exc)
195
+ record_exception(recorded, exc)
180
196
  raise
197
+ finally:
198
+ finish_span(recorded)
181
199
 
182
200
 
183
201
  def record_hitl(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.54
3
+ Version: 0.1.56
4
4
  Summary: The AID Framework Python runtime: model gateway with pinning and cost budgets, prompt registry, tool executor, OTel GenAI tracing, plain-async pipeline, and an eval harness that gates on statistical regression against a stored baseline.
5
5
  Author: The AID Framework authors
6
6
  License-Expression: Apache-2.0
@@ -7,6 +7,7 @@ src/aid_runtime/control.py
7
7
  src/aid_runtime/cost.py
8
8
  src/aid_runtime/errors.py
9
9
  src/aid_runtime/gateway.py
10
+ src/aid_runtime/local_trace.py
10
11
  src/aid_runtime/pipeline.py
11
12
  src/aid_runtime/prompts.py
12
13
  src/aid_runtime/py.typed
@@ -70,6 +71,7 @@ tests/test_evals_predicate.py
70
71
  tests/test_gateway.py
71
72
  tests/test_guardrails.py
72
73
  tests/test_http_provider.py
74
+ tests/test_local_trace.py
73
75
  tests/test_package.py
74
76
  tests/test_pipeline.py
75
77
  tests/test_prompts.py
@@ -0,0 +1,155 @@
1
+ """The local JSONL trace sink.
2
+
3
+ The sink exists so the CLI can read traces without the application installing an
4
+ exporter, so these tests assert on the bytes actually written. A test against a mock
5
+ writer would prove nothing about whether a file appears, which is the only thing the
6
+ feature promises.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import math
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ import pytest
17
+ from opentelemetry.sdk.trace import TracerProvider
18
+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor
19
+ from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
20
+
21
+ from aid_runtime import (
22
+ ATTRIBUTES,
23
+ GEN_AI_OPERATION_CHAT,
24
+ TRACE_DIR_ENV,
25
+ local_trace_enabled,
26
+ )
27
+ from aid_runtime.local_trace import finish_span, wrap_span
28
+ from aid_runtime.tracing import agent_span, get_tracer, llm_span, record_cost
29
+
30
+
31
+ class BoomError(Exception):
32
+ """A failure with an unmistakable message."""
33
+
34
+
35
+ def _raise_boom() -> None:
36
+ raise BoomError("boom")
37
+
38
+
39
+ def _lines(directory: Path) -> list[dict[str, Any]]:
40
+ (path,) = directory.glob("trace-*.jsonl")
41
+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()]
42
+
43
+
44
+ def test_the_sink_is_off_unless_a_directory_is_configured(monkeypatch: pytest.MonkeyPatch) -> None:
45
+ monkeypatch.delenv(TRACE_DIR_ENV, raising=False)
46
+
47
+ assert local_trace_enabled() is False
48
+ span = get_tracer().start_span("unrecorded")
49
+ assert wrap_span(span, name="unrecorded", kind="CLIENT") is span
50
+
51
+
52
+ def test_nothing_is_written_without_the_variable(
53
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
54
+ ) -> None:
55
+ monkeypatch.delenv(TRACE_DIR_ENV, raising=False)
56
+
57
+ with llm_span(model="m", provider="p"):
58
+ pass
59
+
60
+ assert list(tmp_path.iterdir()) == []
61
+
62
+
63
+ def test_one_line_per_span(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
64
+ monkeypatch.setenv(TRACE_DIR_ENV, str(tmp_path))
65
+
66
+ with llm_span(model="m", provider="p") as span:
67
+ record_cost(span, 0.25)
68
+
69
+ (record,) = _lines(tmp_path)
70
+ assert record["name"] == f"{GEN_AI_OPERATION_CHAT} m"
71
+ assert record["kind"] == "CLIENT"
72
+ assert record["parent_span_id"] is None
73
+ assert len(str(record["trace_id"])) == 32
74
+ assert len(str(record["span_id"])) == 16
75
+ assert record["attributes"][ATTRIBUTES["system"]] == "p"
76
+ assert record["attributes"][ATTRIBUTES["cost_usd"]] == 0.25
77
+ assert record["status"] is None
78
+ assert float(str(record["duration_ms"])) >= 0
79
+
80
+
81
+ def test_a_child_span_points_at_its_parent(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
82
+ monkeypatch.setenv(TRACE_DIR_ENV, str(tmp_path))
83
+
84
+ with agent_span(agent_id="support", engine="native"), llm_span(model="m", provider="p"):
85
+ pass
86
+
87
+ # The inner span ends first, so it is the first line.
88
+ call, agent = _lines(tmp_path)
89
+ assert call["parent_span_id"] == agent["span_id"]
90
+ assert call["trace_id"] == agent["trace_id"]
91
+ assert agent["parent_span_id"] is None
92
+
93
+
94
+ def test_a_failure_is_recorded_once_with_an_error_status(
95
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
96
+ ) -> None:
97
+ monkeypatch.setenv(TRACE_DIR_ENV, str(tmp_path))
98
+
99
+ with pytest.raises(BoomError, match="boom"), llm_span(model="m", provider="p"):
100
+ _raise_boom()
101
+
102
+ (record,) = _lines(tmp_path)
103
+ assert record["status"]["code"] == "ERROR"
104
+ assert record["status"]["message"] == "boom"
105
+ (event,) = record["events"]
106
+ assert event["name"] == "exception"
107
+ assert event["attributes"]["exception.message"] == "boom"
108
+
109
+
110
+ def test_attributes_json_cannot_hold_are_coerced(
111
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
112
+ ) -> None:
113
+ monkeypatch.setenv(TRACE_DIR_ENV, str(tmp_path))
114
+
115
+ span = get_tracer().start_span("coerced")
116
+ recorded = wrap_span(
117
+ span,
118
+ name="coerced",
119
+ kind="CLIENT",
120
+ attributes={"tuple": (1, "two"), "infinite": math.inf, "object": Path("a/b")},
121
+ )
122
+ finish_span(recorded)
123
+
124
+ (record,) = _lines(tmp_path)
125
+ assert record["attributes"]["tuple"] == [1, "two"]
126
+ assert record["attributes"]["infinite"] == "inf"
127
+ assert record["attributes"]["object"] == str(Path("a/b"))
128
+
129
+
130
+ def test_ending_twice_writes_one_line(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
131
+ monkeypatch.setenv(TRACE_DIR_ENV, str(tmp_path))
132
+
133
+ with llm_span(model="m", provider="p") as span:
134
+ span.end()
135
+ span.end()
136
+
137
+ assert len(_lines(tmp_path)) == 1
138
+
139
+
140
+ def test_the_opentelemetry_path_still_records(
141
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
142
+ ) -> None:
143
+ monkeypatch.setenv(TRACE_DIR_ENV, str(tmp_path))
144
+ exporter = InMemorySpanExporter()
145
+ provider = TracerProvider()
146
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
147
+ tracer = provider.get_tracer("aid-runtime-tests")
148
+
149
+ with llm_span(model="m", provider="p", tracer=tracer):
150
+ pass
151
+
152
+ (recorded,) = exporter.get_finished_spans()
153
+ assert recorded.name == f"{GEN_AI_OPERATION_CHAT} m"
154
+ (line,) = _lines(tmp_path)
155
+ assert line["name"] == recorded.name