agentrail-python 0.2.0__py3-none-any.whl → 0.4.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.
@@ -1,8 +1,8 @@
1
1
  # Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.
2
2
  """Agentrail for Python: backend journey evidence over OpenTelemetry.
3
3
 
4
- Standalone: ``agentrail = init(Options(...))``. With an existing OpenTelemetry
5
- setup: ``create_processors(Options(...))``, then ``bind`` your provider.
4
+ ``agentrail = init(Options(...))``, the same with or without Sentry, Datadog or
5
+ an OpenTelemetry setup of your own: Agentrail registers no OpenTelemetry global.
6
6
  """
7
7
 
8
8
  from ._client import Client, Diagnostics, MilestoneScope
@@ -30,7 +30,6 @@ from ._options import (
30
30
  VerifiedIdentity,
31
31
  )
32
32
  from ._privacy import StructuredLog
33
- from ._processors import Processors, create_processors
34
33
  from ._queue import QueueStats
35
34
  from ._version import VERSION
36
35
 
@@ -57,12 +56,10 @@ __all__ = [
57
56
  "PerformanceContext",
58
57
  "PluginInvocation",
59
58
  "PrincipalKind",
60
- "Processors",
61
59
  "QueueOptions",
62
60
  "QueueStats",
63
61
  "StructuredLog",
64
62
  "Surface",
65
63
  "VerifiedIdentity",
66
- "create_processors",
67
64
  "init",
68
65
  ]
