CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
feat(tracing): tracing_context() for per-run tags + metadata (#92)
Chrisb9e8714cfb20
diff --git a/cubepi/tracing/__init__.py b/cubepi/tracing/__init__.pyindex 042ed49..60a9c8b 100644--- a/cubepi/tracing/__init__.py+++ b/cubepi/tracing/__init__.py@@ -17,6 +17,7 @@ except ImportError as exc: # pragma: no cover — exercised only without the ex"Install it via: pip install cubepi[tracing]") from exc+from cubepi.tracing.context import tracing_contextfrom cubepi.tracing.exporters import JsonlSpanExporterfrom cubepi.tracing.meter import Meterfrom cubepi.tracing.schema import SCHEMA_URL@@ -27,4 +28,5 @@ __all__ = ["Meter","SCHEMA_URL","Tracer",+ "tracing_context",]diff --git a/cubepi/tracing/context.py b/cubepi/tracing/context.pynew file mode 100644index 0000000..c727646--- /dev/null+++ b/cubepi/tracing/context.py@@ -0,0 +1,106 @@+"""Per-run tagging / metadata context for cubepi.tracing.++Sets a contextvar-scoped ``tags`` / ``metadata`` payload that the+:class:`~cubepi.tracing.recorder.Recorder` reads on ``AgentStartEvent``+and stamps onto the ``invoke_agent`` span. Inspired by LangSmith's+``langsmith.run_helpers.tracing_context`` (same contextvar mechanism).++Namespacing:++- Tags use a single attribute ``cubepi.tags`` (tuple of strings).+- User metadata is namespaced under ``cubepi.metadata.*`` so that+ recorder-owned schema keys (``cubepi.run_id``,+ ``cubepi.turn.index``, …) can never be overridden by+ caller-supplied values.++Usage::++ from cubepi.tracing import tracing_context++ async with tracer.attached(agent):+ with tracing_context(tags=["beta-arm"], metadata={"user_id": "u-42"}):+ await agent.prompt("hello")+ # the next run does NOT carry those tags+ await agent.prompt("goodbye")++Resulting ``invoke_agent`` span attributes:++- ``cubepi.tags`` = ``("beta-arm",)``+- ``cubepi.metadata.user_id`` = ``"u-42"``++Multiple nested ``tracing_context`` blocks merge: inner tags are+appended, inner metadata keys override outer ones (last-write-wins).+"""++from __future__ import annotations++import contextlib+import contextvars+from typing import Any, Iterator+++_run_metadata: contextvars.ContextVar[dict[str, Any]] = contextvars.ContextVar(+ "cubepi.tracing.run_metadata", default={}+)++_run_tags: contextvars.ContextVar[tuple[str, ...]] = contextvars.ContextVar(+ "cubepi.tracing.run_tags", default=()+)+++def tracing_context(+ *,+ tags: list[str] | tuple[str, ...] | None = None,+ metadata: dict[str, Any] | None = None,+) -> Iterator[None]:+ """Scope tags / metadata onto agent runs started inside this block.++ The recorder reads these contextvars on ``AgentStartEvent`` and+ stamps them on the ``invoke_agent`` span as:++ - ``cubepi.tags`` — tuple of strings (OTel attribute type)+ - one attribute per metadata key, namespaced under+ ``cubepi.metadata.*`` (e.g. ``metadata={"user_id": "u-42"}`` →+ ``cubepi.metadata.user_id = "u-42"``). The dedicated+ sub-namespace keeps recorder-owned schema keys+ (``cubepi.run_id``, ``cubepi.turn.index``, …) safe from+ caller-supplied collisions.++ The contextvar nature means this works for concurrent agents:+ each asyncio task tree gets its own value. Nested blocks merge+ additively (tags concatenate; metadata is union with inner+ keys winning).++ Args:+ tags: Tags to apply to runs started in this scope. Stored as+ a tuple on the span so it round-trips through OTel's+ attribute serializer.+ metadata: Per-run key/value pairs. Values must be types that+ OTel attributes accept (str, bool, int, float, or a+ tuple/list of those); other shapes will be silently+ dropped by the recorder.+ """+ new_meta = {**_run_metadata.get(), **(metadata or {})}+ new_tags = tuple(_run_tags.get()) + tuple(tags or ())+ meta_token = _run_metadata.set(new_meta)+ tag_token = _run_tags.set(new_tags)+ try:+ yield+ finally:+ _run_metadata.reset(meta_token)+ _run_tags.reset(tag_token)+++def _current_tags() -> tuple[str, ...]:+ """Internal: return the active tag tuple for the current task.++ Called by :class:`~cubepi.tracing.recorder.Recorder` on+ ``_on_agent_start``; not part of the public API.+ """+ return _run_tags.get()+++def _current_metadata() -> dict[str, Any]:+ """Internal: return the active metadata dict for the current task."""+ return _run_metadata.get()diff --git a/cubepi/tracing/recorder.py b/cubepi/tracing/recorder.pyindex 50bbe0b..364363f 100644--- a/cubepi/tracing/recorder.py+++ b/cubepi/tracing/recorder.py@@ -431,6 +431,37 @@ class Recorder:# that vary per-run set their own value via _ensure_agent_name.self._run = _RunState(run_id=run_id, agent_span=span)+ # Stamp any tags / metadata set via ``cubepi.tracing.tracing_context``+ # for this run. Per-task contextvar scoping means concurrent+ # agents each see their own values; nested ``tracing_context``+ # blocks merge before reaching here.+ #+ # User metadata is namespaced under ``cubepi.metadata.*`` so+ # that keys like ``run_id`` / ``turn_index`` / ``agent.tools``+ # — which the recorder owns under ``cubepi.*`` — can never be+ # overwritten by caller-supplied values. Reserved cubepi+ # schema keys (especially ``cubepi.run_id`` which the JSONL+ # exporter shards on) must stay recorder-controlled (codex P2+ # on PR #92).+ try:+ from cubepi.tracing.context import _current_metadata, _current_tags++ tags = _current_tags()+ if tags:+ span.set_attribute("cubepi.tags", tags)+ metadata = _current_metadata()+ for key, value in metadata.items():+ # OTel attribute values are limited to scalar primitives+ # and homogeneous sequences. Anything else is silently+ # dropped here — better to lose one tag than corrupt the+ # whole span.+ try:+ span.set_attribute(f"cubepi.metadata.{key}", value)+ except (TypeError, ValueError):+ pass+ except ImportError: # pragma: no cover — context module always available+ pass+# Seed the transcript from the agent's existing conversation# history. The cubepi agent loop only emits MessageStartEvent# for newly-introduced messages (new prompts in ``run_agent_loop``,diff --git a/tests/tracing/test_recorder.py b/tests/tracing/test_recorder.pyindex 48e1e8e..5a4ff6b 100644--- a/tests/tracing/test_recorder.py+++ b/tests/tracing/test_recorder.py@@ -915,6 +915,187 @@ class TestAttachedContextManager:assert exporter.spans+class TestTracingContext:+ """``cubepi.tracing.tracing_context`` sets per-task tags ++ metadata that the recorder stamps onto the invoke_agent span."""++ async def test_tags_land_on_invoke_agent_span(self):+ from cubepi.tracing import tracing_context++ agent, provider, exporter, tracer = await _build()+ provider.append_responses([faux_assistant_message("ok")])++ with tracing_context(tags=["beta-arm", "test-suite"]):+ await agent.prompt("hi")+ await agent.wait_for_idle()+ await tracer.shutdown()++ root = next(s for s in exporter.spans if s.name == "invoke_agent")+ attrs = _attrs(root)+ assert attrs.get("cubepi.tags") == ("beta-arm", "test-suite")++ async def test_metadata_keys_land_with_prefix(self):+ from cubepi.tracing import tracing_context++ agent, provider, exporter, tracer = await _build()+ provider.append_responses([faux_assistant_message("ok")])++ with tracing_context(metadata={"user_id": "u-42", "ab_arm": "control"}):+ await agent.prompt("hi")+ await agent.wait_for_idle()+ await tracer.shutdown()++ root = next(s for s in exporter.spans if s.name == "invoke_agent")+ attrs = _attrs(root)+ assert attrs.get("cubepi.metadata.user_id") == "u-42"+ assert attrs.get("cubepi.metadata.ab_arm") == "control"++ async def test_no_context_means_no_tag_attr(self):+ agent, provider, exporter, tracer = await _build()+ provider.append_responses([faux_assistant_message("ok")])+ await agent.prompt("hi")+ await agent.wait_for_idle()+ await tracer.shutdown()++ root = next(s for s in exporter.spans if s.name == "invoke_agent")+ attrs = _attrs(root)+ assert "cubepi.tags" not in attrs++ async def test_context_does_not_leak_across_runs(self):+ """The contextvar resets on block exit — the next run started+ outside the block must NOT carry the previous tags."""+ from cubepi.tracing import tracing_context++ agent, provider, exporter, tracer = await _build()+ provider.append_responses(+ [+ faux_assistant_message("first"),+ faux_assistant_message("second"),+ ]+ )++ with tracing_context(tags=["scoped"]):+ await agent.prompt("first")+ await agent.wait_for_idle()+ await agent.prompt("second")+ await agent.wait_for_idle()+ await tracer.shutdown()++ roots = sorted(+ [s for s in exporter.spans if s.name == "invoke_agent"],+ key=lambda s: s.start_time or 0,+ )+ assert len(roots) == 2+ assert _attrs(roots[0]).get("cubepi.tags") == ("scoped",)+ assert "cubepi.tags" not in _attrs(roots[1])++ async def test_nested_contexts_merge_additively(self):+ from cubepi.tracing import tracing_context++ agent, provider, exporter, tracer = await _build()+ provider.append_responses([faux_assistant_message("ok")])++ with tracing_context(tags=["outer"], metadata={"k": "outer-val"}):+ with tracing_context(+ tags=["inner"], metadata={"k": "inner-val", "x": "new"}+ ):+ await agent.prompt("hi")+ await agent.wait_for_idle()+ await tracer.shutdown()++ root = next(s for s in exporter.spans if s.name == "invoke_agent")+ attrs = _attrs(root)+ assert attrs.get("cubepi.tags") == ("outer", "inner")+ assert attrs.get("cubepi.metadata.k") == "inner-val"+ assert attrs.get("cubepi.metadata.x") == "new"++ async def test_unsupported_metadata_value_is_dropped(self):+ """OTel attributes can't hold dicts or arbitrary objects."""+ from cubepi.tracing import tracing_context++ agent, provider, exporter, tracer = await _build()+ provider.append_responses([faux_assistant_message("ok")])++ with tracing_context(+ metadata={+ "good_str": "yes",+ "good_int": 42,+ "bad_dict": {"nested": 1},+ }+ ):+ await agent.prompt("hi")+ await agent.wait_for_idle()+ await tracer.shutdown()++ root = next(s for s in exporter.spans if s.name == "invoke_agent")+ attrs = _attrs(root)+ assert attrs.get("cubepi.metadata.good_str") == "yes"+ assert attrs.get("cubepi.metadata.good_int") == 42+ assert "cubepi.metadata.bad_dict" not in attrs++ async def test_metadata_set_attribute_typeerror_is_swallowed(self, monkeypatch):+ """OTel SDK silently drops most invalid attribute values, but+ a non-conforming type could in principle raise TypeError /+ ValueError from ``set_attribute``. The recorder must swallow+ per-key so one bad metadata entry can't crash the whole span+ (covers the defensive ``except (TypeError, ValueError)``+ branch)."""+ from cubepi.tracing import tracing_context+ from opentelemetry.sdk.trace import Span as _SdkSpan++ agent, provider, exporter, tracer = await _build()+ provider.append_responses([faux_assistant_message("ok")])++ # Patch set_attribute to raise on a specific cubepi.metadata.*+ # key while letting every other attribute go through. The+ # recorder writes many cubepi.* / gen_ai.* attrs at agent+ # start, so we need to be surgical.+ original = _SdkSpan.set_attribute++ def _selective_set_attribute(self, key, value):+ if key == "cubepi.metadata.boom":+ raise TypeError("simulated OTel reject")+ return original(self, key, value)++ monkeypatch.setattr(_SdkSpan, "set_attribute", _selective_set_attribute)++ with tracing_context(metadata={"boom": object(), "good": "yes"}):+ await agent.prompt("hi")+ await agent.wait_for_idle()+ await tracer.shutdown()++ root = next(s for s in exporter.spans if s.name == "invoke_agent")+ attrs = _attrs(root)+ # bad key swallowed; good key landed.+ assert "cubepi.metadata.boom" not in attrs+ assert attrs.get("cubepi.metadata.good") == "yes"++ async def test_metadata_cannot_clobber_reserved_cubepi_attrs(self):+ """User-supplied metadata keys must not be able to overwrite+ recorder-owned schema attributes like ``cubepi.run_id`` —+ the JSONL exporter shards spans by that key, so an+ invoke_agent span with a clobbered ``run_id`` ends up in a+ different file than its turn/chat/tool spans (codex P2 on+ PR #92). The fix is the ``cubepi.metadata.*`` sub-namespace."""+ from cubepi.tracing import tracing_context++ agent, provider, exporter, tracer = await _build()+ provider.append_responses([faux_assistant_message("ok")])++ with tracing_context(metadata={"run_id": "hijacked", "turn.index": "x"}):+ await agent.prompt("hi")+ await agent.wait_for_idle()+ await tracer.shutdown()++ root = next(s for s in exporter.spans if s.name == "invoke_agent")+ attrs = _attrs(root)+ # The genuine recorder-owned value is unchanged…+ assert attrs.get("cubepi.run_id") and attrs["cubepi.run_id"] != "hijacked"+ # …and the user-supplied values land under the safe namespace.+ assert attrs.get("cubepi.metadata.run_id") == "hijacked"+ assert attrs.get("cubepi.metadata.turn.index") == "x"++class TestLifecycle:async def test_shutdown_is_idempotent(self):agent, provider, exporter, tracer = await _build()