将追踪数据发送到你可以自行运行的后端
阅读约 66分钟,7节中含5个示例。
实验室
通过动手实践学习本章
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。约 30 秒后打开。
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。Labs 为你运行:每月 40小时。
在你自己的机器上,免费: 下载本书的笔记本,附其代码和数据,来源为 GitHub。
在本书所用版本上运行你的代码
读完本章,你将能够把两个进程的 span 发送到同一台机器上运行的同一个接收器,检查它存储的行是否与导出器发送的行一致,用 SQL 查询这些行,并说明每个具名后端接受什么,以及它的文档页面没有说明什么。第 4 章结束时,发给 Ambrewick 的一条消息被拆在两个地方。助手的 span 保存在它的内存中,而联系人服务器把自己的 span 写入一个文件,助手只有在服务器退出之后才会读取该文件。这两个地方都无法回答关于整条消息的问题,而两个团队都需要一个可以查询的统一位置,并且明年还能自行更换。
本章的每一个计数都由一次已记录运行中的示例打印出来。其余少数数字来自探测或所引用的页面,正文会说明出处。因此,本章为两个进程构建一个接收器,把它的行与导出器的行相互核对,并在它旁边把 MLflow 部署到磁盘上。
这部分尚未翻译,因此以英文显示。
The exporter sends each span over OTLP
Chapter 1 said that an exporter sends each ended span "to memory, a file or an OTLP endpoint", and left the endpoint for this chapter. OTLP is OpenTelemetry's protocol for sending telemetry to a receiver. A backend stores spans and answers queries over them. A collector is a separate process that receives, processes and exports telemetry, and it is taken up in Changing the backend. The protocol itself is written down in the OTLP specification, which the docs site gives at version 1.11.1, and we cite it for the path, the content types and the status codes.
For traces, the request goes to the path /v1/traces, and its body is either Protocol Buffers, sent as application/x-protobuf, or JSON, sent as application/json. A successful export gets HTTP 200. The specification says a client should retry a request that gets 429, 502, 503 or 504, and must not retry any other 4xx or 5xx code. The Python exporter, OTLPSpanExporter in opentelemetry-exporter-otlp-proto-http at 1.45.2, follows the same four codes in its source, and it also retries connection failures. It makes up to six attempts with backoff, and a Retry-After header replaces the backoff. The whole export, retries included, stops at the exporter's timeout. That timeout is 10 seconds by default (DEFAULT_TIMEOUT), and at the default a closed port gets four attempts, not six; six needs a longer timeout. When the last attempt fails, the exporter returns the batch as failed, and the batch is dropped and logged, not kept for later.
Here a dev-day message's three spans go through that exporter to a receiver on loopback, which the next section describes: its agent span, its chat span and its execute_tool find_contact span, whose counts come from the recording. Two things about a synchronous processor, the kind the examples use, are checked along the way.
1"""Export one dev-day message's three spans over OTLP/HTTP to the book's receiver on loopback, and check that a span's2request is in the receiver when its span.end() returns. The stored rows equal the in-memory exporter's rows, so the3protobuf round trip loses nothing the book's rows keep; the request count is printed and the yes lines are asserted."""4from lib.assistant import AGENT, RELEASES5from lib.clock import VirtualClock6from lib.export import spans_to_rows7from lib.genai import SCHEMA_URL8from lib.ids import SequentialIds9from lib.otlp import message_spans, start10from lib.tracing import make_provider11from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter12from opentelemetry.sdk.resources import Resource13from opentelemetry.sdk.trace import TracerProvider14from opentelemetry.sdk.trace.export import SimpleSpanProcessor15from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1617DAY, RELEASE = "2026-12-07", RELEASES["r0"]18receiver = start() # the book's receiver on loopback; the port is never printed19memory = InMemorySpanExporter() # the same spans, kept in memory, to compare with what arrives20clock = VirtualClock(DAY)21provider = make_provider(AGENT, RELEASE.service_version, "otlp-export-loopback", clock, SequentialIds(), memory, SCHEMA_URL)22# SimpleSpanProcessor calls the exporter when each span ends, so the request is sent on the ending thread (O-7)23provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint=receiver.endpoint)))24root, chat, tool = message_spans(provider.get_tracer("ambrewick.assistant"), clock)2526assert receiver.address == "127.0.0.1" # bound to loopback only, never to a network address27assert len(receiver.requests()) == 3 # one request per span the processor exported28assert sum(count == 1 for _, count in receiver.requests()) == 3 # each request holds one span29assert receiver.rows() == spans_to_rows(memory) # the stored rows equal the exporter's own rows3031# A span from a provider with only the OTLP exporter: its request must be in the receiver when end() returns.32probe = TracerProvider(resource=Resource.create({"service.name": AGENT, "service.instance.id": "probe"}))33probe.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint=receiver.endpoint)))34before = len(receiver.requests())35# 36001 s is an offset on the virtual clock, past the message's spans, so the probe's times do not overlap them36probe.get_tracer("probe").start_span("probe", start_time=clock.at(36001)).end(end_time=clock.at("36001.1"))37assert len(receiver.requests()) == before + 13839print("bound to loopback: yes (asserted)")40print("requests for the message's three spans:", before)41print("spans per request: one in each, for every request (asserted)")42print("content types of the requests:", ", ".join(sorted({kind for kind, _ in receiver.requests()})))43print("stored rows equal the exporter's rows: yes (asserted)")44print("a request is in the receiver when span.end() returns: yes (asserted)")45receiver.stop()
python otlp-export-loopback.pybound to loopback: yes (asserted)
requests for the message's three spans: 3
spans per request: one in each, for every request (asserted)
content types of the requests: application/x-protobuf
stored rows equal the exporter's rows: yes (asserted)
a request is in the receiver when span.end() returns: yes (asserted)
为什么请求体是 protobuf
+10 项证明来自The exporter sends each span over OTLP,第 5 章再读一遍
建立在 span processor 的基础上,参见第1章,“手工构造 span”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
该示例为其请求打印出“content types of the requests: application/x-protobuf”。为什么请求体是 protobuf,而不是 JSON?
原理何在
The receiver logged 3 requests for the message's three spans, and each request's body was application/x-protobuf. Each of the three spans reached the receiver in a request of its own, and each request was there before its span.end() returned, because SimpleSpanProcessor calls the exporter on the thread that ends the span. Chapter 1 chose that processor so that every printed span has been exported by the time it is printed. The example asserts these lines, so it stops if one of them is false. The rows the receiver stored equal the rows the exporter built in memory, so the protobuf round trip loses nothing the book's rows keep. The compared rows leave out the status description, links, trace state, flags, scope version, schema URL and the telemetry.sdk.* resource values.
The synchronous processor has a cost, and a probe shows it. A probe pointed the exporter at a closed loopback port, at its default 10-second timeout; span.end() returned after about 7 seconds, after four attempts, and no exception reached the application.
Working rule: Give each process the endpoint of its receiver, and send production spans with the batch processor that chapter 1 recommends, so the request is not made on the thread that ends the span. In production we recommend that processor, because its export runs on its own schedule and not on the thread that ends a span. The trade is the one chapter 1 named: spans still in its queue are lost if the process dies.
这部分尚未翻译,因此以英文显示。
The book's receiver holds both processes' spans
The receiver is the book's own: an HTTP server from the standard library that decodes requests with OpenTelemetry's protobuf classes, started on loopback by start() in the book's lib/otlp.py. It decodes a request in either encoding, Protocol Buffers or JSON, and stores each span as a row in the shape the book's export writes to JSON lines. It stores the request before it replies, which is what the last section's assertion relied on. It keeps the rows in memory, for one run. That makes it a test receiver for this book, not a store a team would keep for a year. The next section's backend keeps its rows on disk.
Both processes export to it. The assistant's exporter runs in the assistant's own process. The contacts server gets the endpoint from its environment: when OTEL_EXPORTER_OTLP_TRACES_ENDPOINT or OTEL_EXPORTER_OTLP_ENDPOINT names one, the server exports its spans over OTLP itself. When neither is set, it writes the JSON-lines file that The contacts server is another process describes. The receiver takes a port that the system chooses, and the examples never print it; the contacts server is still a stdio subprocess and only sends to that port.
1"""Replay baseline day 1's messages that route to the messages tools, with the contacts server live, and send both2processes' spans to one receiver: every server span joins a trace the assistant made. The server's clock is its own,3so the example prints counts only, never a span time from it."""4from lib.assistant import AGENT5from lib.case import load_messages, scenario_to_route6from lib.contacts_server import SERVICE_NAME7from lib.dayrun import run_day_traced8from lib.otlp import start910DAY = "2026-12-08"11receiver = start() # the book's receiver on loopback; its port is never printed12ids = {m.message_id for m in load_messages(DAY) if scenario_to_route(m.scenario) == "messages"} # only these can call a contacts tool13traced = run_day_traced(DAY, message_ids=ids, otlp_endpoint=receiver.endpoint) # both processes export here14stored = receiver.rows()15mine = [row for row in stored if row["resource"]["service.name"] == AGENT]16theirs = [row for row in stored if row["resource"]["service.name"] == SERVICE_NAME]17mine_ids = {row["span_id"] for row in mine}18find = {row["trace_id"] for row in mine if row["name"] == "execute_tool find_contact"} # those messages' traces19both = {row["trace_id"] for row in mine} & {row["trace_id"] for row in theirs}2021assert mine == traced.spans # the stored assistant rows equal export.py's rows22assert find <= {row["trace_id"] for row in theirs} # each find_contact message has server spans in its trace23assert find <= {row["trace_id"] for row in mine if row["name"].startswith("invoke_agent")} # and a message root24# every server span whose parent is set names a stored span, from either process: the join crosses no gap25assert all(row["parent_span_id"] in mine_ids | {r["span_id"] for r in theirs} for row in theirs if row["parent_span_id"])2627rooted = {row["trace_id"] for row in mine if row["name"].startswith("invoke_agent")}28print("messages replayed:", len(traced.runs))29print("messages that called find_contact:", len(find))30print("assistant traces with a message root:", len(rooted))31print("assistant traces without one (the startup, with its discovery call):", len({row["trace_id"] for row in mine} - rooted))32print("traces with spans from both processes:", len(both))33print("spans from the assistant, in the find_contact messages:", sum(row["trace_id"] in find for row in mine))34print("spans from the contacts server, in the find_contact messages:", sum(row["trace_id"] in find for row in theirs))35print("spans from the assistant, all messages:", len(mine))36print("spans from the contacts server, all messages:", len(theirs))37print("contacts server spans under an assistant span:", sum(row["parent_span_id"] in mine_ids for row in theirs))38print("stored assistant rows equal the exporter's rows: yes (asserted)")39receiver.stop()
python two-processes-one-receiver.pymessages replayed: 17
messages that called find_contact: 3
assistant traces with a message root: 17
assistant traces without one (the startup, with its discovery call): 1
traces with spans from both processes: 4
spans from the assistant, in the find_contact messages: 22
spans from the contacts server, in the find_contact messages: 7
spans from the assistant, all messages: 70
spans from the contacts server, all messages: 8
contacts server spans under an assistant span: 5
stored assistant rows equal the exporter's rows: yes (asserted)
按父链接统计已连接的跨度
+10 项证明来自The book's receiver holds both processes' spans,第 5 章再读一遍
建立在 span ID 的基础上,参见第1章,“手工构造 span”
建立在 trace 的基础上,参见第1章,“一条消息,一条追踪”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 37 行按所在的追踪统计联系人服务器跨度,但它的标签却说这些跨度位于某个助手跨度之下。请修改第 37 行,使它统计标签所描述的跨度。
原理何在
解释没有消息根的追踪
+10 项证明来自The book's receiver holds both processes' spans,第 5 章再读一遍
建立在 parent span 的基础上,参见第1章,“手工构造 span”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
输出报告了一条没有消息根的助手追踪,而示例称它是启动过程。下列哪种解释是正确的?
原理何在
The replay runs the messages from baseline day 1 that take the messages route, which goes to the messages tools: 17 in all, and 3 of them call find_contact. The receiver stores the spans of both processes, and the output counts each side. The server's spans sit in the trace of each message that asked for a contact. Of all the traces, 4 hold spans from both processes: the three lookups and the startup.
One trace in the replay answers no message, and that is by design: the contacts server starts once, inside a contacts startup span, so its discovery call is a trace of its own. It is the one root expected besides the message roots. A server started outside any span would make its server/discover call a detached root of its own, and one started per message would make one for every message. This replay follows chapter 4's one process per run, where a run is the server's whole life, here one replay. The output shows it: 1 assistant trace has no message root, and it is the startup. Every message has its own root, 17 in all, and each lookup joins its message's trace.
The rows the receiver stored equal the rows that lib/export.py writes for the same spans. That is the claim the rest of the book depends on. From here on, the book's queries read rows of this shape, and chapter 8 runs its failure queries on the receiver itself, so this check shows that those rows are what a backend would hold, not a copy the book made for its own queries.
The rows checked above are what the queries read, and the example writes them to a JSON Lines file first. connect() in lib/query.py opens an in-memory DuckDB connection, at 2.0.1, with one view named spans over that file.
1"""Query the receiver's stored rows with DuckDB: the spans each process stored, the join across the process boundary,2and the orphans (spans whose parent names no stored span). Every query orders by its group keys, so the printed order3is the same on every run; the server's own times are never printed."""4import tempfile5from pathlib import Path67from lib.case import load_messages, scenario_to_route8from lib.contacts_server import SERVICE_NAME9from lib.dayrun import run_day_traced10from lib.export import write_jsonl11from lib.otlp import start12from lib.query import connect1314DAY = "2026-12-08"15receiver = start() # the book's receiver on loopback, as in the example before16ids = {m.message_id for m in load_messages(DAY) if scenario_to_route(m.scenario) == "messages"}17run_day_traced(DAY, message_ids=ids, otlp_endpoint=receiver.endpoint) # both processes export to the receiver18with tempfile.TemporaryDirectory() as folder:19 rows_file = Path(folder) / "spans.jsonl" # the stored rows, as a file a query can read20 write_jsonl(rows_file, receiver.rows())21 db = connect(rows_file)22 assert db.execute("SELECT count(*) FROM spans").fetchone()[0] == len(receiver.rows())23 per_service = db.execute("SELECT service, count(*), count(DISTINCT trace_id) FROM spans GROUP BY service "24 "ORDER BY service").fetchall()25 server_names = db.execute("SELECT name, count(*) FROM spans WHERE service = ? GROUP BY name ORDER BY name",26 [SERVICE_NAME]).fetchall()27 # a server span whose parent is an assistant span: the join across the process boundary28 joins = db.execute("SELECT c.name, count(*) FROM spans c JOIN spans p ON c.parent_span_id = p.span_id "29 "WHERE c.service <> p.service GROUP BY c.name ORDER BY c.name").fetchall()30 both = db.execute("SELECT count(*) FROM (SELECT trace_id FROM spans GROUP BY trace_id "31 "HAVING count(DISTINCT service) = 2 ORDER BY trace_id)").fetchone()[0]32 orphans = db.execute("SELECT count(*) FROM spans c WHERE c.parent_span_id IS NOT NULL AND NOT EXISTS "33 "(SELECT 1 FROM spans p WHERE p.span_id = c.parent_span_id) ORDER BY 1").fetchone()[0]3435for service, count, traces in per_service:36 print(f"stored spans from {service}: {count}, in {traces} traces")37for name, count in server_names:38 print(f"contacts server spans named {name}: {count}")39for name, count in joins:40 print(f"contacts server spans under an assistant span, named {name}: {count}")41print("traces holding both processes' spans:", both)42print("orphans in the stored rows:", orphans)
python query-stored-spans.pystored spans from ambrewick-assistant: 70, in 18 traces
stored spans from contacts-server: 8, in 4 traces
contacts server spans named contacts.lookup: 3
contacts server spans named server/discover: 1
contacts server spans named tools/call find_contact: 3
contacts server spans named tools/list: 1
contacts server spans under an assistant span, named server/discover: 1
contacts server spans under an assistant span, named tools/call find_contact: 3
contacts server spans under an assistant span, named tools/list: 1
traces holding both processes' spans: 4
orphans in the stored rows: 0
自第 2026.11.2 版起由 duckdb2.0.0至2.0.1 更新。
The first two lines count the stored spans by process, the assistant's and the contacts server's. The join is the query that matters. A contacts server span whose parent is an assistant span crossed the process boundary and joined. Three names do that: tools/call find_contact, with 3 spans; server/discover, the startup's discovery, with 1; and tools/list, the tool listing, with 1. The lookup's own span, contacts.lookup, is not in that list, because its parent is the server's tools/call span. The join is one hop, at the server's entry point.
The last two lines are the checks that the halves joined. 4 traces hold spans from both processes, and 0 orphans are stored. The term is defined in Context is lost at a thread boundary, and a zero there means every stored parent link resolves. A GROUP BY or a join has no defined order in DuckDB, whatever the setting, and DuckDB's order-preservation page at version 2.0 lists both. So every query in the example orders its rows. A probe at this version, with the setting off, saw a query with no ORDER BY return its rows in a different order on another run.
Working rule: Send every process's spans to one receiver, and check the join, the detached roots and the orphan count before you read a query over one process. Leave the contacts startup span out of the detached-root count by its name. If no server span sits under an assistant span, or any orphan is stored, the halves did not join or a span was lost, and the other queries cannot yet be trusted. For a team, we recommend one receiver for every process, because a trace split over two stores cannot be read whole; the trade is one more place to run and keep.
这部分尚未翻译,因此以英文显示。
MLflow on SQLite takes the same spans
The receiver keeps rows in memory. A team needs a backend that stores them on disk and answers queries over them. MLflow 3.18.0 is one the book can run. Its OpenTelemetry ingest page says that OTLP ingest starts at 3.6.0, takes OTLP over HTTP only, with no gRPC, and needs a SQL-based backend store, which the book provides as SQLite. The route at this version declares the x-mlflow-experiment-id header as required, in its source (mlflow/server/otel_api.py). A probe found that without the header the route answers 422, a code the exporter does not retry, so the batch is dropped. The book's exporter always sends the header.
The book starts the server on loopback with a SQLite file in a temporary folder. It turns telemetry off through environment variables. It stops the server by its process group, since the server starts worker processes of its own and signalling the parent alone leaves them running.
1"""Send one message's three spans to MLflow 3.18.0 on SQLite over OTLP/HTTP, and read them back with search_traces. MLflow2returns span IDs base64-encoded, so the example decodes them before comparing. The code reads the trace's total token3usage from its metadata, and MLflow stores no cost, because it has no price for the model the chat span names."""4import tempfile56from lib.assistant import AGENT, RELEASES7from lib.clock import VirtualClock8from lib.export import spans_to_rows9from lib.genai import SCHEMA_URL10from lib.ids import SequentialIds11from lib.mlflow_server import otlp_exporter, running, stored_spans, trace_usage12from lib.otlp import message_spans13from lib.tracing import make_provider1415import mlflow16from opentelemetry.sdk.trace.export import SimpleSpanProcessor17from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1819DAY, RELEASE = "2026-12-07", RELEASES["r0"]20memory = InMemorySpanExporter()21clock = VirtualClock(DAY)22with tempfile.TemporaryDirectory() as folder, running(folder, "ambrewick-sample") as (uri, experiment):23 provider = make_provider(AGENT, RELEASE.service_version, "mlflow-search-traces", clock, SequentialIds(), memory,24 SCHEMA_URL)25 provider.add_span_processor(SimpleSpanProcessor(otlp_exporter(uri, experiment)))26 message_spans(provider.get_tracer("ambrewick.assistant"), clock)27 found = mlflow.search_traces(locations=[experiment])2829spans, usage = stored_spans(found), trace_usage(found)30root = next(span for span in spans if span["parent"] is None)31chat = next(span for span in spans if span["name"].startswith("chat "))32# the trace ID is "tr-" followed by the 32 hex digits of the OpenTelemetry trace ID, 35 characters in all33assert len(found) == 1 and len(found.iloc[0]["trace_id"]) == 35 and found.iloc[0]["trace_id"].startswith("tr-")34assert {span["span"] for span in spans} == {row["span_id"] for row in spans_to_rows(memory)} # decoded IDs match35assert all(span["parent"] in (None, root["span"]) for span in spans) # the chat and tool spans sit under the root36assert chat["attributes"]["mlflow.spanType"] == "CHAT_MODEL" # MLflow's own label, added on the chat span37assert usage["total"] == usage["input"] + usage["output"] # cache reads are not added again38# MLflow prices a span only when it knows the span's model, and this book's model is not in its table39assert "mlflow.llm.cost" not in chat["attributes"] and "mlflow.trace.cost" not in found.iloc[0]["trace_metadata"]4041print("traces found for the experiment:", len(found))42print("spans in the trace:", len(spans))43print("span IDs, decoded from base64, equal the exporter's IDs: yes (asserted)")44print("chat span, MLflow span type:", chat["attributes"]["mlflow.spanType"])45print("chat span, model MLflow recorded:", chat["attributes"]["mlflow.llm.model"])46print("trace token usage, input:", usage["input"])47print("trace token usage, output:", usage["output"])48print("trace token usage, cache read:", usage["cache_read"])49print("trace token usage, total = input + output: yes (asserted)")50print("cost MLflow stored for this model, on the chat span and in the trace: none (asserted)")
python mlflow-search-traces.pytraces found for the experiment: 1
spans in the trace: 3
span IDs, decoded from base64, equal the exporter's IDs: yes (asserted)
chat span, MLflow span type: CHAT_MODEL
chat span, model MLflow recorded: qwen3-4b-instruct-2507
trace token usage, input: 331
trace token usage, output: 38
trace token usage, cache read: 192
trace token usage, total = input + output: yes (asserted)
cost MLflow stored for this model, on the chat span and in the trace: none (asserted)
让令牌总数检查与求和一致
+10 项证明来自MLflow on SQLite takes the same spans,第 5 章再读一遍
建立在 attribute 的基础上,参见第1章,“手工构造 span”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 37 行把缓存读取也加进了总数检查,因此在本书的数据上断言失败,运行在打印之前就停止了。请修正第 37 行,使检查通过,并使该示例打印出每一行。
原理何在
MLflow hands back the same three spans, with their IDs in its own encodings. They are the dev-day message from the exporter section, and they come back through search_traces(locations=...). MLflow returns 1 trace with 3 spans. Its trace ID is tr- followed by the 32 hexadecimal digits of the OpenTelemetry trace ID, and its span IDs come back base64-encoded. They are decoded before the check, which asserts that the decoded IDs equal the exporter's, so each span can be matched to its source. experiment_ids is deprecated in favour of locations, as @deprecated_parameter("experiment_ids", "locations") in mlflow/tracing/fluent.py shows, so the code passes locations. A probe saw a FutureWarning from the old argument.
MLflow marks the chat span with its own attribute, mlflow.spanType, and the marked value is CHAT_MODEL. MLflow keeps the span's gen_ai.usage.* attributes, adds its own mlflow.chat.tokenUsage on the chat span, and sums usage for the trace in its metadata, mlflow.trace.tokenUsage. The code reads the trace's total from that metadata: 331 input tokens, 38 output tokens and 192 cache-read tokens. The total is checked to be the input plus the output, so the cache reads are not added twice.
MLflow priced nothing. At 3.18.0 it prices a span into mlflow.llm.cost and the trace into mlflow.trace.cost when its price lookup knows the model. It has no price for qwen3-4b-instruct-2507, the model the chat span names, so it stored no cost on either. Chapter 6 prices tokens with the book's own table, because the model is self-hosted and a price has a date.
1"""Send one message's spans, from one provider, to two receivers: the book's receiver and MLflow. Both hold the same span2IDs and the same attributes, and MLflow adds its own attributes under mlflow.*; the book's receiver adds none."""3import tempfile45from lib.assistant import AGENT, RELEASES6from lib.clock import VirtualClock7from lib.genai import SCHEMA_URL8from lib.ids import SequentialIds9from lib.mlflow_server import otlp_exporter, running, stored_spans10from lib.otlp import message_spans, start11from lib.tracing import make_provider1213import mlflow14from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter15from opentelemetry.sdk.trace.export import SimpleSpanProcessor16from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1718DAY, RELEASE = "2026-12-07", RELEASES["r0"]19receiver = start() # the book's receiver on loopback20clock = VirtualClock(DAY)21with tempfile.TemporaryDirectory() as folder, running(folder, "ambrewick-two-backends") as (uri, experiment):22 provider = make_provider(AGENT, RELEASE.service_version, "same-spans-two-receivers", clock, SequentialIds(),23 InMemorySpanExporter(), SCHEMA_URL)24 provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint=receiver.endpoint)))25 provider.add_span_processor(SimpleSpanProcessor(otlp_exporter(uri, experiment)))26 message_spans(provider.get_tracer("ambrewick.assistant"), clock)27 found = mlflow.search_traces(locations=[experiment])2829book = {row["span_id"]: row for row in receiver.rows()}30other = {span["span"]: span for span in stored_spans(found)}31receiver.stop()32assert len(book) == len(other) == 3 and set(book) == set(other) # the same spans in both33added = set()34for span_id, row in book.items():35 kept = {key: value for key, value in other[span_id]["attributes"].items() if not key.startswith("mlflow.")}36 assert kept == row["attributes"] # every attribute the book stored is still there, unchanged37 assert not any(key.startswith("mlflow.") for key in row["attributes"]) # the book's rows hold no mlflow.* keys38 added |= set(other[span_id]["attributes"]) - set(row["attributes"])3940print("spans received by the book's receiver:", len(book))41print("spans received by MLflow:", len(other))42print("the same span IDs in both: yes (asserted)")43print("the book's attributes equal in both, on every span: yes (asserted)")44print("attributes MLflow adds, by name:", ", ".join(sorted(added)))45print("mlflow.* attributes in the book's rows: none (asserted)")
python same-spans-two-receivers.pyspans received by the book's receiver: 3
spans received by MLflow: 3
the same span IDs in both: yes (asserted)
the book's attributes equal in both, on every span: yes (asserted)
attributes MLflow adds, by name: mlflow.chat.tokenUsage, mlflow.llm.model, mlflow.llm.provider, mlflow.spanType, mlflow.traceRequestId
mlflow.* attributes in the book's rows: none (asserted)
为什么接收端的行中没有 MLflow 键
+10 项证明来自MLflow on SQLite takes the same spans,第 5 章再读一遍
建立在 attribute 的基础上,参见第1章,“手工构造 span”
建立在 exporter 的基础上,参见第1章,“手工构造 span”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
输出显示,本书的接收端没有存储任何 mlflow.* 属性,而 MLflow 中同一批跨度的副本却有这些属性。下列哪种解释是正确的?
原理何在
One provider can carry two processors, so the same spans can reach the receiver and MLflow in one run. The receiver and MLflow hold the same span IDs, and every attribute the receiver stored is in MLflow's copy unchanged, once MLflow's JSON-text values are decoded. MLflow adds mlflow.chat.tokenUsage, mlflow.llm.model, mlflow.llm.provider, mlflow.spanType, mlflow.traceRequestId, all under mlflow., and the receiver's rows hold none of them.
MLflow's docs at this version name no flag for its GenAI conventions, but the code has MLFLOW_ENABLE_OTEL_GENAI_SEMCONV. At 3.18.0 the flag is read only by MLflow's own client-side span processor (mlflow/tracing/processor/otel.py), before MLflow's SDK exports the spans it made itself. The server's ingest route never reads it. So the flag governs how MLflow's SDK exports its own spans, not what the server stores from the book's exporter, and the book's path never reaches it.
Working rule: Give each backend its own exporter, and check its stored span IDs and attributes against the exporter's before you trust its queries. Set the experiment header on the OTLP exporter, search with locations, decode the span IDs, and read the trace's total from its metadata. In production we recommend a backend that keeps its rows on disk and is checked against the exporter, because a query is only as good as the rows it reads. The cost is one more service to run and keep.
这部分尚未翻译,因此以英文显示。
What the other backends say
MLflow is one backend these spans reach unchanged. Four others are named here as places the same names might go: Langfuse, Arize Phoenix, Jaeger and Datadog. We ran none of them. Each paragraph gives the date or version of the page we read and what that page says. A page's claim is the vendor's, and this book does not rank the four.
Langfuse's OpenTelemetry integration page, which is undated, says that it accepts OTLP at a /api/public/otel path, over HTTP with JSON or with protobuf, and that it does not support gRPC. It uses Basic authentication with a key pair. It maps some gen_ai.* attributes to its own fields, and it says its own langfuse.* attributes take precedence. The mapping names gen_ai.prompt and gen_ai.completion, which are older names than the gen_ai.input.messages that chapter 3's capture switch writes. The page says Langfuse aims to be compliant with the GenAI conventions, and gives no version for them.
Arize Phoenix's release note of 2026-05-15 says that Phoenix converts incoming gen_ai.* attributes to OpenInference attributes when spans arrive. The statements in this paragraph are from arize-phoenix 15.10.0, per that release note. Conversion fills in only what is missing, so an attribute that is already OpenInference wins, and the note names no flag to turn it off or on. Phoenix's own Python setup sends spans with OpenInference conventions. Phoenix takes spans at POST /v1/traces, in protobuf only, sent as application/x-protobuf with gzip or deflate, so unlike Langfuse it takes no JSON. The route is in traces.py at tag arize-phoenix-v22.0.1. Phoenix's licence begins "Elastic License 2.0 (ELv2)", and that is one reason the book does not depend on it.
Jaeger's documentation at version 2.23 describes Jaeger as a distribution of the OpenTelemetry Collector framework, on its architecture page. Its OTLP receiver, in the same documentation, accepts spans sent over OTLP. The storage options on its pages are Badger, Cassandra, ClickHouse, Elasticsearch, Memory and OpenSearch, and Kafka, which sits in front of storage as a persistent queue rather than as a store. The pages we read say nothing about GenAI spans, so this chapter makes no claim about Jaeger and GenAI.
Datadog's OpenTelemetry ingestion page, which is undated, says that it accepts OTLP traces directly, without a Datadog Agent or its Agent Observability SDK, provided conversion is enabled. Conversion is enabled by the resource attribute dd_llmobs_enabled=true or by the export header DD-LLMObs-Enabled: true. A trace is eligible only when its spans follow the OpenTelemetry GenAI conventions from version 1.37 onward, or OpenInference, and carry one of a short list of attributes. The page does not say whether the GenAI conventions at v0.1.0, which the book writes, count as 1.37 onward. The page says spans can take three to five minutes to appear.
Working rule: When a backend says it reads the OpenTelemetry names, find out which names it maps, at what version, and on what date, before a team relies on the claim. When the page gives no version or date, say so beside the claim.
更换后端
接收器和 MLflow 都不需要在导出器与存储之间再放任何东西,而 OpenTelemetry Collector 通常就位于这个位置。它的概述称其为“接收、处理和导出遥测数据的、与厂商无关的方式”,其组件页面列出了五类组件:接收器、处理器、导出器、连接器和扩展。这两个页面均于 2026-11-23 打开,且都没有版本号。Collector 的接收器是这五类组件之一,它们不是本书所说的接收器,后者是本书自己的一个服务器。
概述还允许小型部署不使用 Collector,本书遵循这一做法。这里的 span 直接发送到本书的接收器或 MLflow,二者都能直接接收 OTLP,因此本章不运行 Collector。
因此,更换后端就是修改导出器。SQLite 上的 MLflow中的双接收器运行,已经通过增加第二个处理器、保持 span 代码不变,把同一个提供方的 span 发送到了两个接收器。两处的属性相互一致。这就是全部的改动:插桩和 span 保持不变,由导出器上的端点和请求头指明它们的去向。
在本书其余部分,Collector 承担两项工作,本书会在各自出现的地方指明。第 11 章决定保留哪些完整的链路,这要求一条链路的所有 span 都汇集在同一处。尾部采样处理器的 README(contrib v0.140.0)给出了原因:“All spans for a given trace MUST be received by the same collector instance for effective sampling decisions.”在示例中,第 11 章在本书的接收器里执行这一决定,而在生产环境中执行它的是 Collector。第 12 章在 span 离开进程之前移除其中的个人数据。Collector 的概述把敏感数据过滤列为 Collector 的功能之一,所以它也是可以执行同一步骤的位置。第 12 章首先在进程内进行脱敏,因此 Collector 是第二道防线,而不是替代。
**工作准则:**在导出器上设置端点和请求头,不改动 span 代码,使更换后端只是一次设置的更改。只有当某条规则需要看到完整链路,或需要在数据离开之前修改数据时,才加入 Collector,在此之前不要加。小型部署可以不用它。在某条规则需要完整链路之前,我们不加入 Collector,因为 Collector 是多出的一跳,需要运行并维护,本书只在规则需要时才付出这一代价。
生产环境中会出什么问题
第 1 章已经指明,生产环境应选用批处理器,而本章的导出器说明了原因。使用简单处理器时,如果端点响应缓慢或已关闭,结束某个 span 的那次请求就会被阻塞;在默认超时下,这段时间约为 7 秒,这是 The exporter sends each span over OTLP 所述探测中的结果。使用批处理器时,导出按处理器自己的调度进行,因此请求不必等待。批处理器的代价正是第 1 章所指出的那一条:如果进程终止,仍在其队列中的 span 会丢失。通过批处理器写出 span 的服务器,必须在退出前将这些 span 刷新出去,The contacts server is another process 以联系人服务器为例对此做了说明。
另一种故障更为隐蔽,应用程序对此毫无察觉:导出器会记录一条批次丢失的日志,然后继续运行。根据该软件包的源代码,超过导出器默认请求上限 64 MiB 的批次,同样会被整体丢弃,而不会被拆分。因此在生产环境中,批次丢失会体现在导出器的日志里,想要掌握丢失情况的团队必须阅读该日志,或针对它设置告警。
工作准则: 在生产环境中,保留批处理器,确保每台服务器在退出前完成刷新,并通过导出器的日志查看被丢弃的批次。不要指望应用程序报告丢失,因为导出器不会向它抛出任何错误。
本章的决定
- 我们通过 OTLP/HTTP 把每个进程的 span 发送到接收器,本书的路径中不运行 Collector。在这个规模下并不需要 Collector,第 11 章和第 12 章可以说明 Collector 应放在哪里,而无需运行它。
- 本书的接收器在一次运行期间把数据行保存在内存中,MLflow 则把它们保存在磁盘上的 SQLite 中。两者保存的都是导出器的 span,ID 和属性相同,之后的每次查询读取的都是接收器中的数据行。
- 打印出来的检查使用简单处理器运行,它在每个 span 结束时就把它交给导出器。生产环境使用批处理器。
- 关联(join)和孤立 span 的计数以数字形式打印出来,而不是留给读者凭眼睛判断,因此破坏关联的改动会表现为计数发生变化。
- 每个后端都有自己的导出器,后端所存储的数据行要与该导出器的数据行核对,如最后一条所述。
- 对于列出名称的后端,我们依据读过的页面加以描述,并标明日期或版本,不运行任何一个,也不做排名。
- MLflow 的 GenAI 开关保持关闭,因为它不适用于本书的路径。
- 后端是否声称能读取 OpenTelemetry 的名称,要通过比较它所存储的数据行与导出器的数据行来核对,而不是照着它的页面来判断。
本章,在本版次中
版次 2026.11.2示例于 2026年11月23日 通过5 of 5个示例 in this chapter pass
译自英文版图书,版次 2026.11.2。