@@ -0,0 +1,173 @@
1
+ # Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.
2
+ """The header a customer's CLI sends its own API, as a server reads it.
3
+
4
+ ``agentrail-cli-sdk`` writes ``x-agentrail-cli``, an RFC 9651 Dictionary naming
5
+ the command an agent ran, the run, the session and the agent. This reads it as
6
+ agentrail-core's ``readCliHeader`` and agentrail-go do (the contract's
7
+ ``cliHeader``), and turns it into the span attributes the collector reads
8
+ (``otlp.cliAttributes``), the session only as its keyed hash.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from collections.abc import Callable, Mapping
15
+ from dataclasses import dataclass
16
+
17
+ import http_sf
18
+
19
+ from ._runtime import Attributes
20
+
21
+ CLI_HEADER = "x-agentrail-cli" # also in ``_handoff.AGENTRAIL_HEADERS``
22
+
23
+ _TEXT = re.compile(r"[\x20-\x7e]{1,64}")
24
+ _COMMAND = re.compile(r"[\x20-\x7e]{1,128}")
25
+ _RUN = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
26
+ _SESSION = re.compile(r"[0-9a-f]{32}")
27
+ _AGENT = re.compile(r"[a-z0-9._-]{1,64}")
28
+ _VARIABLE = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,63}")
29
+ _SESSION_SOURCES = ("agent", "ci", "local", "run")
30
+ _MODES = ("agent", "ci", "interactive", "non-interactive")
31
+ # The largest Integer RFC 9651 holds, and the most evidence a header names.
32
+ _MAX_INTEGER = 999_999_999_999_999
33
+ _MAX_EVIDENCE = 8
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class CliHeader:
38
+ sdk_version: str
39
+ cli: str
40
+ run: str
41
+ sequence: int
42
+ session: str
43
+ session_from: str
44
+ mode: str
45
+ cli_version: str | None = None
46
+ agent: str | None = None
47
+ agent_version: str | None = None
48
+ evidence: tuple[str, ...] | None = None
49
+ command: str | None = None
50
+
51
+
52
+ class _Unread(Exception):
53
+ """A header no CLI SDK writes: it reads as nothing."""
54
+
55
+
56
+ def _item(members: Mapping[str, object], key: str) -> object:
57
+ member = members.get(key)
58
+ if not isinstance(member, tuple) or len(member) != 2: # pyright: ignore[reportUnknownArgumentType]
59
+ raise _Unread(key)
60
+ return member[0] # pyright: ignore[reportUnknownVariableType]
61
+
62
+
63
+ def _string(members: Mapping[str, object], key: str, pattern: re.Pattern[str]) -> str:
64
+ value = _item(members, key)
65
+ # A Token or a Display String is no String, though each holds text.
66
+ if type(value) is not str or pattern.fullmatch(value) is None:
67
+ raise _Unread(key)
68
+ return value
69
+
70
+
71
+ def _optional(members: Mapping[str, object], key: str, pattern: re.Pattern[str]) -> str | None:
72
+ return _string(members, key, pattern) if key in members else None
73
+
74
+
75
+ def _token(members: Mapping[str, object], key: str, allowed: tuple[str, ...]) -> str:
76
+ value = _item(members, key)
77
+ if not isinstance(value, http_sf.Token) or str(value) not in allowed:
78
+ raise _Unread(key)
79
+ return str(value)
80
+
81
+
82
+ def _integer(members: Mapping[str, object], key: str, low: int, high: int) -> int:
83
+ value = _item(members, key)
84
+ # bool is an int in Python; a Boolean is no Integer.
85
+ if type(value) is not int or not low <= value <= high:
86
+ raise _Unread(key)
87
+ return value
88
+
89
+
90
+ def _evidence(members: Mapping[str, object]) -> tuple[str, ...] | None:
91
+ if "ev" not in members:
92
+ return None
93
+ items = _item(members, "ev")
94
+ if not isinstance(items, list):
95
+ raise _Unread("ev")
96
+ entries: list[object] = items # pyright: ignore[reportUnknownVariableType]
97
+ if not 1 <= len(entries) <= _MAX_EVIDENCE:
98
+ raise _Unread("ev")
99
+ names: list[str] = []
100
+ for entry in entries:
101
+ if not isinstance(entry, tuple):
102
+ raise _Unread("ev")
103
+ parts: tuple[object, ...] = entry # pyright: ignore[reportUnknownVariableType]
104
+ name = parts[0]
105
+ if type(name) is not str or _VARIABLE.fullmatch(name) is None:
106
+ raise _Unread("ev")
107
+ names.append(name)
108
+ return tuple(names)
109
+
110
+
111
+ def read_cli_header(value: str | None) -> CliHeader | None:
112
+ """What the header says, or None for none, or one that is not a CLI header of
113
+ any version: not a Dictionary, a member missing, one outside the contract's
114
+ rules, or one given twice, as two header lines a server joined are. Any ``v``
115
+ from 1 is read, and members this version does not know are ignored."""
116
+ if value is None:
117
+ return None
118
+ repeated: list[str] = []
119
+ try:
120
+ members = http_sf.parse(
121
+ value.encode("latin-1"),
122
+ tltype="dictionary",
123
+ on_duplicate_key=lambda key, _context: repeated.append(key),
124
+ )
125
+ except (http_sf.StructuredFieldError, UnicodeEncodeError):
126
+ return None
127
+ if repeated or not isinstance(members, dict):
128
+ return None
129
+ fields: Mapping[str, object] = members
130
+ try:
131
+ _integer(fields, "v", 1, _MAX_INTEGER)
132
+ return CliHeader(
133
+ sdk_version=_string(fields, "sdk", _TEXT),
134
+ cli=_string(fields, "cli", _TEXT),
135
+ run=_string(fields, "run", _RUN),
136
+ sequence=_integer(fields, "seq", 1, _MAX_INTEGER),
137
+ session=_string(fields, "ses", _SESSION),
138
+ session_from=_token(fields, "sesfrom", _SESSION_SOURCES),
139
+ mode=_token(fields, "mode", _MODES),
140
+ cli_version=_optional(fields, "cliv", _TEXT),
141
+ agent=_optional(fields, "agent", _AGENT),
142
+ agent_version=_optional(fields, "agentv", _TEXT),
143
+ evidence=_evidence(fields),
144
+ command=_optional(fields, "cmd", _COMMAND),
145
+ )
146
+ except _Unread:
147
+ return None
148
+
149
+
150
+ def cli_attributes(value: str | None, keyed_hash: Callable[[str], str]) -> Attributes:
151
+ """The request's CLI facts as span attributes; empty for a header that does not read."""
152
+ header = read_cli_header(value)
153
+ if header is None:
154
+ return {}
155
+ attributes: Attributes = {
156
+ "agentrail.cli.name": header.cli,
157
+ "agentrail.cli.run_id": header.run,
158
+ "agentrail.cli.sequence": header.sequence,
159
+ "agentrail.cli.mode": header.mode,
160
+ "agentrail.cli.session.id_hash": keyed_hash(header.session),
161
+ "agentrail.cli.session.source": header.session_from,
162
+ "agentrail.cli.sdk.version": header.sdk_version,
163
+ }
164
+ for key, optional in (
165
+ ("agentrail.cli.version", header.cli_version),
166
+ ("agentrail.cli.command", header.command),
167
+ ("agentrail.cli.agent.name", header.agent),
168
+ ("agentrail.cli.agent.version", header.agent_version),
169
+ ("agentrail.cli.agent.evidence", None if header.evidence is None else ",".join(header.evidence)),
170
+ ):
171
+ if optional is not None:
172
+ attributes[key] = optional
173
+ return attributes
@@ -9,6 +9,7 @@ import re
9
9
  import threading
