agentrail-python 0.1.0__py3-none-any.whl → 0.2.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.
- agentrail_python/__init__.py +4 -0
- agentrail_python/_client.py +46 -7
- agentrail_python/_options.py +38 -1
- agentrail_python/_privacy.py +153 -8
- agentrail_python/_processors.py +4 -1
- agentrail_python/_queue.py +88 -18
- agentrail_python/_runtime.py +76 -2
- agentrail_python/_version.py +1 -1
- agentrail_python/asgi.py +11 -1
- agentrail_python/mcp.py +438 -43
- agentrail_python/wsgi.py +9 -1
- agentrail_python-0.2.0.dist-info/METADATA +202 -0
- agentrail_python-0.2.0.dist-info/RECORD +25 -0
- agentrail_python-0.1.0.dist-info/METADATA +0 -625
- agentrail_python-0.1.0.dist-info/RECORD +0 -25
- {agentrail_python-0.1.0.dist-info → agentrail_python-0.2.0.dist-info}/WHEEL +0 -0
- {agentrail_python-0.1.0.dist-info → agentrail_python-0.2.0.dist-info}/licenses/LICENSE +0 -0
agentrail_python/__init__.py
CHANGED
|
@@ -11,6 +11,7 @@ from ._options import (
|
|
|
11
11
|
AuthorizedOperation,
|
|
12
12
|
CaptureCode,
|
|
13
13
|
CaptureError,
|
|
14
|
+
CapturePayloads,
|
|
14
15
|
CollectorOptions,
|
|
15
16
|
ConfigurationError,
|
|
16
17
|
IncomingRequest,
|
|
@@ -18,6 +19,7 @@ from ._options import (
|
|
|
18
19
|
LocationSource,
|
|
19
20
|
LogsOptions,
|
|
20
21
|
McpContext,
|
|
22
|
+
McpPayload,
|
|
21
23
|
MilestoneContext,
|
|
22
24
|
Options,
|
|
23
25
|
PerformanceContext,
|
|
@@ -38,6 +40,7 @@ __all__ = [
|
|
|
38
40
|
"AuthorizedOperation",
|
|
39
41
|
"CaptureCode",
|
|
40
42
|
"CaptureError",
|
|
43
|
+
"CapturePayloads",
|
|
41
44
|
"Client",
|
|
42
45
|
"CollectorOptions",
|
|
43
46
|
"ConfigurationError",
|
|
@@ -47,6 +50,7 @@ __all__ = [
|
|
|
47
50
|
"LocationSource",
|
|
48
51
|
"LogsOptions",
|
|
49
52
|
"McpContext",
|
|
53
|
+
"McpPayload",
|
|
50
54
|
"MilestoneContext",
|
|
51
55
|
"MilestoneScope",
|
|
52
56
|
"Options",
|
agentrail_python/_client.py
CHANGED
|
@@ -17,20 +17,22 @@ from opentelemetry import context as otel_context
|
|
|
17
17
|
from opentelemetry import trace
|
|
18
18
|
from opentelemetry.trace import Link, NonRecordingSpan, Span, SpanContext, SpanKind, StatusCode, TraceFlags
|
|
19
19
|
|
|
20
|
-
from ._handoff import HANDOFF_HEADER, Refused, parse_traceparent, verify
|
|
20
|
+
from ._handoff import HANDOFF_HEADER, Refused, keyed_hash, parse_traceparent, verify
|
|
21
21
|
from ._options import (
|
|
22
22
|
LOCATION_SOURCES,
|
|
23
23
|
PRINCIPAL_KINDS,
|
|
24
24
|
SURFACES,
|
|
25
|
+
CaptureCode,
|
|
25
26
|
ConfigurationError,
|
|
26
27
|
IncomingRequest,
|
|
27
28
|
MilestoneContext,
|
|
29
|
+
Signal,
|
|
28
30
|
VerifiedIdentity,
|
|
29
31
|
)
|
|
30
32
|
from ._performance import performance_attributes
|
|
31
33
|
from ._privacy import StructuredLog, clean_context, copy_log
|
|
32
34
|
from ._queue import ExportQueue, QueueStats
|
|
33
|
-
from ._runtime import Attributes, Mark, RequestState, Runtime
|
|
35
|
+
from ._runtime import Attributes, Mark, McpEvidence, RequestState, Runtime
|
|
34
36
|
from ._suppression import suppressed
|
|
35
37
|
from ._text import bounded, valid_text
|
|
36
38
|
from ._version import VERSION
|
|
@@ -62,16 +64,28 @@ class MilestoneScope:
|
|
|
62
64
|
The block's exception is recorded and re-raised unchanged.
|
|
63
65
|
"""
|
|
64
66
|
|
|
65
|
-
def __init__(
|
|
67
|
+
def __init__(
|
|
68
|
+
self,
|
|
69
|
+
client: Client,
|
|
70
|
+
name: str,
|
|
71
|
+
details: MilestoneContext,
|
|
72
|
+
*,
|
|
73
|
+
step: bool = True,
|
|
74
|
+
mcp: McpEvidence | None = None,
|
|
75
|
+
) -> None:
|
|
66
76
|
client._validate_milestone(name, details) # pyright: ignore[reportPrivateUsage]
|
|
67
77
|
self._client = client
|
|
68
78
|
self._name = name
|
|
69
79
|
self._details = details
|
|
80
|
+
self._step = step
|
|
81
|
+
self._mcp = mcp
|
|
70
82
|
self._span: Span | None = None
|
|
71
83
|
self._token: object | None = None
|
|
72
84
|
|
|
73
85
|
def __enter__(self) -> MilestoneScope:
|
|
74
|
-
span, ctx = self._client._start(
|
|
86
|
+
span, ctx = self._client._start( # pyright: ignore[reportPrivateUsage]
|
|
87
|
+
self._name, self._details, step=self._step, mcp=self._mcp
|
|
88
|
+
)
|
|
75
89
|
self._span = span
|
|
76
90
|
self._token = otel_context.attach(ctx)
|
|
77
91
|
return self
|
|
@@ -200,7 +214,13 @@ class Client:
|
|
|
200
214
|
raise ConfigurationError("Milestone name and kind must contain 1-256 characters, with a known surface.")
|
|
201
215
|
|
|
202
216
|
def _start(
|
|
203
|
-
self,
|
|
217
|
+
self,
|
|
218
|
+
name: str,
|
|
219
|
+
details: MilestoneContext,
|
|
220
|
+
identity: Attributes | None = None,
|
|
221
|
+
*,
|
|
222
|
+
step: bool = True,
|
|
223
|
+
mcp: McpEvidence | None = None,
|
|
204
224
|
) -> tuple[Span, otel_context.Context]:
|
|
205
225
|
performance = None
|
|
206
226
|
if details.performance is not None:
|
|
@@ -210,16 +230,24 @@ class Client:
|
|
|
210
230
|
self._runtime.report("invalid_performance", "context")
|
|
211
231
|
base = otel_context.get_current()
|
|
212
232
|
state = self._runtime.state(base)
|
|
233
|
+
continued: list[Link] = []
|
|
234
|
+
if state is not None and state.entry is not None:
|
|
235
|
+
current = trace.get_current_span(base).get_span_context()
|
|
236
|
+
if current.is_valid and (current.is_remote or current.trace_id != state.entry.trace_id):
|
|
237
|
+
# A trace continued from unsigned input inside the request (the MCP
|
|
238
|
+
# SDK continues a client's _meta traceparent) is a link, never the parent.
|
|
239
|
+
continued.append(Link(clean_context(current)))
|
|
240
|
+
base = trace.set_span_in_context(NonRecordingSpan(state.entry), base)
|
|
213
241
|
if state is None:
|
|
214
242
|
external = trace.get_current_span(base).get_span_context()
|
|
215
243
|
links = [Link(clean_context(external))] if external.is_valid else []
|
|
216
244
|
state = RequestState(links=links)
|
|
217
245
|
# Its own managed scope: an unrelated caller's trace is a link, never the parent.
|
|
218
246
|
base = otel_context.set_value(self._runtime.state_key, state, otel_context.Context())
|
|
219
|
-
mark = Mark(name=name, details=details, performance=performance, identity=identity)
|
|
247
|
+
mark = Mark(name=name, details=details, performance=performance, identity=identity, step=step, mcp=mcp)
|
|
220
248
|
marked = otel_context.set_value(self._runtime.mark_key, mark, base)
|
|
221
249
|
parented = trace.get_current_span(base).get_span_context().is_valid
|
|
222
|
-
span = self._tracer.start_span(name, context=marked, links=[] if parented else state.links)
|
|
250
|
+
span = self._tracer.start_span(name, context=marked, links=continued + ([] if parented else state.links))
|
|
223
251
|
if not span.is_recording():
|
|
224
252
|
self._runtime.report("entry_not_recording", "traces")
|
|
225
253
|
return span, trace.set_span_in_context(span, base)
|
|
@@ -278,6 +306,16 @@ class Client:
|
|
|
278
306
|
|
|
279
307
|
return AgentrailWSGIMiddleware(app, client=self)
|
|
280
308
|
|
|
309
|
+
def _keyed_hash(self, value: str) -> str:
|
|
310
|
+
"""The keyed hash principal IDs use: 32 lowercase hex under the workspace key."""
|
|
311
|
+
return keyed_hash(self._runtime.options.input.hash_key, value)
|
|
312
|
+
|
|
313
|
+
def _payload_room(self) -> bool:
|
|
314
|
+
return self._spans.payload_room()
|
|
315
|
+
|
|
316
|
+
def _report(self, code: CaptureCode, signal: Signal) -> None:
|
|
317
|
+
self._runtime.report(code, signal)
|
|
318
|
+
|
|
281
319
|
def _managed(self) -> bool:
|
|
282
320
|
return not self._closed and not suppressed() and self._runtime.state() is not None
|
|
283
321
|
|
|
@@ -318,6 +356,7 @@ class Client:
|
|
|
318
356
|
span = self._tracer.start_span(
|
|
319
357
|
f"HTTP {request.method}", context=ctx, kind=SpanKind.SERVER, attributes=attributes
|
|
320
358
|
)
|
|
359
|
+
state.entry = span.get_span_context()
|
|
321
360
|
if not span.is_recording():
|
|
322
361
|
self._runtime.report("entry_not_recording", "traces")
|
|
323
362
|
return span, trace.set_span_in_context(span, ctx)
|
agentrail_python/_options.py
CHANGED
|
@@ -8,7 +8,7 @@ import sys
|
|
|
8
8
|
import uuid
|
|
9
9
|
from collections.abc import Callable, Mapping, Sequence
|
|
10
10
|
from dataclasses import dataclass, field
|
|
11
|
-
from typing import TYPE_CHECKING, Literal
|
|
11
|
+
from typing import TYPE_CHECKING, Any, Literal, TypedDict
|
|
12
12
|
from urllib.parse import SplitResult, urlsplit
|
|
13
13
|
|
|
14
14
|
from ._text import valid_text, well_formed
|
|
@@ -36,6 +36,8 @@ CaptureCode = Literal[
|
|
|
36
36
|
"ignore_failed",
|
|
37
37
|
"identity_outside_request",
|
|
38
38
|
"invalid_performance",
|
|
39
|
+
"payload_redact_failed",
|
|
40
|
+
"payload_budget",
|
|
39
41
|
]
|
|
40
42
|
Signal = Literal["traces", "logs", "context"]
|
|
41
43
|
|
|
@@ -143,6 +145,41 @@ class McpContext:
|
|
|
143
145
|
client: str | None = None
|
|
144
146
|
client_version: str | None = None
|
|
145
147
|
protocol: str | None = None
|
|
148
|
+
# The tool, resource or prompt's registered name, never a value from its arguments.
|
|
149
|
+
name: str | None = None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class McpPayload(TypedDict):
|
|
153
|
+
"""What a redact hook sees of one MCP message: copies, never the live objects.
|
|
154
|
+
|
|
155
|
+
``name`` is the tool, the resource URI (without userinfo, query or
|
|
156
|
+
fragment) or the prompt, else ``None``. ``request`` is the message's
|
|
157
|
+
params; ``response`` is the result or the JSON-RPC error the server
|
|
158
|
+
answers with (``code``, ``message``, ``data``), and ``None`` only for a
|
|
159
|
+
notification or a request ended without an answer (a cancellation). A
|
|
160
|
+
multi-round-trip ``requestState`` is removed from both.
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
method: str
|
|
164
|
+
name: str | None
|
|
165
|
+
request: Any
|
|
166
|
+
response: Any
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@dataclass(frozen=True, kw_only=True)
|
|
170
|
+
class CapturePayloads:
|
|
171
|
+
"""Opt in to sending MCP request and response content.
|
|
172
|
+
|
|
173
|
+
``redact`` runs in the request, after the handler returns and before the
|
|
174
|
+
answer is written, on JSON copies.
|
|
175
|
+
Return the mapping to send (its ``request`` and ``response`` are encoded
|
|
176
|
+
as JSON text; a missing or ``None`` side is not sent), or ``None`` to send
|
|
177
|
+
neither. A hook that raises sends nothing for that message and is
|
|
178
|
+
reported as ``payload_redact_failed``, as is one whose result is not JSON;
|
|
179
|
+
the MCP call is unaffected.
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
redact: Callable[[McpPayload], Mapping[str, Any] | None]
|
|
146
183
|
|
|
147
184
|
|
|
148
185
|
@dataclass(frozen=True, kw_only=True)
|
agentrail_python/_privacy.py
CHANGED
|
@@ -8,6 +8,7 @@ holds these copies.
|
|
|
8
8
|
from __future__ import annotations
|
|
9
9
|
|
|
10
10
|
import math
|
|
11
|
+
import re
|
|
11
12
|
import uuid
|
|
12
13
|
from collections.abc import Mapping
|
|
13
14
|
from dataclasses import dataclass, field
|
|
@@ -30,10 +31,18 @@ from opentelemetry.trace import (
|
|
|
30
31
|
from opentelemetry.util.types import AttributeValue
|
|
31
32
|
|
|
32
33
|
from ._handoff import valid_marker
|
|
33
|
-
from ._runtime import Attributes, Runtime, SpanMeta
|
|
34
|
+
from ._runtime import Attributes, McpEvidence, RequestFacts, Runtime, SpanMeta
|
|
34
35
|
from ._text import bounded, js_json, utf16_length, valid_text
|
|
35
36
|
|
|
36
37
|
_LIMIT = 4096
|
|
38
|
+
_HEADER_NAME = re.compile(r"[!#$%&'*+.^_`|~0-9A-Za-z-]+")
|
|
39
|
+
"""An HTTP token (RFC 9110), as a header name is written."""
|
|
40
|
+
REQUEST_PAYLOAD = "agentrail.mcp.request.payload"
|
|
41
|
+
RESPONSE_PAYLOAD = "agentrail.mcp.response.payload"
|
|
42
|
+
REQUEST_TRUNCATED = "agentrail.mcp.request.truncated"
|
|
43
|
+
RESPONSE_TRUNCATED = "agentrail.mcp.response.truncated"
|
|
44
|
+
_PAYLOADS = frozenset((REQUEST_PAYLOAD, RESPONSE_PAYLOAD))
|
|
45
|
+
_PAYLOAD_KEYS = _PAYLOADS | {REQUEST_TRUNCATED, RESPONSE_TRUNCATED}
|
|
37
46
|
|
|
38
47
|
|
|
39
48
|
def clean_context(context: SpanContext) -> SpanContext:
|
|
@@ -116,7 +125,7 @@ def copy_span(span: ReadableSpan, meta: SpanMeta, runtime: Runtime) -> ReadableS
|
|
|
116
125
|
# one per message) is supporting work, not a second entry.
|
|
117
126
|
kind = SpanKind.INTERNAL
|
|
118
127
|
mark = meta.mark
|
|
119
|
-
entry = mark is not None or kind in (SpanKind.SERVER, SpanKind.CONSUMER)
|
|
128
|
+
entry = (mark is not None and mark.step) or kind in (SpanKind.SERVER, SpanKind.CONSUMER)
|
|
120
129
|
if entry:
|
|
121
130
|
identity = mark.identity if mark is not None and mark.identity is not None else meta.state.principal()
|
|
122
131
|
attributes.update(identity)
|
|
@@ -127,20 +136,25 @@ def copy_span(span: ReadableSpan, meta: SpanMeta, runtime: Runtime) -> ReadableS
|
|
|
127
136
|
name = f"HTTP {method}" if isinstance(method, str) else "backend.operation"
|
|
128
137
|
if mark is not None:
|
|
129
138
|
name = mark.name
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
139
|
+
if mark.step:
|
|
140
|
+
attributes["agentrail.step"] = True
|
|
141
|
+
attributes["agentrail.step.surface"] = mark.details.surface
|
|
142
|
+
attributes["agentrail.step.kind"] = mark.details.kind
|
|
133
143
|
if mark.performance is not None:
|
|
134
144
|
attributes.update(mark.performance)
|
|
135
145
|
mcp = mark.details.mcp
|
|
136
146
|
if mcp is not None:
|
|
147
|
+
# Resource URIs have no standard name attribute.
|
|
137
148
|
for key, value, limit in (
|
|
138
|
-
("
|
|
139
|
-
("
|
|
140
|
-
("
|
|
149
|
+
("mcp.method.name", mcp.method, 128),
|
|
150
|
+
("gen_ai.tool.name", mcp.name if mcp.method == "tools/call" else None, 256),
|
|
151
|
+
("gen_ai.prompt.name", mcp.name if mcp.method == "prompts/get" else None, 256),
|
|
141
152
|
):
|
|
142
153
|
if value:
|
|
143
154
|
attributes[key] = bounded(value, limit)
|
|
155
|
+
_client_details(attributes, mcp.client, mcp.client_version, mcp.protocol)
|
|
156
|
+
if mark.mcp is not None:
|
|
157
|
+
_mcp_attributes(attributes, mark.mcp)
|
|
144
158
|
links = [Link(clean_context(link.context)) for link in span.links]
|
|
145
159
|
if kind == SpanKind.SERVER:
|
|
146
160
|
links.extend(Link(clean_context(link.context)) for link in meta.state.links)
|
|
@@ -162,6 +176,137 @@ def copy_span(span: ReadableSpan, meta: SpanMeta, runtime: Runtime) -> ReadableS
|
|
|
162
176
|
)
|
|
163
177
|
|
|
164
178
|
|
|
179
|
+
def _client_details(attributes: Attributes, client: str | None, version: str | None, protocol: str | None) -> None:
|
|
180
|
+
for key, value, limit in (
|
|
181
|
+
("agentrail.mcp.client.name", client, 128),
|
|
182
|
+
("agentrail.mcp.client.version", version, 128),
|
|
183
|
+
("agentrail.mcp.protocol.version", protocol, 64),
|
|
184
|
+
):
|
|
185
|
+
if value:
|
|
186
|
+
attributes[key] = bounded(value, limit)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _mcp_attributes(attributes: Attributes, evidence: McpEvidence) -> None:
|
|
190
|
+
"""The contract's ``otlp.mcpAttributes``. Payloads are exempt from the text limit."""
|
|
191
|
+
attributes["agentrail.mcp.layer"] = evidence.layer
|
|
192
|
+
if evidence.method is not None:
|
|
193
|
+
attributes["agentrail.mcp.method"] = evidence.method
|
|
194
|
+
_client_details(attributes, evidence.client, evidence.client_version, evidence.protocol)
|
|
195
|
+
values = (
|
|
196
|
+
("agentrail.mcp.session.id_hash", evidence.session_hash),
|
|
197
|
+
("agentrail.mcp.request.bytes", evidence.request_bytes),
|
|
198
|
+
("agentrail.mcp.response.bytes", evidence.response_bytes),
|
|
199
|
+
("agentrail.mcp.jsonrpc.error_code", evidence.error_code),
|
|
200
|
+
(REQUEST_PAYLOAD, evidence.request_payload),
|
|
201
|
+
(RESPONSE_PAYLOAD, evidence.response_payload),
|
|
202
|
+
)
|
|
203
|
+
for key, value in values:
|
|
204
|
+
if value is not None:
|
|
205
|
+
attributes[key] = value
|
|
206
|
+
for key, flag in (
|
|
207
|
+
("agentrail.mcp.result.is_error", evidence.is_error),
|
|
208
|
+
(REQUEST_TRUNCATED, evidence.request_truncated and evidence.request_payload is not None),
|
|
209
|
+
(RESPONSE_TRUNCATED, evidence.response_truncated and evidence.response_payload is not None),
|
|
210
|
+
):
|
|
211
|
+
if flag:
|
|
212
|
+
attributes[key] = True
|
|
213
|
+
if evidence.request is not None:
|
|
214
|
+
_request_facts(attributes, evidence.request)
|
|
215
|
+
if evidence.jsonrpc_id is not None:
|
|
216
|
+
attributes["agentrail.mcp.jsonrpc.id"] = evidence.jsonrpc_id
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _request_facts(attributes: Attributes, facts: RequestFacts) -> None:
|
|
220
|
+
"""The contract's ``otlp.mcpSpans.requestFacts``: the HTTP request that carried the message.
|
|
221
|
+
|
|
222
|
+
No HTTP status: a step can end before its answer's status is written (a JSON
|
|
223
|
+
response is written after it), so only the HTTP entry span carries one.
|
|
224
|
+
"""
|
|
225
|
+
attributes["http.request.method"] = bounded(facts.method, _LIMIT)
|
|
226
|
+
url = sanitized_url(facts.url)
|
|
227
|
+
if url is not None:
|
|
228
|
+
attributes["url.full"] = url
|
|
229
|
+
for key, value in (
|
|
230
|
+
("user_agent.original", facts.user_agent),
|
|
231
|
+
("agentrail.http.request.accept", facts.accept),
|
|
232
|
+
("agentrail.http.request.accept_encoding", facts.accept_encoding),
|
|
233
|
+
):
|
|
234
|
+
if value:
|
|
235
|
+
attributes[key] = bounded(value, _LIMIT)
|
|
236
|
+
names = _header_names(facts.header_names)
|
|
237
|
+
if names is not None:
|
|
238
|
+
attributes["agentrail.http.request.header_names"] = names
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _header_names(names: tuple[str, ...]) -> str | None:
|
|
242
|
+
"""Comma-joined, whole names within the text limit; None when any is no HTTP token.
|
|
243
|
+
|
|
244
|
+
A "name" that is no token holds a value, or part of one (a lax server's), so
|
|
245
|
+
no part of the list is sent: the collector would take none of it either.
|
|
246
|
+
"""
|
|
247
|
+
if not names or not all(_HEADER_NAME.fullmatch(name) for name in names):
|
|
248
|
+
return None
|
|
249
|
+
kept: list[str] = []
|
|
250
|
+
length = -1
|
|
251
|
+
for name in names:
|
|
252
|
+
length += len(name) + 1 # a token is ASCII: one UTF-16 unit a character
|
|
253
|
+
if length > _LIMIT:
|
|
254
|
+
break
|
|
255
|
+
kept.append(name)
|
|
256
|
+
return ",".join(kept)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _utf8_length(value: str) -> int:
|
|
260
|
+
return len(value.encode("utf-8", "surrogatepass"))
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def span_weight(span: ReadableSpan) -> tuple[int, int]:
|
|
264
|
+
"""An over-estimate of the span's OTLP protobuf size, and its payload bytes."""
|
|
265
|
+
size = 256 + _utf8_length(span.name) + 64 * len(span.links)
|
|
266
|
+
payload = 0
|
|
267
|
+
for key, value in (span.attributes or {}).items():
|
|
268
|
+
size += 16 + len(key)
|
|
269
|
+
if isinstance(value, str):
|
|
270
|
+
length = _utf8_length(value)
|
|
271
|
+
size += length
|
|
272
|
+
if key in _PAYLOADS:
|
|
273
|
+
payload += length
|
|
274
|
+
else:
|
|
275
|
+
size += 16
|
|
276
|
+
return size, payload
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def log_weight(record: ReadableLogRecord) -> tuple[int, int]:
|
|
280
|
+
"""An over-estimate of the record's OTLP protobuf size; logs carry no payloads."""
|
|
281
|
+
log = record.log_record
|
|
282
|
+
body = log.body
|
|
283
|
+
size = 256 + (_utf8_length(body) if isinstance(body, str) else 0)
|
|
284
|
+
size += sum(
|
|
285
|
+
16 + len(key) + (_utf8_length(value) if isinstance(value, str) else 16)
|
|
286
|
+
for key, value in (log.attributes or {}).items()
|
|
287
|
+
)
|
|
288
|
+
return size, 0
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def without_payloads(span: ReadableSpan) -> ReadableSpan:
|
|
292
|
+
"""The same sanitized copy without its payload attributes."""
|
|
293
|
+
attributes = {key: value for key, value in (span.attributes or {}).items() if key not in _PAYLOAD_KEYS}
|
|
294
|
+
return ReadableSpan(
|
|
295
|
+
name=span.name,
|
|
296
|
+
context=span.get_span_context(),
|
|
297
|
+
parent=span.parent,
|
|
298
|
+
resource=span.resource,
|
|
299
|
+
attributes=attributes,
|
|
300
|
+
events=(),
|
|
301
|
+
links=span.links,
|
|
302
|
+
kind=span.kind,
|
|
303
|
+
status=span.status,
|
|
304
|
+
start_time=span.start_time,
|
|
305
|
+
end_time=span.end_time,
|
|
306
|
+
instrumentation_scope=span.instrumentation_scope,
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
|
|
165
310
|
def _scalar(value: object) -> str | int | float | bool | type[_Skip] | None:
|
|
166
311
|
if value is None or isinstance(value, bool):
|
|
167
312
|
return value
|
agentrail_python/_processors.py
CHANGED
|
@@ -34,7 +34,7 @@ from opentelemetry.util.types import Attributes
|
|
|
34
34
|
from ._client import Client
|
|
35
35
|
from ._handoff import OWNED_HEADERS
|
|
36
36
|
from ._options import ConfigurationError, Options, resolve
|
|
37
|
-
from ._privacy import StructuredLog, copy_log, copy_span
|
|
37
|
+
from ._privacy import StructuredLog, copy_log, copy_span, log_weight, span_weight, without_payloads
|
|
38
38
|
from ._queue import ExportQueue
|
|
39
39
|
from ._runtime import Runtime, SpanMeta
|
|
40
40
|
from ._suppression import suppressed
|
|
@@ -229,6 +229,8 @@ class Processors:
|
|
|
229
229
|
lambda batch: _export_spans(span_exporter, batch),
|
|
230
230
|
lambda code, count: runtime.report(code, "traces", count),
|
|
231
231
|
span_exporter.shutdown,
|
|
232
|
+
weigh=span_weight,
|
|
233
|
+
strip=without_payloads,
|
|
232
234
|
)
|
|
233
235
|
self.logs: ExportQueue[ReadableLogRecord] = ExportQueue(
|
|
234
236
|
"logs",
|
|
@@ -236,6 +238,7 @@ class Processors:
|
|
|
236
238
|
lambda batch: _export_logs(log_exporter, batch),
|
|
237
239
|
lambda code, count: runtime.report(code, "logs", count),
|
|
238
240
|
log_exporter.shutdown,
|
|
241
|
+
weigh=log_weight,
|
|
239
242
|
)
|
|
240
243
|
self.span_processor: SpanProcessor = _SpanProcessor(runtime, self.spans)
|
|
241
244
|
self.log_processor: LogRecordProcessor = _LogProcessor(runtime, self.logs)
|
agentrail_python/_queue.py
CHANGED
|
@@ -4,6 +4,11 @@
|
|
|
4
4
|
Capacity counts the batch being exported. One batch is exported at a time; the
|
|
5
5
|
OTLP exporter owns retries within its timeout. Records only ever wait in
|
|
6
6
|
memory: there is no disk persistence.
|
|
7
|
+
|
|
8
|
+
A batch closes at ``batch_size`` records or before its estimated encoded size
|
|
9
|
+
would pass ``BATCH_BYTES``, under the collector's 16 MiB body limit. MCP
|
|
10
|
+
payload text is held to ``PAYLOAD_BUDGET`` per queue, the batch in flight
|
|
11
|
+
included; past it a record keeps everything but its payloads.
|
|
7
12
|
"""
|
|
8
13
|
|
|
9
14
|
from __future__ import annotations
|
|
@@ -22,6 +27,26 @@ from ._suppression import reporting
|
|
|
22
27
|
|
|
23
28
|
T = TypeVar("T")
|
|
24
29
|
|
|
30
|
+
EXPORT_BYTES = 16 * 1024 * 1024
|
|
31
|
+
"""The collector's request body limit (the contract's ``otlp.limits.bodyBytes``)."""
|
|
32
|
+
BATCH_BYTES = 15 * 1024 * 1024
|
|
33
|
+
"""Where a batch closes (the contract's ``otlp.limits.exportBatchBytes``): headroom
|
|
34
|
+
for the resource, framing and estimate error."""
|
|
35
|
+
PAYLOAD_BUDGET = 64 * 1024 * 1024
|
|
36
|
+
"""Payload text one queue may hold, the batch in flight included."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _unweighted(_value: object) -> tuple[int, int]:
|
|
40
|
+
return 0, 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class _Record(Generic[T]):
|
|
45
|
+
sequence: int
|
|
46
|
+
value: T
|
|
47
|
+
size: int
|
|
48
|
+
payload: int
|
|
49
|
+
|
|
25
50
|
|
|
26
51
|
@dataclass(frozen=True)
|
|
27
52
|
class QueueStats:
|
|
@@ -32,7 +57,7 @@ class QueueStats:
|
|
|
32
57
|
|
|
33
58
|
|
|
34
59
|
class _Batch(Generic[T]):
|
|
35
|
-
def __init__(self, records: list[
|
|
60
|
+
def __init__(self, records: list[_Record[T]]) -> None:
|
|
36
61
|
self.records = records
|
|
37
62
|
self.dropped = False
|
|
38
63
|
|
|
@@ -45,14 +70,27 @@ class ExportQueue(Generic[T]):
|
|
|
45
70
|
export: Callable[[Sequence[T]], bool],
|
|
46
71
|
report: Callable[[CaptureCode, int], None],
|
|
47
72
|
shutdown_exporter: Callable[[], None],
|
|
73
|
+
*,
|
|
74
|
+
weigh: Callable[[T], tuple[int, int]] = _unweighted,
|
|
75
|
+
strip: Callable[[T], T] | None = None,
|
|
76
|
+
batch_bytes: int = BATCH_BYTES,
|
|
77
|
+
payload_budget: int = PAYLOAD_BUDGET,
|
|
48
78
|
) -> None:
|
|
79
|
+
"""``weigh`` gives a record's estimated encoded size and its payload bytes;
|
|
80
|
+
``strip`` returns it without its payloads."""
|
|
49
81
|
self._options = options
|
|
50
82
|
self._export = export
|
|
51
83
|
self._report = report
|
|
52
84
|
self._shutdown_exporter = shutdown_exporter
|
|
85
|
+
self._weigh = weigh
|
|
86
|
+
self._strip = strip
|
|
87
|
+
self._batch_bytes = batch_bytes
|
|
88
|
+
self._payload_budget = payload_budget
|
|
53
89
|
self._lock = threading.Condition()
|
|
54
|
-
self._records: deque[
|
|
90
|
+
self._records: deque[_Record[T]] = deque()
|
|
55
91
|
self._active: _Batch[T] | None = None
|
|
92
|
+
self._queued_bytes = 0
|
|
93
|
+
self._payload = 0
|
|
56
94
|
self._accepted = 0
|
|
57
95
|
self._exported = 0
|
|
58
96
|
self._dropped = 0
|
|
@@ -82,6 +120,8 @@ class ExportQueue(Generic[T]):
|
|
|
82
120
|
self._lock = threading.Condition()
|
|
83
121
|
self._records = deque()
|
|
84
122
|
self._active = None
|
|
123
|
+
self._queued_bytes = 0
|
|
124
|
+
self._payload = 0
|
|
85
125
|
self._accepted = 0
|
|
86
126
|
self._exported = 0
|
|
87
127
|
self._dropped = 0
|
|
@@ -100,6 +140,8 @@ class ExportQueue(Generic[T]):
|
|
|
100
140
|
|
|
101
141
|
def add(self, value: T) -> bool:
|
|
102
142
|
"""Never waits for an export. False means the record was dropped."""
|
|
143
|
+
size, payload = self._weigh(value)
|
|
144
|
+
stripped = False
|
|
103
145
|
with self._lock:
|
|
104
146
|
retained = len(self._records) + (0 if self._active is None else len(self._active.records))
|
|
105
147
|
code: CaptureCode | None = None
|
|
@@ -108,15 +150,30 @@ class ExportQueue(Generic[T]):
|
|
|
108
150
|
elif retained >= self._options.max_records:
|
|
109
151
|
code = "queue_full"
|
|
110
152
|
if code is None:
|
|
153
|
+
if payload > 0 and self._payload + payload > self._payload_budget and self._strip is not None:
|
|
154
|
+
value = self._strip(value)
|
|
155
|
+
size, payload = self._weigh(value)
|
|
156
|
+
stripped = True
|
|
111
157
|
self._accepted += 1
|
|
112
158
|
self._pending += 1
|
|
113
|
-
self.
|
|
114
|
-
|
|
159
|
+
self._payload += payload
|
|
160
|
+
self._queued_bytes += size
|
|
161
|
+
self._records.append(_Record(self._accepted, value, size, payload))
|
|
162
|
+
if len(self._records) >= self._options.batch_size or self._queued_bytes >= self._batch_bytes:
|
|
115
163
|
self._lock.notify_all()
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
164
|
+
else:
|
|
165
|
+
self._dropped += 1
|
|
166
|
+
if code is not None:
|
|
167
|
+
self._report(code, 1)
|
|
168
|
+
return False
|
|
169
|
+
if stripped:
|
|
170
|
+
self._report("payload_budget", 1)
|
|
171
|
+
return True
|
|
172
|
+
|
|
173
|
+
def payload_room(self) -> bool:
|
|
174
|
+
"""False once the payload budget is spent: a new payload would be dropped."""
|
|
175
|
+
with self._lock:
|
|
176
|
+
return self._payload < self._payload_budget
|
|
120
177
|
|
|
121
178
|
def flush(self, timeout: float | None = None) -> None:
|
|
122
179
|
"""Attempts every record accepted when called. Delivery is not guaranteed."""
|
|
@@ -153,9 +210,9 @@ class ExportQueue(Generic[T]):
|
|
|
153
210
|
|
|
154
211
|
def _outstanding(self, target: int) -> bool:
|
|
155
212
|
active = self._active
|
|
156
|
-
if active is not None and not active.dropped and active.records[0]
|
|
213
|
+
if active is not None and not active.dropped and active.records[0].sequence <= target:
|
|
157
214
|
return True
|
|
158
|
-
return len(self._records) > 0 and self._records[0]
|
|
215
|
+
return len(self._records) > 0 and self._records[0].sequence <= target
|
|
159
216
|
|
|
160
217
|
def _wait(self, target: int, deadline: float) -> None:
|
|
161
218
|
count = 0
|
|
@@ -172,11 +229,13 @@ class ExportQueue(Generic[T]):
|
|
|
172
229
|
def _abort(self, target: int) -> int:
|
|
173
230
|
count = 0
|
|
174
231
|
active = self._active
|
|
175
|
-
if active is not None and not active.dropped and active.records[0]
|
|
232
|
+
if active is not None and not active.dropped and active.records[0].sequence <= target:
|
|
176
233
|
active.dropped = True
|
|
177
234
|
count += len(active.records)
|
|
178
|
-
while self._records and self._records[0]
|
|
179
|
-
self._records.popleft()
|
|
235
|
+
while self._records and self._records[0].sequence <= target:
|
|
236
|
+
record = self._records.popleft()
|
|
237
|
+
self._queued_bytes -= record.size
|
|
238
|
+
self._payload -= record.payload
|
|
180
239
|
count += 1
|
|
181
240
|
self._dropped += count
|
|
182
241
|
self._pending -= count
|
|
@@ -189,14 +248,21 @@ class ExportQueue(Generic[T]):
|
|
|
189
248
|
records = self._records
|
|
190
249
|
if not records:
|
|
191
250
|
return None
|
|
192
|
-
|
|
251
|
+
full = len(records) >= size or self._queued_bytes >= self._batch_bytes
|
|
252
|
+
if not self._closed and not full and records[0].sequence > self._force:
|
|
193
253
|
return None
|
|
194
|
-
count =
|
|
254
|
+
count = 0
|
|
255
|
+
total = 0
|
|
256
|
+
# Closes before the estimate would pass the limit; a record is never split.
|
|
257
|
+
while count < min(len(records), size) and (count == 0 or total + records[count].size <= self._batch_bytes):
|
|
258
|
+
total += records[count].size
|
|
259
|
+
count += 1
|
|
195
260
|
# A partial batch never sweeps in records accepted after the flush that forced it.
|
|
196
|
-
if not self._closed and records[0]
|
|
197
|
-
while count > 1 and records[count - 1]
|
|
261
|
+
if not self._closed and records[0].sequence <= self._force:
|
|
262
|
+
while count > 1 and records[count - 1].sequence > self._force:
|
|
198
263
|
count -= 1
|
|
199
264
|
batch = _Batch([records.popleft() for _ in range(count)])
|
|
265
|
+
self._queued_bytes -= sum(record.size for record in batch.records)
|
|
200
266
|
self._active = batch
|
|
201
267
|
return batch
|
|
202
268
|
|
|
@@ -216,13 +282,14 @@ class ExportQueue(Generic[T]):
|
|
|
216
282
|
else:
|
|
217
283
|
self._lock.wait(remaining)
|
|
218
284
|
batch = self._next_batch()
|
|
219
|
-
values = [value for
|
|
285
|
+
values = [record.value for record in batch.records]
|
|
220
286
|
try:
|
|
221
287
|
succeeded = self._export(values)
|
|
222
288
|
except Exception: # noqa: BLE001 - a failed export is reported as loss, never raised
|
|
223
289
|
succeeded = False
|
|
224
290
|
with self._lock:
|
|
225
291
|
count = len(batch.records)
|
|
292
|
+
self._payload -= sum(record.payload for record in batch.records)
|
|
226
293
|
reported = not batch.dropped
|
|
227
294
|
if reported:
|
|
228
295
|
self._pending -= count
|
|
@@ -230,6 +297,9 @@ class ExportQueue(Generic[T]):
|
|
|
230
297
|
self._exported += count
|
|
231
298
|
else:
|
|
232
299
|
self._dropped += count
|
|
300
|
+
# Released before flush() can wake: once it returns, delivered
|
|
301
|
+
# records, payloads included, are no longer held here.
|
|
302
|
+
del values, batch
|
|
233
303
|
self._active = None
|
|
234
304
|
self._lock.notify_all()
|
|
235
305
|
if reported and not succeeded:
|