Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

docs(tracing): document attached() / atexit_flush / tracing_context (#93)

Chrisa1dd175bda8e
diff --git a/website/docs/guides/tracing/getting-started.md b/website/docs/guides/tracing/getting-started.md
index f78182d..a68387a 100644
--- a/website/docs/guides/tracing/getting-started.md
+++ b/website/docs/guides/tracing/getting-started.md
@@ -19,7 +19,7 @@ rather than mid-run.
## Attach a Tracer
-The minimal end-to-end setup — local JSONL export:
+The minimal end-to-end setup — local JSONL export, idiomatic RAII:
```python
import asyncio
@@ -36,26 +36,47 @@ async def main() -> None:
system_prompt="Be helpful.",
)
- tracer = Tracer(
- service_name="my-bot",
- agent_name="assistant",
- exporters=[JsonlSpanExporter(directory="./cubepi-traces")],
- )
- detach = tracer.attach(agent)
- try:
+ async with (
+ Tracer(
+ service_name="my-bot",
+ agent_name="assistant",
+ exporters=[JsonlSpanExporter(directory="./cubepi-traces")],
+ ) as tracer,
+ tracer.attached(agent),
+ ):
await agent.prompt("Say hello.")
await agent.wait_for_idle()
- finally:
- # Either is enough on its own:
- # await detach() # awaits the scheduled flush
- # await tracer.shutdown() # flushes + closes exporters
- detach()
- await tracer.shutdown()
+ # On exit: auto-detach (closes any cancelled-run spans, awaits the
+ # flush) + tracer shutdown (flushes + closes exporters). No
+ # try/finally needed.
asyncio.run(main())
```
+If you can't restructure into an `async with` (e.g. long-lived web
+handler that hands the agent around), the explicit pattern still
+works and is fully equivalent:
+
+```python
+detach = tracer.attach(agent)
+try:
+ await agent.prompt("…")
+finally:
+ # Either is enough on its own:
+ # await detach() # awaits the scheduled flush
+ # await tracer.shutdown() # flushes + closes exporters
+ detach()
+ await tracer.shutdown()
+```
+
+Even if you forget the cleanup entirely, `Tracer` registers an
+`atexit` hook by default that sync-flushes buffered spans at process
+exit — pass `atexit_flush=False` to opt out, or rely on it as a
+safety net while you're still building. (Doesn't run on `SIGKILL` or
+`os._exit`; for guaranteed delivery there, use the synchronous
+`SimpleSpanProcessor` from OTel.)
+
The run produces one JSONL file per agent run:
```text
@@ -163,6 +184,42 @@ metric state so concurrent agents don't share span or histogram state,
and MCP CLIENT spans route through the right Tracer based on which
agent's `execute_tool` span is the parent.
+With the RAII helper, stacking them is one `async with`:
+
+```python
+async with (
+ Tracer(...) as tracer,
+ tracer.attached(agent_a),
+ tracer.attached(agent_b),
+):
+ await asyncio.gather(agent_a.prompt("…"), agent_b.prompt("…"))
+```
+
+## Tagging individual runs
+
+`cubepi.tracing.tracing_context` scopes per-run tags / metadata onto
+the `invoke_agent` span — perfect for `user_id`, `session_id`,
+A/B-test arm, anything you'd want to filter by in the backend later:
+
+```python
+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.")
+```
+
+Attributes on the span:
+
+- `cubepi.tags = ("beta-arm",)`
+- `cubepi.metadata.user_id = "u-42"`
+
+The `cubepi.metadata.*` prefix keeps user keys from clobbering
+recorder-owned schema (e.g. `cubepi.run_id`). Tags and metadata
+contextvars are per-asyncio-task, so concurrent agents see
+independent values, and nested `tracing_context` blocks merge
+(tags concatenate, metadata keys union with inner winning).
+
## Next
- [OTLP & Backends](./otlp) — Jaeger, Tempo, Honeycomb, Datadog, …
diff --git a/website/docs/guides/tracing/metrics.md b/website/docs/guides/tracing/metrics.md
index 60e0b44..948e811 100644
--- a/website/docs/guides/tracing/metrics.md
+++ b/website/docs/guides/tracing/metrics.md
@@ -29,6 +29,8 @@ landed) are still groupable by what was asked for:
## Attaching a Meter
+The idiomatic RAII form — `async with` everything, no manual cleanup:
+
```python
from opentelemetry.exporter.otlp.proto.http.metric_exporter import (
OTLPMetricExporter,
@@ -36,27 +38,45 @@ from opentelemetry.exporter.otlp.proto.http.metric_exporter import (
from cubepi.tracing import Tracer, Meter
from cubepi.tracing.exporters import JsonlSpanExporter
-tracer = Tracer(
- service_name="my-bot",
- agent_name="assistant",
- exporters=[JsonlSpanExporter(directory="./cubepi-traces")],
-)
-meter = Meter(
- resource=tracer.resource, # share Resource so service.* matches spans
- exporters=[
- OTLPMetricExporter(endpoint="http://otel-collector:4318/v1/metrics"),
- ],
-)
+async with (
+ Tracer(
+ service_name="my-bot",
+ agent_name="assistant",
+ exporters=[JsonlSpanExporter(directory="./cubepi-traces")],
+ ) as tracer,
+ Meter(
+ resource=tracer.resource, # share Resource so service.* matches spans
+ exporters=[
+ OTLPMetricExporter(endpoint="http://otel-collector:4318/v1/metrics"),
+ ],
+ ) as meter,
+ tracer.attached(agent),
+ meter.attached(agent),
+):
+ await agent.prompt("...")
+# Exit order auto: detach both (closes any cancelled-run spans, flushes
+# the trace pipeline) → shutdown both (flush + close exporters).
+```
+`Meter.attach()` is independent from `Tracer.attach()`. You can run
+either on its own; the recommended setup is both, sharing one
+`Resource` so the backend treats them as the same service.
+
+If you need the explicit, non-RAII form (e.g. attaching agents
+dynamically over the lifetime of a long-running server):
+
+```python
tracer_detach = tracer.attach(agent)
meter_detach = meter.attach(agent)
+try:
+ ...
+finally:
+ tracer_detach() # closes any cancelled-run spans
+ meter_detach() # unsubscribes the meter's listeners
+ await tracer.shutdown()
+ await meter.shutdown()
```
-`Meter.attach()` is independent from `Tracer.attach()`. Each returns its
-own detach callable — capture both. You can run either on its own; the
-recommended setup is both, sharing one Resource so the backend treats
-them as the same service.
-
## Bucket boundaries
The duration histograms ship with the OTel GenAI semconv's recommended
@@ -89,18 +109,22 @@ filterable by `gen_ai.agent.name` (set at the `Resource` level when
## Shutting down
+The RAII form (`async with … as tracer, … as meter, tracer.attached(agent),
+meter.attached(agent):` from above) handles the shutdown ordering for you:
+detach inner first → outer `Tracer/Meter` `__aexit__` runs `shutdown()`.
+
+For the manual pattern, order matters — `tracer_detach()` must run before
+`tracer.shutdown()` so any spans an in-flight cancellation left open get
+closed and exported in the same flush:
+
```python
finally:
- tracer_detach() # closes any spans a cancelled run left open
- meter_detach() # unsubscribes the meter's listeners
+ tracer_detach()
+ meter_detach()
await tracer.shutdown()
await meter.shutdown()
```
-Order matters: run `tracer_detach()` before `tracer.shutdown()` so any
-spans an in-flight cancellation left open get closed and exported in
-the same flush.
-
`Meter.shutdown()` awaits a flush of the metric reader, then closes it.
`PeriodicExportingMetricReader` exports on a fixed interval (60 s by
default) — `shutdown` is the only way to guarantee the final window lands
diff --git a/website/docs/guides/tracing/otlp.md b/website/docs/guides/tracing/otlp.md
index efddc64..c93dd75 100644
--- a/website/docs/guides/tracing/otlp.md
+++ b/website/docs/guides/tracing/otlp.md
@@ -137,24 +137,38 @@ tracer = Tracer(
## Flushing
`Tracer` uses `BatchSpanProcessor` under the hood, so spans are exported in
-the background. To make sure buffered spans land before your process exits:
+the background. The recommended pattern — and the one that exercises all
+the cleanup paths automatically — is the `async with` form:
```python
-finally:
- detach() # closes any spans a cancelled run left open
- await tracer.shutdown() # awaits force_flush, then shuts the SDK down
+async with Tracer(...) as tracer, tracer.attached(agent):
+ await agent.prompt("...")
+# On exit:
+# - detach() runs synchronously: closes any spans a cancelled run left
+# open, then schedules the flush as an asyncio.Task and awaits it.
+# - tracer.shutdown() flushes again (idempotent) and closes exporters.
```
-`detach()` runs its synchronous cleanup (unsubscribe + close any spans an
-in-flight cancellation left open) immediately, then schedules a flush as
-an `asyncio.Task` on the running loop and returns it. Two valid patterns:
+If you've stored `detach` from a manual `tracer.attach(agent)` call, it
+returns the scheduled flush `Task`. Two valid manual patterns:
-- **Both** `detach(); await tracer.shutdown()` — the safest belt-and-braces
- approach; `shutdown()` is idempotent.
-- **Awaited detach** `await detach()` — the returned Task awaits
- `force_flush`, so this single call is enough when you're not also
- shutting down the Tracer.
+```python
+# (a) Belt-and-braces — safest, both run.
+finally:
+ detach() # closes cancelled-run spans, schedules flush
+ await tracer.shutdown() # awaits force_flush, then shuts the SDK down
+
+# (b) Awaited detach — single call when you're not also shutting down.
+finally:
+ await detach() # awaits the scheduled flush
+```
Outside an async context (no running loop) `detach()` returns `None` — the
sync part has run, but the flush is the caller's responsibility via
`await tracer.shutdown()`.
+
+If even that gets missed — say a script raises before reaching `finally` —
+`Tracer(atexit_flush=True)` (the default) registers a process-exit handler
+that sync-flushes buffered spans through `BatchSpanProcessor`. Doesn't run
+on `SIGKILL` / `os._exit`; for guaranteed delivery there, use
+`SimpleSpanProcessor` (sync export per span).
diff --git a/website/docs/guides/tracing/overview.md b/website/docs/guides/tracing/overview.md
index a551244..09e8a97 100644
--- a/website/docs/guides/tracing/overview.md
+++ b/website/docs/guides/tracing/overview.md
@@ -40,6 +40,17 @@ Each layer carries standard `gen_ai.*` attributes — `gen_ai.operation.name`,
- **W3C trace context propagation** — outgoing MCP calls inject the active
`traceparent` as an HTTP header so an instrumented MCP server can continue
the trace.
+- **`tracer.attached(agent)` / `meter.attached(agent)`** — async context
+ managers that RAII-wrap attach/detach, so cleanup is one `async with`
+ block instead of an explicit `try/finally`.
+- **`atexit` flush hook** — `Tracer(atexit_flush=True)` (default) registers
+ a process-exit handler that sync-flushes any buffered spans, so callers
+ who forget `await tracer.shutdown()` still get their spans exported on
+ normal exit / Ctrl-C / unhandled exception.
+- **`tracing_context()`** — set per-run tags and metadata
+ (`cubepi.tags = ("beta-arm",)`, `cubepi.metadata.user_id = "u-42"`)
+ via a contextvar-scoped block. Concurrent agents each see their own
+ values.
## What it costs
@@ -62,6 +73,9 @@ Each layer carries standard `gen_ai.*` attributes — `gen_ai.operation.name`,
| Latency + token histograms next to the spans | `Meter` alongside `Tracer` |
| Record prompts / model outputs for evaluation | `Tracer(record_content=True)` |
| Redact PII before it leaves the process | `Tracer(redact=…)` |
+| Tag runs with `user_id` / `session_id` / A-B arm | `tracing_context(tags=…, metadata=…)` |
+| One-liner cleanup, no try/finally | `async with tracer.attached(agent): …` |
+| Forget to call `shutdown()` and not lose spans | `Tracer(atexit_flush=True)` (default) |
| Continue a trace from an upstream service | `Tracer(resource=…)` + W3C `traceparent` (auto for MCP, manual for HTTP) |
## Where to go next