10
10
  import time
11
11
  from collections.abc import Callable
12
+ from contextvars import Token
12
13
  from dataclasses import dataclass
13
14
  from types import TracebackType
14
15
  from typing import TYPE_CHECKING, Any, TypeVar, cast
@@ -17,6 +18,7 @@ from opentelemetry import context as otel_context
17
18
  from opentelemetry import trace
18
19
  from opentelemetry.trace import Link, NonRecordingSpan, Span, SpanContext, SpanKind, StatusCode, TraceFlags
19
20
 
21
+ from ._cli import CLI_HEADER, cli_attributes
20
22
  from ._handoff import HANDOFF_HEADER, Refused, keyed_hash, parse_traceparent, verify
21
23
  from ._options import (
22
24
  LOCATION_SOURCES,
@@ -32,7 +34,7 @@ from ._options import (
32
34
  from ._performance import performance_attributes
33
35
  from ._privacy import StructuredLog, clean_context, copy_log
34
36
  from ._queue import ExportQueue, QueueStats
35
- from ._runtime import Attributes, Mark, McpEvidence, RequestState, Runtime
37
+ from ._runtime import Attributes, Mark, McpEvidence, RequestState, Runtime, attach, current, current_span, detach
36
38
  from ._suppression import suppressed
37
39
  from ._text import bounded, valid_text
38
40
  from ._version import VERSION
@@ -61,7 +63,8 @@ def _error_type(error: BaseException) -> str:
61
63
  class MilestoneScope:
62
64
  """A milestone around a block: ``with`` or ``async with``.
63
65
 
64
- The block's exception is recorded and re-raised unchanged.
66
+ The block's exception is recorded and re-raised unchanged. The
67
+ application's own current span stays current inside it.
65
68
  """
66
69
 
67
70
  def __init__(
@@ -72,6 +75,7 @@ class MilestoneScope:
72
75
  *,
73
76
  step: bool = True,
74
77
  mcp: McpEvidence | None = None,
78
+ link: SpanContext | None = None,
75
79
  ) -> None:
76
80
  client._validate_milestone(name, details) # pyright: ignore[reportPrivateUsage]
77
81
  self._client = client
@@ -79,15 +83,16 @@ class MilestoneScope:
79
83
  self._details = details
80
84
  self._step = step
81
85
  self._mcp = mcp
86
+ self._link = link
82
87
  self._span: Span | None = None
83
- self._token: object | None = None
88
+ self._token: Token[otel_context.Context] | None = None
84
89
 
85
90
  def __enter__(self) -> MilestoneScope:
86
91
  span, ctx = self._client._start( # pyright: ignore[reportPrivateUsage]
87
- self._name, self._details, step=self._step, mcp=self._mcp
92
+ self._name, self._details, step=self._step, mcp=self._mcp, link=self._link
88
93
  )
89
94
  self._span = span
90
- self._token = otel_context.attach(ctx)
95
+ self._token = attach(ctx)
91
96
  return self
92
97
 
93
98
  def __exit__(
@@ -106,7 +111,7 @@ class MilestoneScope:
106
111
  span.set_attribute("error.type", _error_type(exc))
107
112
  span.end()
108
113
  finally:
109
- otel_context.detach(cast(Any, token))
114
+ detach(token)
110
115
 
111
116
  async def __aenter__(self) -> MilestoneScope:
112
117
  return self.__enter__()
@@ -121,9 +126,10 @@ class MilestoneScope:
121
126
 
122
127
 
123
128
  class Client:
124
- """Records backend evidence with a bound tracer provider.
129
+ """Records backend evidence with Agentrail's own tracer provider.
125
130
 
126
- Get one from ``init`` or from ``create_processors(...).bind(provider)``.
131
+ Get one from ``init``. It registers no OpenTelemetry global and never
132
+ changes the application's current span.
127
133
  """
128
134
 
129
135
  def __init__(
@@ -221,33 +227,36 @@ class Client:
221
227
  *,
222
228
  step: bool = True,
223
229
  mcp: McpEvidence | None = None,
230
+ link: SpanContext | None = None,
224
231
  ) -> tuple[Span, otel_context.Context]:
232
+ """A milestone span parented on Agentrail's current span, and the context to make it current in."""
225
233
  performance = None
226
234
  if details.performance is not None:
227
235
  try:
228
236
  performance = performance_attributes(details.performance, self._runtime.options.input.hash_key)
229
237
  except ConfigurationError:
230
238
  self._runtime.report("invalid_performance", "context")
231
- base = otel_context.get_current()
239
+ base = current()
232
240
  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)
241
241
  if state is None:
242
- external = trace.get_current_span(base).get_span_context()
243
- links = [Link(clean_context(external))] if external.is_valid else []
242
+ # Its own managed scope: the application's span it runs in (its trace,
243
+ # an unrelated caller's) is a link, never the parent. When the message
244
+ # names a trace, a span on that trace is the library that continued it
245
+ # (the MCP SDK continues _meta in OpenTelemetry's context): one link.
246
+ external = trace.get_current_span().get_span_context()
247
+ continued = link is not None and external.trace_id == link.trace_id
248
+ links = [Link(clean_context(external))] if external.is_valid and not continued else []
244
249
  state = RequestState(links=links)
245
- # Its own managed scope: an unrelated caller's trace is a link, never the parent.
246
250
  base = otel_context.set_value(self._runtime.state_key, state, otel_context.Context())
247
251
  mark = Mark(name=name, details=details, performance=performance, identity=identity, step=step, mcp=mcp)
248
252
  marked = otel_context.set_value(self._runtime.mark_key, mark, base)
249
253
  parented = trace.get_current_span(base).get_span_context().is_valid
250
- span = self._tracer.start_span(name, context=marked, links=continued + ([] if parented else state.links))
254
+ links = [] if parented else list(state.links)
255
+ if link is not None:
256
+ # A trace the message itself names (an MCP client's _meta traceparent)
257
+ # is a link, never the parent.
258
+ links.append(Link(clean_context(link)))
259
+ span = self._tracer.start_span(name, context=marked, links=links)
251
260
  if not span.is_recording():
252
261
  self._runtime.report("entry_not_recording", "traces")
253
262
  return span, trace.set_span_in_context(span, base)
@@ -263,7 +272,7 @@ class Client:
263
272
  return
264
273
  span = None
265
274
  if state is not None:
266
- context = trace.get_current_span().get_span_context()
275
+ context = current_span().get_span_context()
267
276
  span = context if context.is_valid else None
268
277
  now = time.time_ns()
269
278
  self._logs.add(copy_log(entry, now, now, span, self._runtime))
@@ -345,6 +354,7 @@ class Client:
345
354
  remote_context = SpanContext(remote.trace_id, remote.span_id, True, TraceFlags(remote.flags & 1))
346
355
  ctx = trace.set_span_in_context(NonRecordingSpan(remote_context), ctx)
347
356
  state.location = self._location(request)
357
+ state.cli = cli_attributes(request.headers.get(CLI_HEADER), self._keyed_hash)
348
358
  ctx = otel_context.set_value(self._runtime.state_key, state, ctx)
349
359
  attributes: Attributes = {
350
360
  "http.request.method": request.method,
@@ -17,8 +17,16 @@ from dataclasses import dataclass
17
17
  from ._text import js_json, well_formed
18
18
 
19
19
  HANDOFF_HEADER = "x-agentrail-trace-handoff"
20
- # Headers a managed request never forwards as received.
21
- OWNED_HEADERS = ("traceparent", "tracestate", "baggage", "sentry-trace", HANDOFF_HEADER)
20
+ # Agentrail's own headers, which a managed call never sends on as the server
21
+ # received them: a handoff binds one request, and a CLI's x-agentrail-cli names
22
+ # its run and session to this server alone. Every other header is the
23
+ # application's, its tracers' included, and is left alone.
24
+ AGENTRAIL_HEADERS = (HANDOFF_HEADER, "x-agentrail-cli")
25
+ # What a call to an allowed origin loses with the application's traceparent,
26
+ # which the signed one replaces: the vendor state that belonged to it.
27
+ SIGNED_REPLACES = ("traceparent", "tracestate")
28
+ # What a managed call to the collector itself never carries.
29
+ COLLECTOR_STRIPPED = ("traceparent", "tracestate", "baggage", "sentry-trace", *AGENTRAIL_HEADERS)
22
30
  MAX_AGE_MS = 60_000
23
31
  _MAX_SAFE_INTEGER = 9_007_199_254_740_991
24
32
 
agentrail_python/_init.py CHANGED
@@ -1,35 +1,30 @@
1
1
  # Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.
2
- """Standalone startup: Agentrail owns the process's OpenTelemetry providers."""
2
+ """Startup: one Agentrail installation per process, beside whatever tracer the application runs."""
3
3
 
4
4
  from __future__ import annotations
5
5
 
6
+ import atexit
6
7
  import threading
7
- from dataclasses import replace
8
-
9
- from opentelemetry import _logs as otel_logs
10
- from opentelemetry import propagate, trace
11
- from opentelemetry._logs._internal import ProxyLoggerProvider # pyright: ignore[reportPrivateImportUsage]
12
- from opentelemetry.sdk._logs import LoggerProvider
13
- from opentelemetry.sdk.trace import TracerProvider
14
- from opentelemetry.sdk.trace.sampling import ALWAYS_ON
15
8
 
16
9
  from ._client import Client
17
10
  from ._options import ConfigurationError, Options
18
- from ._processors import Processors
11
+ from ._processors import build
19
12
 
20
13
  _lock = threading.Lock()
21
14
  _installed: tuple[Options, Client] | None = None
22
15
 
23
16
 
24
17
  def init(options: Options) -> Client:
25
- """Install Agentrail's tracer provider, logger provider and propagator globally.
26
-
27
- Call once at startup, before the application serves requests. The
28
- providers drain when the interpreter exits; call ``shutdown`` yourself after
29
- your server stops accepting requests to bound it. Calling it
30
- again with the same options object returns the same client. If the process
31
- already has an OpenTelemetry provider, build it with ``create_processors``
32
- instead.
18
+ """Start Agentrail with its own tracer provider and export queues.
19
+
20
+ Registers no OpenTelemetry global (tracer provider, logger provider,
21
+ propagator or context): Sentry, Datadog or the application's own
22
+ OpenTelemetry setup can start before or after it, unchanged. Call once at
23
+ startup, before the application serves requests. What is still queued is
24
+ sent when the interpreter exits; call ``shutdown`` yourself after your
25
+ server stops accepting requests to bound it. Calling it again with the same
26
+ options object returns the same client; other options are refused, since a
27
+ second installation would record every request twice.
33
28
  """
34
29
  global _installed
35
30
  with _lock:
@@ -37,28 +32,7 @@ def init(options: Options) -> Client:
37
32
  if _installed[0] is not options:
38
33
  raise ConfigurationError("Agentrail is already initialized. Reuse the original options and client.")
39
34
  return _installed[1]
40
- if not isinstance(trace.get_tracer_provider(), trace.ProxyTracerProvider):
41
- raise ConfigurationError(
42
- "A tracer provider is already installed. Wire create_processors into its construction instead."
43
- )
44
- if not isinstance(otel_logs.get_logger_provider(), ProxyLoggerProvider):
45
- raise ConfigurationError(
46
- "A logger provider is already installed. Use create_processors with the existing setup."
47
- )
48
- processors = Processors(options if options.propagator is not None else _with_base(options))
49
- provider = TracerProvider(sampler=processors.sampler(ALWAYS_ON))
50
- provider.add_span_processor(processors.span_processor)
51
- logger = LoggerProvider()
52
- logger.add_log_record_processor(processors.log_processor)
53
- client = processors.bind(provider)
54
- trace.set_tracer_provider(provider)
55
- otel_logs.set_logger_provider(logger)
56
- propagate.set_global_textmap(processors.propagator)
57
- client._on_shutdown.extend((provider.shutdown, logger.shutdown)) # pyright: ignore[reportPrivateUsage]
35
+ client = build(options)
36
+ atexit.register(client.shutdown)
58
37
  _installed = (options, client)
59
38
  return client
60
-
61
-
62
- def _with_base(options: Options) -> Options:
63
- """Unmanaged work keeps the process's existing propagator."""
64
- return replace(options, propagator=propagate.get_global_textmap())
@@ -8,14 +8,11 @@ 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, Any, Literal, TypedDict
11
+ from typing import Any, Literal, TypedDict
12
12
  from urllib.parse import SplitResult, urlsplit
13
13
 
14
14
  from ._text import valid_text, well_formed
15
15
 
16
- if TYPE_CHECKING:
17
- from opentelemetry.propagators.textmap import TextMapPropagator
18
-
19
16
  PrincipalKind = Literal["user", "agent_registration", "agent_instance", "oauth_client", "api_key"]
20
17
  PRINCIPAL_KINDS: frozenset[str] = frozenset(("user", "agent_registration", "agent_instance", "oauth_client", "api_key"))
21
18
  Surface = Literal["http", "mcp", "auth", "custom", "a2a", "genai", "payment", "edge", "firewall", "browser"]
@@ -126,7 +123,6 @@ class Options:
126
123
  incoming_location: Callable[[IncomingRequest], IPLocation | None] | None = None
127
124
  logs: LogsOptions = field(default_factory=LogsOptions)
128
125
  queue: QueueOptions = field(default_factory=QueueOptions)
129
- propagator: TextMapPropagator | None = None
130
126
  on_error: Callable[[CaptureError], None] | None = None
131
127
 
132
128
 
@@ -9,7 +9,16 @@ from typing import TYPE_CHECKING
9
9
 
10
10
  from opentelemetry.trace import Span, SpanKind, StatusCode
11
11
 
12
- from ._handoff import HANDOFF_HEADER, HandoffInputError, format_traceparent, sign
12
+ from ._handoff import (
13
+ AGENTRAIL_HEADERS,
14
+ COLLECTOR_STRIPPED,
15
+ HANDOFF_HEADER,
16
+ SIGNED_REPLACES,
17
+ HandoffInputError,
18
+ format_traceparent,
19
+ sign,
20
+ )
21
+ from ._runtime import current
13
22
 
14
23
  if TYPE_CHECKING:
15
24
  from ._client import Client
@@ -27,16 +36,26 @@ def origin(scheme: str, host: str, port: int | None) -> str:
27
36
 
28
37
  @dataclass
29
38
  class Outgoing:
30
- """``span`` is None when the call is not part of a managed operation."""
39
+ """``span`` is None when the call is not part of a managed operation.
40
+
41
+ The call is sent without the headers in ``remove``, then with ``headers``.
42
+ Neither changes the application's own request object: an HTTP client builds
43
+ a redirect from that, and the next destination is admitted on its own.
44
+ """
31
45
 
32
46
  span: Span | None
47
+ remove: tuple[str, ...] = ()
33
48
  headers: dict[str, str] = field(default_factory=lambda: {})
34
- strip: bool = False
49
+
50
+ @property
51
+ def changes(self) -> bool:
52
+ return bool(self.remove or self.headers)
35
53
 
36
54
 
37
55
  def begin(client: Client, method: str, destination: str, path: str, target: str, url: str) -> Outgoing:
38
- """Owned headers are always stripped from managed calls; only exact allowed
39
- origins receive a newly signed handoff."""
56
+ """A managed call keeps the application's headers, its tracers' included,
57
+ without Agentrail's own. Only an exact allowed origin receives a newly signed
58
+ handoff, whose traceparent replaces the application's."""
40
59
  runtime = client._runtime # pyright: ignore[reportPrivateUsage]
41
60
  if not client._managed(): # pyright: ignore[reportPrivateUsage]
42
61
  return Outgoing(None)
@@ -45,24 +64,27 @@ def begin(client: Client, method: str, destination: str, path: str, target: str,
45
64
  f"{options.endpoint_path}/v1/traces",
46
65
  f"{options.endpoint_path}/v1/logs",
47
66
  ):
48
- return Outgoing(None, strip=True)
67
+ return Outgoing(None, remove=COLLECTOR_STRIPPED)
49
68
  tracer = client._tracer # pyright: ignore[reportPrivateUsage]
50
69
  span = tracer.start_span(
51
70
  f"HTTP {method}",
71
+ context=current(),
52
72
  kind=SpanKind.CLIENT,
53
73
  attributes={"http.request.method": method, "url.full": url},
54
74
  )
55
- outgoing = Outgoing(span, strip=True)
56
- if destination in options.origins:
57
- context = span.get_span_context()
58
- parent = format_traceparent(context.trace_id, context.span_id, context.trace_flags)
59
- try:
60
- token = sign(options.input.hash_key, parent, method, target, time.time_ns() // 1_000_000)
61
- except HandoffInputError:
62
- runtime.report("handoff_refused", "context")
63
- else:
64
- outgoing.headers = {"traceparent": parent, HANDOFF_HEADER: token}
65
- return outgoing
75
+ if destination not in options.origins:
76
+ return Outgoing(span, remove=AGENTRAIL_HEADERS)
77
+ context = span.get_span_context()
78
+ parent = format_traceparent(context.trace_id, context.span_id, context.trace_flags)
79
+ try:
80
+ token = sign(options.input.hash_key, parent, method, target, time.time_ns() // 1_000_000)
81
+ except HandoffInputError:
82
+ # Nothing signed, nothing replaced: the call goes as to any other origin.
83
+ runtime.report("handoff_refused", "context")
84
+ return Outgoing(span, remove=AGENTRAIL_HEADERS)
85
+ return Outgoing(
86
+ span, remove=(*AGENTRAIL_HEADERS, *SIGNED_REPLACES), headers={"traceparent": parent, HANDOFF_HEADER: token}
87
+ )
66
88
 
67
89
 
68
90
  def finish(span: Span, status: int | None, error: BaseException | None) -> None:
@@ -132,6 +132,11 @@ def copy_span(span: ReadableSpan, meta: SpanMeta, runtime: Runtime) -> ReadableS
132
132
  attributes.update(meta.state.location)
133
133
  if kind == SpanKind.SERVER:
134
134
  attributes["agentrail.ingress.verified"] = meta.state.verified
135
+ # Only the request's own entry span: a CLI's header says nothing of the
136
+ # calls this server makes while answering it, nor of another server span.
137
+ this = span.get_span_context()
138
+ if this is not None and meta.state.entry is not None and this.span_id == meta.state.entry.span_id:
139
+ attributes.update(meta.state.cli)
135
140
  method = attributes.get("http.request.method")
136
141
  name = f"HTTP {method}" if isinstance(method, str) else "backend.operation"
137
142
  if mark is not None: