OpenTelemetry: datasette.client requests start a new trace instead of nesting under the caller's span
Reproduce
Save this as repro.py and run uv run repro.py:
# /// script
# dependencies = ["datasette==1.0a41", "opentelemetry-sdk"]
# ///
import asyncio
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from datasette import hookimpl
from datasette.app import Datasette
from datasette.plugins import pm
from datasette.utils.asgi import Response
exporter = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
trace.set_tracer_provider(provider)
class OuterRoute:
@hookimpl
def register_routes(self):
async def outer(datasette):
await datasette.client.get("/-/versions.json") # internal request
return Response.text("ok")
return [(r"^/outer$", outer)]
pm.register(OuterRoute(), name="outer-route")
async def main():
ds = Datasette(memory=True)
await ds.client.get("/outer")
outer, inner = sorted(
(s for s in exporter.get_finished_spans() if s.kind == trace.SpanKind.SERVER),
key=lambda s: s.name != "GET ^/outer$",
)
print("outer:", outer.name, "trace", hex(outer.context.trace_id))
print("inner:", inner.name, "trace", hex(inner.context.trace_id))
print("inner parent:", inner.parent)
print("nested:", inner.parent is not None and inner.parent.span_id == outer.context.span_id)
asyncio.run(main())Output on 1.0a41 (and on main at 86bdc751):
outer: GET ^/outer$ trace 0x470aedfa9524d328fc06597d083a53a5
inner: GET /-/versions(\.(?P<format>json))?$ trace 0xa0d29f581c8904b4c4b3436fb8cf338
inner parent: None
nested: FalseThe internal request lands in a separate trace with no parent.
Expected
The docs say internal requests nest:
docs/plugin_telemetry.rst:270: "datasette.clientrequests made from inside a request produce a nestedSERVERspan."docs/internals.rst:2598and thedatasette.internal_clientregistry description (telemetry_registry.py:145-147) say the same thing.
The inner SERVER span should be a child of the span that was current when datasette.client was called, whether that is the outer request span or a plugin's own span. It should be in the same trace.
Cause
datasette/telemetry.py:252, in TelemetryMiddleware.__call__:
context = extract(headers, getter=_HEADERS_GETTER)
with tracer.start_as_current_span(method, context=context, kind=SpanKind.SERVER):- When
extract()gets nocontext=, it starts from an emptyContext(). With notraceparentheader, which is always the case fordatasette.clientcalls, it returns that empty context. - Passing that context explicitly to
start_as_current_spanmakes the span a new root. - The caller's span is still current in contextvars at this point. The
_in_datasette_clientflag read a few lines later proves the call runs in the caller's context. The span just doesn't use it.
test_internal_client_requests_are_marked (tests/test_http_span.py:716) asserts the datasette.internal_client attribute but never the parent, so this wasn't caught.
Suggested fix
Extract into the current context. An inbound traceparent header still takes priority, so network requests are unaffected:
from opentelemetry import context as otel_context
context = extract(headers, getter=_HEADERS_GETTER, context=otel_context.get_current())Monkeypatching exactly this into the repro above gives:
outer: GET ^/outer$ trace 0x1c74fda5ccb192f0876bc704c6c58e88
inner: GET /-/versions(\.(?P<format>json))?$ trace 0x1c74fda5ccb192f0876bc704c6c58e88
inner parent: SpanContext(trace_id=0x1c74fda5ccb192f0876bc704c6c58e88, span_id=0xb2817d2468fa9ca4, ...)
nested: TrueOption: apply this only when _in_datasette_client.get() is true. That keeps network requests exactly as they are today, even when Datasette is mounted under another ASGI tracer that already has a span current.
Tests to add in tests/test_http_span.py:
- An internal request made from inside a route handler: the inner SERVER span's parent is the outer SERVER span, and both share a trace id.
- An internal request made under a plain
tracer.start_as_current_span("plugin.work"): the SERVER span's parent isplugin.work. - An internal request that carries an explicit
traceparentheader: that header still wins.
Why it matters
Plugins that do work through datasette.client end up with orphaned traces. For example, datasette-enrichments fetches each batch of rows with datasette.client.get(table.json?...) inside its own batch span. The fetch, and every db.query span under it, shows up as an unrelated root trace.
Current workaround in plugins: inject the context by hand.
from opentelemetry.propagate import inject
headers = {}
inject(headers)
await datasette.client.get(path, headers=headers)That depends on the global propagator, so it stops working with OTEL_PROPAGATORS=none.
Source: simonw/datasette