HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
trace context: a caller's W3C traceparent reaches the agent's environment and a child goes out on every model call (#537)
aswathase3e3ce7c9f48
diff --git a/README.md b/README.mdindex 15ef4fd5..8e4d3180 100644--- a/README.md+++ b/README.md@@ -209,6 +209,10 @@ curl --fail-with-body -sS "$HARNESSROUTER_BASE_URL/v1/responses" \The task and its transcript appear in the same workspace in the Console. Set `"stream": true` to receive server-sent events.+**Join a caller's trace to the task.**++Send the W3C Trace Context headers `traceparent` and `tracestate` on the request, and the task's model calls carry a child of that trace: the same trace id, a new span id and the sampled flag, so the provider's log and yours are one trace. A value that is not valid W3C syntax is dropped, never refused: a broken tracing header does not fail a task. `baggage` is never read and never leaves the instance.+**Retry a task without running it twice.**Send the same request with the same `Idempotency-Key` when retrying a task. For example, send this request twice using the URL and API key above (key generation needs Python 3):diff --git a/gateway/app.py b/gateway/app.pyindex 3897ee8f..5d5106e3 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -416,6 +416,20 @@ def _load_reasoning():reasoning = _load_reasoning()+def _load_tracecontext():+ """runner/tracecontext.py, by path, as _load_reasoning: the gateway checks the caller's trace+ context with the rules the runner applies before a provider sees it."""+ import importlib.util+ path = pathlib.Path(__file__).resolve().parents[1] / "runner" / "tracecontext.py"+ spec = importlib.util.spec_from_file_location("hr_tracecontext", path)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++tracecontext = _load_tracecontext()++def _reasoning_level(value, where: str = "") -> str:"""A level as the API takes it, "" for none given. A value that is not a level is refused whenit came with the request (`where` names the field) and read as none when it was stored."""@@ -8516,7 +8530,8 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, spartial_messages: bool = False, probe: dict | None = None,codex_appserver: bool = False,hv: dict | None = None,- environment: dict | None = None) -> tuple[str, list[dict], dict]:+ environment: dict | None = None,+ trace_ctx: dict | None = None) -> tuple[str, list[dict], dict]:"""Hydrate → run turn over the connection chain → translate events to `emit` → collect producedfiles → checkpoint + persist trace. Returns (status, produced_files, rec).model_req: the caller-selected model (honored over the connection default when provided)."""@@ -8747,7 +8762,11 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s# does not depend on the model chosen to write with. See _vision_auth."vision_auth": vision_auth,# codex streaming: run via the app-server protocol (item/agentMessage/delta)- "codex_appserver": bool(codex_appserver)}+ "codex_appserver": bool(codex_appserver),+ # The caller's W3C trace context (#473): the runner puts it in the CLI's+ # environment and gives the model calls a child of it. Empty when the caller sent+ # none, so a turn without a trace context sends none.+ **(trace_ctx or {})}# Stop requested while we were resolving the connection / provisioning the previous# attempt? Honor it BEFORE launching a CLI process (from any replica, via the one signal).if await _turn_cancelled(sid, org, translator.resp_id):@@ -9618,6 +9637,15 @@ def _ignored_request_fields(body: "CreateResponseBody") -> list[str]:return [f for f in _UNAPPLIED_REQUEST_FIELDS if getattr(body, f, None) is not None]+def _trace_context(traceparent: str | None, tracestate: str | None) -> dict:+ """The caller's W3C trace context (#473), as the runner's /turn takes it: the traceparent and,+ only with one, the tracestate. runner/tracecontext.py holds the rules, one copy for both+ services: a value that is not valid W3C syntax is dropped, never refused, since a broken tracing+ header must not fail a turn; and only these two headers are read. `baggage` carries the+ caller's own data to whoever reads it, and it never leaves the box."""+ return tracecontext.parse(traceparent, tracestate)++_IDEM_TERMINAL = {"completed", "failed", "incomplete", "cancelled", "error"}# The event name a terminal status gets on the wire. streaming.md §2.1 names all three; the@@ -9851,6 +9879,9 @@ async def create_response(body: CreateResponseBody, request: Request):_v = request.headers.get(_hn)if _v is not None:hdr_vals[_hn.lower()] = _v+ # The caller's W3C trace context (#473): read once here, carried to the runner with the turn.+ # `baggage` is never read — only these two headers may leave the box.+ trace_ctx = _trace_context(request.headers.get("traceparent"), request.headers.get("tracestate"))# Fail fast, not deep in the tool: if an ENABLED MCP server references $headers.{name} and this# request didn't supply that header, the tool call would fail opaquely (bad auth at the MCP).# Reject up-front instead, naming exactly what's missing and where it's needed.@@ -9961,8 +9992,12 @@ async def create_response(body: CreateResponseBody, request: Request):async def persist(status: str) -> None:if status != "running":await _browser_close(sid, "turn_end") # the turn's browser, if it opened one+ # The trace context is kept on the turn record under internal names: a leading+ # underscore is dropped by _strip_internal, so the caller's trace id never reaches the+ # response object the caller and the console read.stored = {**tr._response_obj(status), "_session_id": sid, "_org": org,- "_member": member, "_input": input_items, "_backend": backend}+ "_member": member, "_input": input_items, "_backend": backend,+ **{"_" + k: v for k, v in trace_ctx.items()}}await _resp_put(resp_id, stored, org, sid, body.previous_response_id, status, created_at, body.store)# Persist the turn as 'running' NOW so GET /v1/sessions/{sid}/turns surfaces the in-flight@@ -10001,7 +10036,8 @@ async def create_response(body: CreateResponseBody, request: Request):prompt=prompt, files_in=files_in, resume=resume, emit=bus_emit_bg,model_req=model_req, user_text=user_text, harness_id=harness_id,max_step=max_step, timeout_s=timeout_s, effort=effort, hdr_vals=hdr_vals,- partial_messages=want_partial, codex_appserver=want_appserver, hv=hv, probe=probe, environment=environment)+ partial_messages=want_partial, codex_appserver=want_appserver, hv=hv, probe=probe, environment=environment,+ trace_ctx=trace_ctx)end["status"] = status# A failed turn says why in the transcript, not only in the response record: fail()# carries the message as an error event, which the console prints under the answer.@@ -10055,7 +10091,8 @@ async def create_response(body: CreateResponseBody, request: Request):tr, org=org, member=member, sid=sid, backend=backend, chain=chain,prompt=prompt, files_in=files_in, resume=resume, emit=emit, model_req=model_req,user_text=user_text, harness_id=harness_id, max_step=max_step,- timeout_s=timeout_s, effort=effort, hdr_vals=hdr_vals, partial_messages=want_partial, codex_appserver=want_appserver, hv=hv, probe=probe, environment=environment)+ timeout_s=timeout_s, effort=effort, hdr_vals=hdr_vals, partial_messages=want_partial, codex_appserver=want_appserver, hv=hv, probe=probe, environment=environment,+ trace_ctx=trace_ctx)end["status"] = status# A failed turn says why in the transcript, not only in the response record: fail()# carries the message as an error event, which the console prints under the answer.@@ -10115,7 +10152,8 @@ async def create_response(body: CreateResponseBody, request: Request):tr, org=org, member=member, sid=sid, backend=backend, chain=chain,prompt=prompt, files_in=files_in, resume=resume, emit=bus_emit, model_req=model_req,user_text=user_text, harness_id=harness_id, max_step=max_step,- timeout_s=timeout_s, effort=effort, hdr_vals=hdr_vals, partial_messages=want_partial, codex_appserver=want_appserver, hv=hv, probe=probe, environment=environment)+ timeout_s=timeout_s, effort=effort, hdr_vals=hdr_vals, partial_messages=want_partial, codex_appserver=want_appserver, hv=hv, probe=probe, environment=environment,+ trace_ctx=trace_ctx)# A failed turn says why in the transcript, not only in the response record: fail()# carries the message as an error event, which the console prints under the answer.for ev in (tr.fail(_turn_failure_message(rec)) if status == "failed" else tr.complete(status, produced)):diff --git a/gateway/tests/test_trace_context.py b/gateway/tests/test_trace_context.pynew file mode 100644index 00000000..0dbd09f2--- /dev/null+++ b/gateway/tests/test_trace_context.py@@ -0,0 +1,264 @@+"""The caller's W3C trace context reaches the turn (#473).++A client that traces its own request sends `traceparent` (and often `tracestate`) on+`POST /v1/responses`. The gateway read none of them, so the trace stopped at the gateway's door:+the turn ran with no trace context, and the model calls the runner forwarded carried no trace+either, so the caller's trace never reached the provider's log and the two halves of one request+could not be joined.++Only `traceparent` and `tracestate` are read. `baggage` carries the caller's own data to whoever+reads it, and it never leaves the box. A malformed value is DROPPED, never refused: a broken+tracing header must not fail a turn.+"""+import asyncio+import json+import os+import pathlib+import sys+import time++import pytest+from fastapi.testclient import TestClient # noqa: E402++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+os.environ.setdefault("HR_BACKING", "local")+import app as gw # noqa: E402+++ORG = "org_e"++# A W3C traceparent: version 00, a trace id, a span id and the sampled flag.+TRACE_PARENT = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"+++def api(monkeypatch):+ async def principal(request):+ return {"org": ORG, "member": "me@local"}+ monkeypatch.setattr(gw, "_principal", principal)+ monkeypatch.setattr(gw, "_response_in_reach", lambda p, rec: asyncio.sleep(0, True))+ monkeypatch.setattr(gw, "_harness_in_reach", lambda p: asyncio.sleep(0, True))+ return TestClient(gw.app)+++# ── the helper ────────────────────────────────────────────────────────────────────────────────++def test_a_valid_traceparent_is_kept():+ assert gw._trace_context(TRACE_PARENT, "") == {"traceparent": TRACE_PARENT}+ # The spec's ids are lower-case hex (HEXDIGLC): an upper-case value is not a trace context, and+ # it is dropped rather than rewritten.+ assert gw._trace_context(TRACE_PARENT.upper(), "") == {}+++def test_a_malformed_traceparent_is_dropped_and_never_refused():+ """A broken tracing header must not fail a turn: it is dropped, and the helper cannot raise."""+ for bad in ("not-a-traceparent",+ "00-" + "0" * 32 + "-00f067aa0ba902b7-01", # an all-zero trace-id+ "00-4bf92f3577b34da6a3ce929d0e0e4736-" + "0" * 16 + "-01", # an all-zero span-id+ "ff-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", # version ff+ "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7", # no flags+ ""):+ assert gw._trace_context(bad, "vendor=1") == {}, f"{bad!r} was accepted as a trace context"+++def test_a_tracestate_without_a_traceparent_is_dropped():+ """A tracestate is state ABOUT a trace: with no trace there is nothing for it to hang on."""+ assert gw._trace_context("", "vendor=1") == {}+ assert gw._trace_context(None, "vendor=1") == {}+++def test_a_malformed_tracestate_is_dropped_but_the_traceparent_stays():+ """The vendor state is the expendable half: a member that does not parse costs the tracestate,+ not the trace."""+ assert gw._trace_context(TRACE_PARENT, "vendor=1") == {"traceparent": TRACE_PARENT, "tracestate": "vendor=1"}+ assert gw._trace_context(TRACE_PARENT, "not a member") == {"traceparent": TRACE_PARENT}+ assert gw._trace_context(TRACE_PARENT, "v=" + "x" * 300) == {"traceparent": TRACE_PARENT}+ assert gw._trace_context(TRACE_PARENT, ",".join(f"v{i}=1" for i in range(40))) == {"traceparent": TRACE_PARENT}+++def test_a_tracestate_follows_the_specs_rules_for_its_members():+ """A value may hold a space anywhere but its last character and must not be empty, and only+ one entry per key may exist."""+ assert gw._trace_context(TRACE_PARENT, "vendor=a b") == {"traceparent": TRACE_PARENT,+ "tracestate": "vendor=a b"}+ assert gw._trace_context(TRACE_PARENT, "vendor=") == {"traceparent": TRACE_PARENT}+ assert gw._trace_context(TRACE_PARENT, "vendor=1,vendor=2") == {"traceparent": TRACE_PARENT}+ assert gw._trace_context(TRACE_PARENT, "a=1,b=2") == {"traceparent": TRACE_PARENT,+ "tracestate": "a=1,b=2"}+++def test_a_newer_traceparent_version_keeps_its_trace():+ """The spec parses the first 55 characters of a version it does not know and ignores the rest,+ so a forward-compatible header keeps the caller's trace instead of losing it."""+ assert gw._trace_context("01-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01-extra", "") == {+ "traceparent": "01-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"}+ # Version `00` has no trailing data, so the extra makes the value invalid.+ assert gw._trace_context(TRACE_PARENT + "-extra", "") == {}+++def test_baggage_never_leaves():+ """`baggage` carries the caller's own data to whoever reads it, so it is never read here."""+ ctx = gw._trace_context(TRACE_PARENT, "vendor=1")+ assert "baggage" not in ctx and "baggage" not in json.dumps(ctx)+++# ── the turn request the runner receives ──────────────────────────────────────────────────────++def _drive_the_turn_body(monkeypatch, trace_ctx):+ """Run `_resp_execute` with the world's edges stubbed and return the body it handed the+ runner's /turn. The turn is driven end to end so the body is the real one."""+ seen: dict = {}++ async def _sandbox_json(path, sid, method="POST", body=None, **kw):+ if path == "/turn":+ seen["body"] = body+ return {"turn_id": "t1", "status": "running"}+ if path.startswith("/turn/"):+ return {"done": True, "status": "done", "events": [], "n_total": 0}+ return {}++ async def _nothing(*a, **kw):+ return None++ async def _get_connection(org, name):+ return ({"provider": "anthropic", "base_url": "https://proxy.example/v1"}, "tenant-1")++ async def _harness_plugins(*a, **kw):+ return ([], [], [], [], [])++ async def _harness_env(*a, **kw):+ return ({}, [])++ async def _image_auth(*a, **kw):+ return None++ def _auth_from_conn(*a, **kw):+ return {"token": "t", "base_url": "https://proxy.example/v1"}++ async def _turn_cancelled(*a, **kw):+ return False++ async def _collect_produced(*a, **kw):+ return []++ monkeypatch.setattr(gw, "_sandbox_json", _sandbox_json)+ monkeypatch.setattr(gw, "_vertex_get", _nothing)+ monkeypatch.setattr(gw, "_vertex_upsert", _nothing)+ monkeypatch.setattr(gw, "_hydrate", _nothing)+ monkeypatch.setattr(gw, "_harness_plugins", _harness_plugins)+ monkeypatch.setattr(gw, "_harness_env", _harness_env)+ monkeypatch.setattr(gw, "_image_auth", _image_auth)+ monkeypatch.setattr(gw, "_get_connection", _get_connection)+ monkeypatch.setattr(gw, "_auth_from_conn", _auth_from_conn)+ monkeypatch.setattr(gw, "_turn_cancelled", _turn_cancelled)+ monkeypatch.setattr(gw, "_collect_produced", _collect_produced)+ monkeypatch.setattr(gw, "_blob_put", _nothing)+ monkeypatch.setattr(gw, "_checkpoint", _nothing)+ monkeypatch.setattr(gw, "_trace_finalize", _nothing)+ monkeypatch.setattr(gw, "_browser_close", _nothing)+ monkeypatch.setattr(gw, "_recover_trace_cursor", _nothing)+ monkeypatch.setattr(gw, "RESP_POLL_S", 0)+ monkeypatch.setattr(gw.control_store, "enabled", lambda: False)++ translator = gw._RespTranslator("resp_trace", "m", None, True, time.time())+ status, _produced, rec = asyncio.run(gw._resp_execute(+ translator, org=ORG, member="me@local", sid="sess_trace", backend="claude",+ chain=["anthropic"], prompt="hi", files_in=[], resume=None, emit=lambda ev: asyncio.sleep(0),+ trace_ctx=trace_ctx))+ assert status == "completed", f"the turn did not run: {status} {rec.get('tried')}"+ assert seen.get("body") is not None, "the turn never reached the runner's /turn"+ return seen["body"]+++def test_the_trace_context_reaches_the_turn_request(monkeypatch):+ body = _drive_the_turn_body(monkeypatch, {"traceparent": TRACE_PARENT, "tracestate": "vendor=1"})+ assert body.get("traceparent") == TRACE_PARENT, (+ f"the /turn body carries {body.get('traceparent')!r} instead of the caller's traceparent")+ assert body.get("tracestate") == "vendor=1", (+ f"the /turn body carries {body.get('tracestate')!r} instead of the caller's tracestate")+++def test_a_turn_with_no_trace_context_carries_none(monkeypatch):+ body = _drive_the_turn_body(monkeypatch, None)+ assert "traceparent" not in body, f"the /turn body carries {body.get('traceparent')!r} with no trace in"+ assert "tracestate" not in body, f"the /turn body carries {body.get('tracestate')!r} with no trace in"+++# ── the request path ──────────────────────────────────────────────────────────────────────────++def test_the_request_path_reads_the_header_and_the_turn_record_keeps_it(api, monkeypatch):+ """The whole path, driven through the real endpoint: the header is read, the executor is+ handed it, the turn record keeps it, and the response object the caller gets does not."""+ monkeypatch.setattr(gw, "_base_catalog_get", lambda h: {"id": h, "base": "dsh"}, raising=False)++ async def _chain(org, backend, model):+ return [{"backend": backend}]+ monkeypatch.setattr(gw, "_resolve_chain", _chain)++ captured: dict = {}++ async def _exec(tr, **kw):+ captured.update(kw)+ return "completed", [], {}+ monkeypatch.setattr(gw, "_resp_execute", _exec)++ r = api.post("/v1/responses", json={"input": "hi", "harness_id": "h1"},+ headers={"traceparent": TRACE_PARENT, "tracestate": "vendor=1",+ "baggage": "userid=secret"})+ assert r.status_code == 200, r.text+ assert captured.get("trace_ctx") == {"traceparent": TRACE_PARENT, "tracestate": "vendor=1"}, (+ f"the executor was handed {captured.get('trace_ctx')!r}")++ rec = asyncio.run(gw._resp_get(r.json()["id"]))+ assert rec.get("_traceparent") == TRACE_PARENT, (+ f"the turn record carries {rec.get('_traceparent')!r} instead of the caller's traceparent")+ assert rec.get("_tracestate") == "vendor=1", (+ f"the turn record carries {rec.get('_tracestate')!r} instead of the caller's tracestate")+ assert "secret" not in json.dumps(rec), "the caller's baggage reached the turn record"++ public = gw._public_response(rec)+ assert "traceparent" not in public and "_traceparent" not in public, (+ "the trace context leaked into the response object the caller reads")+++def test_a_request_with_no_trace_header_keeps_none(api, monkeypatch):+ monkeypatch.setattr(gw, "_base_catalog_get", lambda h: {"id": h, "base": "dsh"}, raising=False)++ async def _chain(org, backend, model):+ return [{"backend": backend}]+ monkeypatch.setattr(gw, "_resolve_chain", _chain)++ captured: dict = {}++ async def _exec(tr, **kw):+ captured.update(kw)+ return "completed", [], {}+ monkeypatch.setattr(gw, "_resp_execute", _exec)++ r = api.post("/v1/responses", json={"input": "hi", "harness_id": "h1"})+ assert r.status_code == 200, r.text+ assert not captured.get("trace_ctx"), f"the executor was handed {captured.get('trace_ctx')!r}"+ rec = asyncio.run(gw._resp_get(r.json()["id"]))+ assert "_traceparent" not in rec and "_tracestate" not in rec, (+ f"the turn record carries {rec.get('_traceparent')!r} with no trace in")+++def test_a_malformed_trace_header_does_not_refuse_the_request(api, monkeypatch):+ """A broken tracing header is dropped, never refused: the turn still runs."""+ monkeypatch.setattr(gw, "_base_catalog_get", lambda h: {"id": h, "base": "dsh"}, raising=False)++ async def _chain(org, backend, model):+ return [{"backend": backend}]+ monkeypatch.setattr(gw, "_resolve_chain", _chain)++ captured: dict = {}++ async def _exec(tr, **kw):+ captured.update(kw)+ return "completed", [], {}+ monkeypatch.setattr(gw, "_resp_execute", _exec)++ r = api.post("/v1/responses", json={"input": "hi", "harness_id": "h1"},+ headers={"traceparent": "not-a-traceparent"})+ assert r.status_code == 200, r.text+ assert not captured.get("trace_ctx"), f"the executor was handed {captured.get('trace_ctx')!r}"diff --git a/runner/server.py b/runner/server.pyindex 67be70e2..58a78f68 100644--- a/runner/server.py+++ b/runner/server.py@@ -84,6 +84,7 @@ from pydantic import BaseModelimport environments # the read-only project layer a turn may name (runner/environments.py)import reasoning # how much a model thinks on a turn: levels and what sets them (runner/reasoning.py)+import tracecontext # the caller's W3C trace context: its checks and a child for the relay (#473)app = FastAPI(title="harness-runner")@@ -3893,6 +3894,23 @@ _HERMES_RELAY: dict = {"server": None, "port": 0, "routes": {}, "lock": threadin_TURN_THINKING: contextvars.ContextVar[dict | None] = contextvars.ContextVar("hr_turn_thinking", default=None)+# The caller's W3C trace context (#473), for the turn being built: {"traceparent": ..., "tracestate":+# ...}. The relay's routes are registered on the thread that runs /turn, so a context variable is+# what carries the context from the request to the routes — the relay serves each call on a thread+# of its own, where a context variable would not be visible.+_TURN_TRACE: contextvars.ContextVar[dict | None] = contextvars.ContextVar("hr_turn_trace", default=None)+++def _route_trace_flag() -> dict:+ """The turn's trace context, as a route flag. Every route of the turn carries it, so the relay+ gives the provider request a child of the caller's span whichever way the route was made."""+ trace = _TURN_TRACE.get() or {}+ if not trace.get("traceparent"):+ return {}+ return {"traceparent": trace["traceparent"],+ **({"tracestate": trace["tracestate"]} if trace.get("tracestate") else {})}++def _turn_route(flags: dict) -> dict:"""A route's flags, remembered as one of the routes of the turn being built."""t = _TURN_THINKING.get()@@ -5260,10 +5278,35 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):returntail = self.path.removeprefix("/v1") if self.path.startswith("/v1/") else self.pathdrop = {"host", "content-length", "authorization", "x-goog-api-key", "x-api-key", "connection",- "accept-encoding", "transfer-encoding"}+ "accept-encoding", "transfer-encoding", "baggage"}headers = {k: v for k, v in self.headers.items() if k.lower() not in drop}headers["authorization"] = f"Bearer {key}"headers.setdefault("accept", "*/*")+ # The turn's trace context, as a child of it: the same trace id, a new span id (this hop is+ # a span of its own), the sampled flag kept. The client's own header is replaced, not left+ # beside it — two traceparents would leave the provider unable to say which span is which.+ # A turn with no trace context sends none of its own, and the client's headers go upstream+ # exactly as they did before: the relay changes nothing it was not asked to change.+ #+ # The turn's context is the trace's root here: the caller's trace id is never taken from+ # the client. A CLI that read TRACEPARENT from its environment has already made a child of+ # the caller's span, and the provider's request belongs under THAT span — so the CLI's own+ # header is the parent when it carries the caller's trace id, and is ignored otherwise.+ parent = str(flags.get("traceparent") or "")+ inbound = next((v for k, v in headers.items() if k.lower() == "traceparent"), "")+ if parent:+ if tracecontext.trace_id(inbound) and tracecontext.trace_id(inbound) == tracecontext.trace_id(parent):+ parent = inbound+ child = tracecontext.child(parent)+ if child:+ for _k in [k for k in headers if k.lower() == "traceparent"]:+ del headers[_k]+ headers["traceparent"] = child+ state = str(flags.get("tracestate") or "")+ for _k in [k for k in headers if k.lower() == "tracestate"]:+ del headers[_k]+ if state:+ headers["tracestate"] = stateif flags.get("passthrough"):self._passthrough(base, key, tail, headers, body)return@@ -5976,7 +6019,8 @@ def _qoder_relay_route(base_url: str, api_key: str) -> tuple[str, str]:threading.Thread(target=srv.serve_forever, daemon=True).start()_HERMES_RELAY["server"], _HERMES_RELAY["port"] = srv, srv.server_address[1]tok = "hr-relay-" + uuid.uuid4().hex- _HERMES_RELAY["routes"][tok] = ((base_url or "").rstrip("/"), api_key, _turn_route({"passthrough": True}))+ _HERMES_RELAY["routes"][tok] = ((base_url or "").rstrip("/"), api_key,+ _turn_route({"passthrough": True, **_route_trace_flag()}))return f"http://127.0.0.1:{_HERMES_RELAY['port']}/v1", tok@@ -5988,7 +6032,8 @@ def _bedrock_anthropic_route(origin: str, api_key: str) -> tuple[str, str]:threading.Thread(target=srv.serve_forever, daemon=True).start()_HERMES_RELAY["server"], _HERMES_RELAY["port"] = srv, srv.server_address[1]tok = "hr-relay-" + uuid.uuid4().hex- _HERMES_RELAY["routes"][tok] = (origin, api_key, {"bedrock_anthropic": True})+ _HERMES_RELAY["routes"][tok] = (origin, api_key,+ {"bedrock_anthropic": True, **_route_trace_flag()})return f"http://127.0.0.1:{_HERMES_RELAY['port']}/v1", tok@@ -6129,7 +6174,8 @@ def _gemini_relay_route(host_root: str, api_key: str, model: str = "", native_motok = "hr-relay-" + uuid.uuid4().hex_HERMES_RELAY["routes"][tok] = (host_root.rstrip("/"), api_key,_turn_route({"google_native": True, "model": model,- "native_model": native_model, **_turn_effort()}))+ "native_model": native_model, **_turn_effort(),+ **_route_trace_flag()}))return f"http://127.0.0.1:{_HERMES_RELAY['port']}/v1", tok@@ -6168,6 +6214,9 @@ def _hermes_relay_route(base_url: str, api_key: str, drop_fields: tuple[str, ..."stream_usage": bool(stream_usage), "gemini_schemas": bool(gemini_schemas),"usage_no_nulls": bool(usage_no_nulls), "plain_stream": bool(plain_stream),**({"aux": True} if aux else _turn_effort())}+ # The turn's trace context (#473), on every route of this turn: the relay reads it when it+ # forwards, and the relay's own threads never see the turn's context variables.+ flags.update(_route_trace_flag())_HERMES_RELAY["routes"][tok] = (upstream, api_key, flags if aux else _turn_route(flags))return f"http://127.0.0.1:{_HERMES_RELAY['port']}/v1", tok@@ -9336,7 +9385,7 @@ def _systemone_relay_route(provider: str, base_url: str, api_key: str) -> tuple[threading.Thread(target=srv.serve_forever, daemon=True).start()_HERMES_RELAY["server"], _HERMES_RELAY["port"] = srv, srv.server_address[1]tok = "hr-relay-" + uuid.uuid4().hex- _HERMES_RELAY["routes"][tok] = (base, api_key, {})+ _HERMES_RELAY["routes"][tok] = (base, api_key, dict(_route_trace_flag()))return f"http://127.0.0.1:{_HERMES_RELAY['port']}/v1", tok@@ -13316,6 +13365,8 @@ class TurnReq(BaseModel):reasoning_effort: str | None = None # how much the model thinks this turn: one of reasoning.LEVELS; unset = the model's defaultreasoning_route: str | None = None # which measured provider the connection is (reasoning.ROUTES), from the gateway,# which knows it when the base here is a broker's; unset = read it off the base+ traceparent: str | None = None # the caller's W3C trace context (#473); unset = the turn has none+ tracestate: str | None = None # its vendor state for that trace; never `baggage`@app.post("/turn")@@ -13415,6 +13466,15 @@ def turn(req: TurnReq, identifier: str = "") -> dict:turn_thinking = {"asked": effort if effort in reasoning.LEVELS else "", "applied": "", "routes": [],"route": named if named in reasoning.ROUTES else ""}_TURN_THINKING.set(turn_thinking)+ # The caller's W3C trace context (#473). The CLI's environment carries it, so a tool in the turn+ # that speaks OpenTelemetry joins the caller's trace; the relay gives the model calls a child of+ # it. Nothing is set when the turn carried no context.+ turn_trace = tracecontext.parse(req.traceparent, req.tracestate)+ _TURN_TRACE.set(turn_trace)+ if turn_trace.get("traceparent"):+ env["TRACEPARENT"] = turn_trace["traceparent"]+ if turn_trace.get("tracestate"):+ env["TRACESTATE"] = turn_trace["tracestate"]# Image generation. Deliberately NOT the OPENAI_* names: on a codex harness those already# point at the CHAT connection, which is often a different provider, and one env pair can# only carry one credential. The imagegen skill's wrapper reads these and passes them to thediff --git a/runner/tests/test_hermes_relay.py b/runner/tests/test_hermes_relay.pyindex a422cee9..b6d3fadc 100644--- a/runner/tests/test_hermes_relay.py+++ b/runner/tests/test_hermes_relay.py@@ -15,7 +15,8 @@ import urllib.requestfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServersys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))-from server import _hermes_relay_route, _normalize_openai_chat_body # noqa: E402+import server as rs # noqa: E402+from server import Auth, _hermes_relay_route, _normalize_openai_chat_body # noqa: E402def _norm(obj):@@ -431,3 +432,284 @@ def test_probes_still_reach_a_local_server_behind_a_custom_connection():assert len(seen) == len(_PROBES)finally:up.shutdown()+++# ── the caller's trace context (#473) ─────────────────────────────────────────────────────────+# The gateway hands the runner the caller's W3C traceparent/tracestate. The relay puts a CHILD of+# the traceparent on the model calls it forwards — the same trace id, a new span id, so the+# provider's log joins the caller's trace and this hop is a span of its own. Only these two+# headers leave the box: `baggage` carries the caller's own data and never goes out. A malformed+# value is dropped, never forwarded, and never fails the turn.++TRACE_PARENT = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"+++def _relay_with_trace(upstream_port: int, trace: dict | None):+ """Register a route for a turn carrying `trace`, and return (relay base, placeholder token)."""+ token = rs._TURN_TRACE.set(trace or {})+ try:+ return rs._hermes_relay_route(f"http://127.0.0.1:{upstream_port}/v1", "sk-real")+ finally:+ rs._TURN_TRACE.reset(token)+++def _relay_upstream(seen: dict):+ """A fake provider that records the headers it was sent."""+ class Upstream(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def do_POST(self): # noqa: N802+ seen["traceparent"] = self.headers.get("traceparent")+ seen["tracestate"] = self.headers.get("tracestate")+ seen["baggage"] = self.headers.get("baggage")+ self.rfile.read(int(self.headers.get("content-length") or 0))+ data = b'{"ok": true}'+ self.send_response(200)+ self.send_header("content-type", "application/json")+ self.send_header("content-length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def log_message(self, *a):+ pass++ return Upstream+++def test_a_relayed_call_carries_a_child_of_the_callers_traceparent():+ seen = {}+ up = ThreadingHTTPServer(("127.0.0.1", 0), _relay_upstream(seen))+ threading.Thread(target=up.serve_forever, daemon=True).start()+ try:+ base, tok = _relay_with_trace(up.server_address[1], {"traceparent": TRACE_PARENT})+ body = json.dumps({"messages": [{"role": "user", "content": "hi"}]}).encode()+ req = urllib.request.Request(base + "/chat/completions", data=body, method="POST",+ headers={"authorization": f"Bearer {tok}",+ "content-type": "application/json"})+ urllib.request.urlopen(req, timeout=10).read()+ finally:+ up.shutdown()+ got = seen.get("traceparent")+ assert got, "the relayed call carried no traceparent at all"+ parts = got.split("-")+ assert len(parts) == 4, f"the relayed traceparent is not a W3C traceparent: {got!r}"+ version, trace_id, span_id, flags = parts+ assert version == "00", f"the child changed the trace version: {got!r}"+ assert trace_id == "4bf92f3577b34da6a3ce929d0e0e4736", f"the child lost the caller's trace: {got!r}"+ assert span_id != "00f067aa0ba902b7", f"the relay forwarded the caller's own span id: {got!r}"+ assert len(span_id) == 16 and span_id == span_id.lower() and all(c in "0123456789abcdef" for c in span_id), (+ f"the child's span id is not 16 lowercase hex characters: {got!r}")+ assert flags == "01", f"the child changed the sampled flag: {got!r}"+++def test_a_turn_with_no_trace_context_sends_no_traceparent():+ seen = {}+ up = ThreadingHTTPServer(("127.0.0.1", 0), _relay_upstream(seen))+ threading.Thread(target=up.serve_forever, daemon=True).start()+ try:+ base, tok = _relay_with_trace(up.server_address[1], None)+ body = json.dumps({"messages": [{"role": "user", "content": "hi"}]}).encode()+ req = urllib.request.Request(base + "/chat/completions", data=body, method="POST",+ headers={"authorization": f"Bearer {tok}",+ "content-type": "application/json"})+ urllib.request.urlopen(req, timeout=10).read()+ finally:+ up.shutdown()+ assert not seen.get("traceparent"), f"a turn with no trace context still sent {seen.get('traceparent')!r}"+++def test_a_malformed_traceparent_is_not_forwarded():+ seen = {}+ up = ThreadingHTTPServer(("127.0.0.1", 0), _relay_upstream(seen))+ threading.Thread(target=up.serve_forever, daemon=True).start()+ try:+ base, tok = _relay_with_trace(up.server_address[1], {"traceparent": "not-a-traceparent"})+ body = json.dumps({"messages": [{"role": "user", "content": "hi"}]}).encode()+ req = urllib.request.Request(base + "/chat/completions", data=body, method="POST",+ headers={"authorization": f"Bearer {tok}",+ "content-type": "application/json"})+ urllib.request.urlopen(req, timeout=10).read()+ finally:+ up.shutdown()+ assert not seen.get("traceparent"), f"a malformed traceparent was forwarded as {seen.get('traceparent')!r}"+++def test_the_turn_validates_the_trace_context_it_is_handed():+ """The runner is the last place before a provider sees the value, so it checks it itself: a+ header nobody can read is worth less than a turn."""+ assert rs.tracecontext.parse(TRACE_PARENT, "") == {"traceparent": TRACE_PARENT}+ assert rs.tracecontext.parse(TRACE_PARENT.upper(), "") == {} # lower-case hex only (HEXDIGLC)+ for bad in ("not-a-traceparent",+ "00-" + "0" * 32 + "-00f067aa0ba902b7-01", # an all-zero trace-id+ "00-4bf92f3577b34da6a3ce929d0e0e4736-" + "0" * 16 + "-01", # an all-zero span-id+ "ff-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", # version ff+ "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7", # no flags+ ""):+ assert rs.tracecontext.parse(bad, "vendor=1") == {}, f"{bad!r} was accepted as a trace context"+ # A tracestate is only ever read with a traceparent, and a malformed member drops the+ # tracestate alone — never the traceparent beside it.+ assert rs.tracecontext.parse("", "vendor=1") == {}+ assert rs.tracecontext.parse(TRACE_PARENT, "vendor=1") == {"traceparent": TRACE_PARENT, "tracestate": "vendor=1"}+ assert rs.tracecontext.parse(TRACE_PARENT, "not a member") == {"traceparent": TRACE_PARENT}+ # The spec's own rules for a member: a value may hold a space anywhere but its last character+ # and must not be empty, and only one entry per key may exist.+ assert rs.tracecontext.parse(TRACE_PARENT, "vendor=a b") == {"traceparent": TRACE_PARENT,+ "tracestate": "vendor=a b"}+ assert rs.tracecontext.parse(TRACE_PARENT, "vendor=") == {"traceparent": TRACE_PARENT}+ assert rs.tracecontext.parse(TRACE_PARENT, "vendor=1,vendor=2") == {"traceparent": TRACE_PARENT}+ assert rs.tracecontext.parse(TRACE_PARENT, "a=1,b=2") == {"traceparent": TRACE_PARENT,+ "tracestate": "a=1,b=2"}+ # A newer version may carry fields this code does not know yet: the spec parses the first 55+ # characters and ignores the rest, so the trace is kept. Version `00` has no trailing data.+ assert rs.tracecontext.parse("01-" + "4bf92f3577b34da6a3ce929d0e0e4736" + "-00f067aa0ba902b7-01-extra",+ "") == {"traceparent": "01-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"}+ assert rs.tracecontext.parse(TRACE_PARENT + "-extra", "") == {}+++def test_the_turn_hands_the_trace_context_to_the_cli(monkeypatch, tmp_path):+ """The CLI's own environment carries it, so a tool in the turn that speaks OpenTelemetry joins+ the caller's trace."""+ launched = []+ started = threading.Event()++ def _fake(*args):+ launched.append(args)+ started.set()+ monkeypatch.setattr(rs, "_run_hermes_bg", _fake)+ cwd = tmp_path / "w"+ cwd.mkdir()+ rs.turn(rs.TurnReq(backend="hermes", provider="anthropic", model="claude-haiku-4.5", prompt="hi",+ auth=Auth(api_key="sk-test", base_url="https://proxy.example/v1"),+ cwd=str(cwd), traceparent=TRACE_PARENT, tracestate="vendor=1"))+ assert started.wait(10), "the hermes turn was never launched"+ env = launched[-1][2]+ assert env.get("TRACEPARENT") == TRACE_PARENT, f"the CLI's env carries {env.get('TRACEPARENT')!r}"+ assert env.get("TRACESTATE") == "vendor=1", f"the CLI's env carries {env.get('TRACESTATE')!r}"+++def test_a_turn_with_no_trace_context_gives_the_cli_none(monkeypatch, tmp_path):+ launched = []+ started = threading.Event()++ def _fake(*args):+ launched.append(args)+ started.set()+ monkeypatch.setattr(rs, "_run_hermes_bg", _fake)+ cwd = tmp_path / "w"+ cwd.mkdir()+ rs.turn(rs.TurnReq(backend="hermes", provider="anthropic", model="claude-haiku-4.5", prompt="hi",+ auth=Auth(api_key="sk-test", base_url="https://proxy.example/v1"),+ cwd=str(cwd)))+ assert started.wait(10), "the hermes turn was never launched"+ env = launched[-1][2]+ assert "TRACEPARENT" not in env and "TRACESTATE" not in env, (+ f"a turn with no trace context still got {env.get('TRACEPARENT')!r} / {env.get('TRACESTATE')!r}")+++def test_every_route_of_the_turn_carries_the_trace_context(monkeypatch):+ """Every way a route is registered must carry the turn's traceparent, not just the one the+ hermes builders use. The relay mints the provider's child span from the route's flag, so a+ route registered without it sends the provider a request the caller's trace cannot be joined+ to — and the route that missed it would be whichever base nobody tested."""+ routes: dict = {}+ monkeypatch.setattr(rs, "_HERMES_RELAY", {"server": None, "port": 0, "routes": routes, "lock": threading.Lock()})+ token = rs._TURN_TRACE.set({"traceparent": TRACE_PARENT, "tracestate": "vendor=1"})+ try:+ rs._hermes_relay_route("https://proxy.example/v1", "sk-test")+ rs._qoder_relay_route("https://proxy.example/api/v1/cloud", "pat-test")+ rs._bedrock_anthropic_route("https://bedrock.example", "sk-test")+ rs._gemini_relay_route("https://generativelanguage.example", "sk-test", "gemini-4-argon", "gemini-4-argon")+ rs._systemone_relay_route("openrouter", "https://openrouter.example/api/v1", "sk-test")+ finally:+ rs._TURN_TRACE.reset(token)++ assert routes, "no route was registered"+ for tok, (_base, _key, flags) in routes.items():+ assert flags.get("traceparent") == TRACE_PARENT, (+ f"the route {tok} carries {flags.get('traceparent')!r} instead of the caller's traceparent")+++def _relay_call(headers: dict | None = None) -> dict:+ """Send one call through the relay to a fake provider, and return what the provider saw."""+ seen: dict = {}+ up = ThreadingHTTPServer(("127.0.0.1", 0), _relay_upstream(seen))+ threading.Thread(target=up.serve_forever, daemon=True).start()+ try:+ base, tok = _relay_with_trace(up.server_address[1], {"traceparent": TRACE_PARENT,+ "tracestate": "vendor=1"})+ body = json.dumps({"messages": [{"role": "user", "content": "hi"}]}).encode()+ req = urllib.request.Request(base + "/chat/completions", data=body, method="POST",+ headers={"authorization": f"Bearer {tok}",+ "content-type": "application/json",+ **(headers or {})})+ urllib.request.urlopen(req, timeout=10).read()+ finally:+ up.shutdown()+ return seen+++def test_a_client_cannot_replace_the_callers_trace_id():+ """The turn's context is the trace's root: the caller's trace id is never taken from the+ client. A client that sends a traceparent of its own would otherwise send the provider a+ request under a different trace, which the caller's trace cannot be joined to."""+ foreign = "00-11111111111111111111111111111111-2222222222222222-01"+ seen = _relay_call({"traceparent": foreign})+ got = seen.get("traceparent")+ assert got, "the relayed call carried no traceparent at all"+ assert got.split("-")[1] == "4bf92f3577b34da6a3ce929d0e0e4736", (+ f"the provider got {got!r}: the client's own trace id replaced the caller's")+ assert got.split("-")[1] != foreign.split("-")[1], f"the provider got the client's trace: {got!r}"+++def test_a_clients_own_child_of_the_callers_trace_is_the_parent():+ """A CLI that read TRACEPARENT from its environment has already made a child of the caller's+ span, and the provider's request belongs under THAT span: the same trace id, a new span id."""+ child = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"+ seen = _relay_call({"traceparent": child})+ got = seen.get("traceparent")+ assert got, "the relayed call carried no traceparent at all"+ assert got.split("-")[1] == "4bf92f3577b34da6a3ce929d0e0e4736", f"the provider got {got!r}"+ assert got.split("-")[2] != "00f067aa0ba902b7", f"the relay forwarded the CLI's own span id: {got!r}"+++def test_a_malformed_client_traceparent_does_not_reach_the_provider():+ """A header nobody can read is worth less than a turn: the client's own value is dropped and+ the provider gets the caller's trace, not the client's all-zero one."""+ seen = _relay_call({"traceparent": "00-" + "0" * 32 + "-00f067aa0ba902b7-01"})+ got = seen.get("traceparent")+ assert got, "the relayed call carried no traceparent at all"+ assert got.split("-")[1] == "4bf92f3577b34da6a3ce929d0e0e4736", f"the provider got {got!r}"+++def test_baggage_never_reaches_the_provider():+ """`baggage` carries the caller's own data to whoever reads it, and it does not leave the+ box — not even the client's own."""+ seen = _relay_call({"baggage": "userid=secret,tenant=acme"})+ assert not seen.get("baggage"), f"the provider got baggage {seen.get('baggage')!r}"+++def test_the_callers_tracestate_reaches_the_provider():+ """The tracestate is the caller's vendor state for that trace, and the provider is the other+ end of it."""+ seen = _relay_call()+ assert seen.get("tracestate") == "vendor=1", f"the provider got {seen.get('tracestate')!r}"+++def test_a_turn_with_no_trace_context_leaves_the_clients_headers_alone():+ """No header in means nothing out: a turn with no trace context changes nothing, so a client+ that traces already keeps the span it made."""+ seen: dict = {}+ up = ThreadingHTTPServer(("127.0.0.1", 0), _relay_upstream(seen))+ threading.Thread(target=up.serve_forever, daemon=True).start()+ try:+ base, tok = _relay_with_trace(up.server_address[1], None)+ body = json.dumps({"messages": [{"role": "user", "content": "hi"}]}).encode()+ req = urllib.request.Request(base + "/chat/completions", data=body, method="POST",+ headers={"authorization": f"Bearer {tok}",+ "content-type": "application/json",+ "traceparent": TRACE_PARENT})+ urllib.request.urlopen(req, timeout=10).read()+ finally:+ up.shutdown()+ assert seen.get("traceparent") == TRACE_PARENT, (+ f"a turn with no trace context changed the client's own header: {seen.get('traceparent')!r}")diff --git a/runner/tests/test_tracecontext.py b/runner/tests/test_tracecontext.pynew file mode 100644index 00000000..314d70e2--- /dev/null+++ b/runner/tests/test_tracecontext.py@@ -0,0 +1,81 @@+"""runner/tracecontext.py: the W3C trace-context rules both services apply to a caller's+`traceparent` and `tracestate` (#473). The gateway loads this module by path and the runner imports+it, so one set of rules decides what is kept, what is dropped (never refused), and what child the+relay sends to a provider."""+import pathlib+import sys++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+import tracecontext # noqa: E402++TRACE_ID = "4bf92f3577b34da6a3ce929d0e0e4736"+PARENT = f"00-{TRACE_ID}-00f067aa0ba902b7-01"+STATE = "congo=t61rcWkgMzE,rojo=00f067aa0ba902b7"+++def test_valid_context_is_kept_and_anything_else_is_dropped():+ assert tracecontext.parse(PARENT, STATE) == {"traceparent": PARENT, "tracestate": STATE}+ assert tracecontext.parse(PARENT) == {"traceparent": PARENT}+ assert tracecontext.parse(PARENT, "not a state") == {"traceparent": PARENT}+ for bad in ("", None, "garbage", f"ff-{TRACE_ID}-00f067aa0ba902b7-01",+ f"00-{'0' * 32}-00f067aa0ba902b7-01", f"00-{TRACE_ID}-{'0' * 16}-01",+ PARENT + "-extra", PARENT + "\r\nx-injected: 1"):+ assert tracecontext.parse(bad, STATE) == {}, bad+++def test_upper_case_hex_is_not_a_trace_context():+ """The spec's ids are lower-case hex (HEXDIGLC); an upper-case value is dropped, not rewritten."""+ assert tracecontext.parse(PARENT.upper()) == {}+ assert tracecontext.parse(f"00-{TRACE_ID.upper()}-00f067aa0ba902b7-01") == {}+++def test_a_future_version_keeps_its_four_fields_and_never_its_tail():+ """The spec parses the fields it knows of a newer version and ignores the rest: the trace is+ kept, and the unread tail (a long value, a control character) travels nowhere."""+ head = f"01-{TRACE_ID}-00f067aa0ba902b7-01"+ assert tracecontext.parse(head + "-what-the-future-holds") == {"traceparent": head}+ assert tracecontext.parse(head + "-" + "x" * 5000) == {"traceparent": head}+ assert tracecontext.parse(head + "-a\rb") == {"traceparent": head}+++def test_a_repeated_tracestate_key_drops_the_tracestate_not_the_trace():+ """'Only one entry per key may exist': a tracestate that repeats one is dropped whole."""+ assert tracecontext.parse(PARENT, "congo=1,congo=2") == {"traceparent": PARENT}+ assert tracecontext.parse(PARENT, "a@vendor=1,a@vendor=2") == {"traceparent": PARENT}+++def test_empty_tracestate_members_are_skipped():+ """The spec allows empty list-members; they are skipped, and the members around them kept."""+ assert tracecontext.parse(PARENT, "a=1,,b=2") == {"traceparent": PARENT, "tracestate": "a=1,b=2"}+ assert tracecontext.parse(PARENT, " , a=1 ,") == {"traceparent": PARENT, "tracestate": "a=1"}+ assert tracecontext.parse(PARENT, " , ") == {"traceparent": PARENT}+++def test_tracestate_limits_drop_it_never_refuse():+ """At most 32 members and 512 characters: past either, the tracestate is dropped."""+ thirty_two = ",".join(f"k{i}=1" for i in range(32))+ assert tracecontext.parse(PARENT, thirty_two) == {"traceparent": PARENT, "tracestate": thirty_two}+ assert tracecontext.parse(PARENT, thirty_two + ",k32=1") == {"traceparent": PARENT}+ assert tracecontext.parse(PARENT, "k=" + "v" * 600) == {"traceparent": PARENT}+++def test_a_child_keeps_the_trace_id_and_the_sampled_flag_with_a_new_span():+ child = tracecontext.child(PARENT)+ version, trace_id, span, flags = child.split("-")+ assert (version, trace_id, flags) == ("00", TRACE_ID, "01")+ assert span != "00f067aa0ba902b7" and len(span) == 16 and tracecontext.parse(child)+ assert tracecontext.child(f"00-{TRACE_ID}-00f067aa0ba902b7-00").endswith("-00")+ assert tracecontext.child(f"00-{TRACE_ID}-00f067aa0ba902b7-ff").endswith("-01") # unknown flags dropped+ assert tracecontext.child("garbage") == ""+++def test_a_child_of_a_future_version_is_version_00_with_the_sampled_bit_only():+ child = tracecontext.child(f"03-{TRACE_ID}-00f067aa0ba902b7-03-more")+ version, trace_id, _span, flags = child.split("-")+ assert (version, trace_id, flags) == ("00", TRACE_ID, "01")+++def test_trace_id_reads_only_a_valid_traceparent():+ assert tracecontext.trace_id(PARENT) == TRACE_ID+ assert tracecontext.trace_id(PARENT.upper()) == ""+ assert tracecontext.trace_id("") == ""diff --git a/runner/tracecontext.py b/runner/tracecontext.pynew file mode 100644index 00000000..dc16f3b6--- /dev/null+++ b/runner/tracecontext.py@@ -0,0 +1,106 @@+"""W3C trace context (https://www.w3.org/TR/trace-context/) for a turn: the caller's `traceparent`+and `tracestate`, checked, and the child `traceparent` the relay sends on a model call.++A caller with distributed tracing sends these on POST /v1/responses. The gateway keeps the pair on+the turn and hands it to the runner's /turn; the runner puts it in the CLI's environment+(TRACEPARENT, TRACESTATE, the names OpenTelemetry-aware tools read) and on each model call its relay+forwards, as a child: the same trace id, a new span id, the sampled flag kept. Only these two+headers ever leave: `baggage` and any other context can carry the caller's data to a model+provider, so nothing else is read.++A value that is not W3C syntax is dropped, never refused: tracing is the caller's, and a turn does+not fail over it. No header in means nothing out.++Pure functions, no imports from the runner: the runner imports this module (runner/server.py), and+the gateway loads this file by path (gateway/app.py), as it does runner/reasoning.py, so the two+services apply one set of rules.+"""+from __future__ import annotations++import re+import secrets++# version-traceid-parentid-flags, LOWERCASE hex only (the spec's HEXDIGLC: an upper-case value is+# not a trace context). A version above 00 may carry more fields after a dash; only the four known+# ones are read and kept, and only version 00 is ever written.+_TRACEPARENT = re.compile(r"([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?", re.S)+# One list-member: a key (simple, or tenant@system) and a value of printable ASCII without ',' or+# '=', whose last character is not a space and which is not empty.+_TRACESTATE_MEMBER = re.compile(+ r"([a-z][a-z0-9_\-*/]{0,255}|[a-z0-9][a-z0-9_\-*/]{0,240}@[a-z][a-z0-9_\-*/]{0,13})"+ r"=[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]")+# The spec's limits: at most 32 list-members, and a header a vendor may keep to 512 characters.+_TRACESTATE_MAX_MEMBERS = 32+_TRACESTATE_MAX = 512+++def _traceparent(value) -> str:+ """The traceparent when it is valid W3C syntax, as its four fields, else "".++ A version above 00 is read for its first four fields and its tail is not kept: the spec parses+ the fields it knows and ignores the rest, and an unread tail (a long value, a stray control+ character) must not travel into the CLI's environment or a provider's request. Version ff, 00+ with a tail, and an all-zero trace id or parent id are invalid."""+ v = str(value or "").strip()+ m = _TRACEPARENT.fullmatch(v)+ if not m:+ return ""+ version, trace_id, parent_id, flags, rest = m.groups()+ if version == "ff" or (version == "00" and rest):+ return ""+ if trace_id == "0" * 32 or parent_id == "0" * 16:+ return ""+ return f"{version}-{trace_id}-{parent_id}-{flags}"+++def _tracestate(value) -> str:+ """The tracestate when it is valid W3C syntax, else "".++ Empty list-members are allowed and skipped. More than 32 members, more than 512 characters, a+ member that does not parse, or a key that repeats ("only one entry per key") drop the whole+ tracestate, never the traceparent beside it."""+ v = str(value or "").strip()+ if not v or len(v) > _TRACESTATE_MAX:+ return ""+ members = [p.strip() for p in v.split(",")]+ members = [p for p in members if p]+ if not members or len(members) > _TRACESTATE_MAX_MEMBERS:+ return ""+ keys = []+ for p in members:+ m = _TRACESTATE_MEMBER.fullmatch(p)+ if not m:+ return ""+ keys.append(m.group(1))+ if len(keys) != len(set(keys)):+ return ""+ return ",".join(members)+++def parse(traceparent, tracestate=None) -> dict:+ """{"traceparent": ..., "tracestate": ...} with only what is valid; {} when the traceparent is+ missing or invalid, since a tracestate means nothing without one."""+ tp = _traceparent(traceparent)+ if not tp:+ return {}+ ts = _tracestate(tracestate)+ return {"traceparent": tp, **({"tracestate": ts} if ts else {})}+++def child(traceparent: str) -> str:+ """A child of `traceparent`: version 00, the same trace id, a new span id, and of the flags only+ the sampled bit (the only one version 00 defines). "" when the parent is not valid."""+ tp = _traceparent(traceparent)+ if not tp:+ return ""+ _version, trace_id, _parent, flags = tp.split("-")+ span = secrets.token_hex(8)+ while span == "0" * 16:+ span = secrets.token_hex(8)+ return f"00-{trace_id}-{span}-{int(flags, 16) & 0x01:02x}"+++def trace_id(traceparent: str) -> str:+ """The trace id of a valid traceparent, "" otherwise."""+ tp = _traceparent(traceparent)+ return tp.split("-")[1] if tp else ""