將追蹤資料送到你能自行執行的後端

閱讀約 67 分鐘,7 節 中共有 5 個範例。

版次 2026.11.2 範例於 2026年11 月 23 通過測試 80 個範例中有 80 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.2。 閱讀原文

Labs

透過實作學習本章

完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。約 30 秒內開啟。

完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。由 Labs 為你執行:每月 40 小時。

在 Lab 中開啟,於新分頁開啟

正在檢查您的時數…

正在尋找您的 Lab…

於您自己的電腦,免費: 下載本書的筆記本,連同其程式碼與資料,皆取自 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.

otlp-export-loopback.py Python 3.13.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通過
"""Export one dev-day message's three spans over OTLP/HTTP to the book's receiver on loopback, and check that a span'srequest is in the receiver when its span.end() returns. The stored rows equal the in-memory exporter's rows, so theprotobuf round trip loses nothing the book's rows keep; the request count is printed and the yes lines are asserted."""from lib.assistant import AGENT, RELEASESfrom lib.clock import VirtualClockfrom lib.export import spans_to_rowsfrom lib.genai import SCHEMA_URLfrom lib.ids import SequentialIdsfrom lib.otlp import message_spans, startfrom lib.tracing import make_providerfrom opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporterfrom opentelemetry.sdk.resources import Resourcefrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import SimpleSpanProcessorfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporterDAY, RELEASE = "2026-12-07", RELEASES["r0"]receiver = start()                       # the book's receiver on loopback; the port is never printedmemory = InMemorySpanExporter()          # the same spans, kept in memory, to compare with what arrivesclock = VirtualClock(DAY)provider = make_provider(AGENT, RELEASE.service_version, "otlp-export-loopback", clock, SequentialIds(), memory, SCHEMA_URL)# SimpleSpanProcessor calls the exporter when each span ends, so the request is sent on the ending thread (O-7)provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint=receiver.endpoint)))root, chat, tool = message_spans(provider.get_tracer("ambrewick.assistant"), clock)assert receiver.address == "127.0.0.1"   # bound to loopback only, never to a network addressassert len(receiver.requests()) == 3     # one request per span the processor exportedassert sum(count == 1 for _, count in receiver.requests()) == 3  # each request holds one spanassert receiver.rows() == spans_to_rows(memory)  # the stored rows equal the exporter's own rows# A span from a provider with only the OTLP exporter: its request must be in the receiver when end() returns.probe = TracerProvider(resource=Resource.create({"service.name": AGENT, "service.instance.id": "probe"}))probe.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint=receiver.endpoint)))before = len(receiver.requests())# 36001 s is an offset on the virtual clock, past the message's spans, so the probe's times do not overlap themprobe.get_tracer("probe").start_span("probe", start_time=clock.at(36001)).end(end_time=clock.at("36001.1"))assert len(receiver.requests()) == before + 1print("bound to loopback: yes (asserted)")print("requests for the message's three spans:", before)print("spans per request: one in each, for every request (asserted)")print("content types of the requests:", ", ".join(sorted({kind for kind, _ in receiver.requests()})))print("stored rows equal the exporter's rows: yes (asserted)")print("a request is in the receiver when span.end() returns: yes (asserted)")receiver.stop()
輸出python otlp-export-loopback.py
bound 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)
習題 5.1

為什麼請求本文是 protobuf

+10 則證明

這個範例為它送出的請求印出「content types of the requests: application/x-protobuf」。為什麼請求本文是 protobuf,而不是 JSON?

為什麼請求本文是 protobuf:選出正確的說明
在 Python 3.13.16 上執行

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

最近一次變動於第 2026.11.2 版

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.

two-processes-one-receiver.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通過
"""Replay baseline day 1's messages that route to the messages tools, with the contacts server live, and send bothprocesses' spans to one receiver: every server span joins a trace the assistant made. The server's clock is its own,so the example prints counts only, never a span time from it."""from lib.assistant import AGENTfrom lib.case import load_messages, scenario_to_routefrom lib.contacts_server import SERVICE_NAMEfrom lib.dayrun import run_day_tracedfrom lib.otlp import startDAY = "2026-12-08"receiver = start()                   # the book's receiver on loopback; its port is never printedids = {m.message_id for m in load_messages(DAY) if scenario_to_route(m.scenario) == "messages"}  # only these can call a contacts tooltraced = run_day_traced(DAY, message_ids=ids, otlp_endpoint=receiver.endpoint)  # both processes export herestored = receiver.rows()mine = [row for row in stored if row["resource"]["service.name"] == AGENT]theirs = [row for row in stored if row["resource"]["service.name"] == SERVICE_NAME]mine_ids = {row["span_id"] for row in mine}find = {row["trace_id"] for row in mine if row["name"] == "execute_tool find_contact"}  # those messages' tracesboth = {row["trace_id"] for row in mine} & {row["trace_id"] for row in theirs}assert mine == traced.spans                    # the stored assistant rows equal export.py's rowsassert find <= {row["trace_id"] for row in theirs}  # each find_contact message has server spans in its traceassert find <= {row["trace_id"] for row in mine if row["name"].startswith("invoke_agent")}  # and a message root# every server span whose parent is set names a stored span, from either process: the join crosses no gapassert all(row["parent_span_id"] in mine_ids | {r["span_id"] for r in theirs} for row in theirs if row["parent_span_id"])rooted = {row["trace_id"] for row in mine if row["name"].startswith("invoke_agent")}print("messages replayed:", len(traced.runs))print("messages that called find_contact:", len(find))print("assistant traces with a message root:", len(rooted))print("assistant traces without one (the startup, with its discovery call):", len({row["trace_id"] for row in mine} - rooted))print("traces with spans from both processes:", len(both))print("spans from the assistant, in the find_contact messages:", sum(row["trace_id"] in find for row in mine))print("spans from the contacts server, in the find_contact messages:", sum(row["trace_id"] in find for row in theirs))print("spans from the assistant, all messages:", len(mine))print("spans from the contacts server, all messages:", len(theirs))print("contacts server spans under an assistant span:", sum(row["parent_span_id"] in mine_ids for row in theirs))print("stored assistant rows equal the exporter's rows: yes (asserted)")receiver.stop()
輸出python two-processes-one-receiver.py
messages 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)
習題 5.2

依父連結計算已連接的 span

+10 則證明

第 37 行依 trace 計算 contacts 伺服器 span 的數量,但其標籤卻說這些 span 位於某個助理 span 之下。請修改第 37 行,讓它計算標籤所描述的 span。

print("spans from the contacts server, in the find_contact messages:", sum(row["trace_id"] in find for row in theirs))print("spans from the assistant, all messages:", len(mine))print("spans from the contacts server, all messages:", len(theirs))print("stored assistant rows equal the exporter's rows: yes (asserted)")receiver.stop()
在 Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3 上執行
習題 5.3

解釋沒有訊息根節點的追蹤

+10 則證明

輸出回報了一條沒有訊息根節點(message root)的助理追蹤,而範例說明這是啟動過程。下列哪一項解釋是正確的?

解釋沒有訊息根節點的追蹤:選出正確的說明
在 Python 3.13.16 上執行

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.

query-stored-spans.py Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通過
"""Query the receiver's stored rows with DuckDB: the spans each process stored, the join across the process boundary,and the orphans (spans whose parent names no stored span). Every query orders by its group keys, so the printed orderis the same on every run; the server's own times are never printed."""import tempfilefrom pathlib import Pathfrom lib.case import load_messages, scenario_to_routefrom lib.contacts_server import SERVICE_NAMEfrom lib.dayrun import run_day_tracedfrom lib.export import write_jsonlfrom lib.otlp import startfrom lib.query import connectDAY = "2026-12-08"receiver = start()                   # the book's receiver on loopback, as in the example beforeids = {m.message_id for m in load_messages(DAY) if scenario_to_route(m.scenario) == "messages"}run_day_traced(DAY, message_ids=ids, otlp_endpoint=receiver.endpoint)  # both processes export to the receiverwith tempfile.TemporaryDirectory() as folder:    rows_file = Path(folder) / "spans.jsonl"          # the stored rows, as a file a query can read    write_jsonl(rows_file, receiver.rows())    db = connect(rows_file)    assert db.execute("SELECT count(*) FROM spans").fetchone()[0] == len(receiver.rows())    per_service = db.execute("SELECT service, count(*), count(DISTINCT trace_id) FROM spans GROUP BY service "                             "ORDER BY service").fetchall()    server_names = db.execute("SELECT name, count(*) FROM spans WHERE service = ? GROUP BY name ORDER BY name",                              [SERVICE_NAME]).fetchall()    # a server span whose parent is an assistant span: the join across the process boundary    joins = db.execute("SELECT c.name, count(*) FROM spans c JOIN spans p ON c.parent_span_id = p.span_id "                       "WHERE c.service <> p.service GROUP BY c.name ORDER BY c.name").fetchall()    both = db.execute("SELECT count(*) FROM (SELECT trace_id FROM spans GROUP BY trace_id "                      "HAVING count(DISTINCT service) = 2 ORDER BY trace_id)").fetchone()[0]    orphans = db.execute("SELECT count(*) FROM spans c WHERE c.parent_span_id IS NOT NULL AND NOT EXISTS "                         "(SELECT 1 FROM spans p WHERE p.span_id = c.parent_span_id) ORDER BY 1").fetchone()[0]for service, count, traces in per_service:    print(f"stored spans from {service}: {count}, in {traces} traces")for name, count in server_names:    print(f"contacts server spans named {name}: {count}")for name, count in joins:    print(f"contacts server spans under an assistant span, named {name}: {count}")print("traces holding both processes' spans:", both)print("orphans in the stored rows:", orphans)
輸出python query-stored-spans.py
stored 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 版由 duckdb 2.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.

mlflow-search-traces.py Python 3.13.16 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通過
"""Send one message's three spans to MLflow 3.18.0 on SQLite over OTLP/HTTP, and read them back with search_traces. MLflowreturns span IDs base64-encoded, so the example decodes them before comparing. The code reads the trace's total tokenusage from its metadata, and MLflow stores no cost, because it has no price for the model the chat span names."""import tempfilefrom lib.assistant import AGENT, RELEASESfrom lib.clock import VirtualClockfrom lib.export import spans_to_rowsfrom lib.genai import SCHEMA_URLfrom lib.ids import SequentialIdsfrom lib.mlflow_server import otlp_exporter, running, stored_spans, trace_usagefrom lib.otlp import message_spansfrom lib.tracing import make_providerimport mlflowfrom opentelemetry.sdk.trace.export import SimpleSpanProcessorfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporterDAY, RELEASE = "2026-12-07", RELEASES["r0"]memory = InMemorySpanExporter()clock = VirtualClock(DAY)with tempfile.TemporaryDirectory() as folder, running(folder, "ambrewick-sample") as (uri, experiment):    provider = make_provider(AGENT, RELEASE.service_version, "mlflow-search-traces", clock, SequentialIds(), memory,                             SCHEMA_URL)    provider.add_span_processor(SimpleSpanProcessor(otlp_exporter(uri, experiment)))    message_spans(provider.get_tracer("ambrewick.assistant"), clock)    found = mlflow.search_traces(locations=[experiment])spans, usage = stored_spans(found), trace_usage(found)root = next(span for span in spans if span["parent"] is None)chat = next(span for span in spans if span["name"].startswith("chat "))# the trace ID is "tr-" followed by the 32 hex digits of the OpenTelemetry trace ID, 35 characters in allassert len(found) == 1 and len(found.iloc[0]["trace_id"]) == 35 and found.iloc[0]["trace_id"].startswith("tr-")assert {span["span"] for span in spans} == {row["span_id"] for row in spans_to_rows(memory)}  # decoded IDs matchassert all(span["parent"] in (None, root["span"]) for span in spans)  # the chat and tool spans sit under the rootassert chat["attributes"]["mlflow.spanType"] == "CHAT_MODEL"  # MLflow's own label, added on the chat spanassert usage["total"] == usage["input"] + usage["output"]  # cache reads are not added again# MLflow prices a span only when it knows the span's model, and this book's model is not in its tableassert "mlflow.llm.cost" not in chat["attributes"] and "mlflow.trace.cost" not in found.iloc[0]["trace_metadata"]print("traces found for the experiment:", len(found))print("spans in the trace:", len(spans))print("span IDs, decoded from base64, equal the exporter's IDs: yes (asserted)")print("chat span, MLflow span type:", chat["attributes"]["mlflow.spanType"])print("chat span, model MLflow recorded:", chat["attributes"]["mlflow.llm.model"])print("trace token usage, input:", usage["input"])print("trace token usage, output:", usage["output"])print("trace token usage, cache read:", usage["cache_read"])print("trace token usage, total = input + output: yes (asserted)")print("cost MLflow stored for this model, on the chat span and in the trace: none (asserted)")
輸出python mlflow-search-traces.py
traces 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)
習題 5.4

讓 token 總數檢查與總和相符

+10 則證明

第 37 行把快取讀取數也加進總數檢查,因此在本書的資料上,斷言會失敗,執行在印出結果之前就停止。請修正第 37 行,使檢查通過,且範例印出每一行。

assert {span["span"] for span in spans} == {row["span_id"] for row in spans_to_rows(memory)}  # decoded IDs matchassert all(span["parent"] in (None, root["span"]) for span in spans)  # the chat and tool spans sit under the rootassert chat["attributes"]["mlflow.spanType"] == "CHAT_MODEL"  # MLflow's own label, added on the chat span# MLflow prices a span only when it knows the span's model, and this book's model is not in its tableassert "mlflow.llm.cost" not in chat["attributes"] and "mlflow.trace.cost" not in found.iloc[0]["trace_metadata"]
在 Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3 上執行

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.

same-spans-two-receivers.py Python 3.13.16 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通過
"""Send one message's spans, from one provider, to two receivers: the book's receiver and MLflow. Both hold the same spanIDs and the same attributes, and MLflow adds its own attributes under mlflow.*; the book's receiver adds none."""import tempfilefrom lib.assistant import AGENT, RELEASESfrom lib.clock import VirtualClockfrom lib.genai import SCHEMA_URLfrom lib.ids import SequentialIdsfrom lib.mlflow_server import otlp_exporter, running, stored_spansfrom lib.otlp import message_spans, startfrom lib.tracing import make_providerimport mlflowfrom opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporterfrom opentelemetry.sdk.trace.export import SimpleSpanProcessorfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporterDAY, RELEASE = "2026-12-07", RELEASES["r0"]receiver = start()                   # the book's receiver on loopbackclock = VirtualClock(DAY)with tempfile.TemporaryDirectory() as folder, running(folder, "ambrewick-two-backends") as (uri, experiment):    provider = make_provider(AGENT, RELEASE.service_version, "same-spans-two-receivers", clock, SequentialIds(),                             InMemorySpanExporter(), SCHEMA_URL)    provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint=receiver.endpoint)))    provider.add_span_processor(SimpleSpanProcessor(otlp_exporter(uri, experiment)))    message_spans(provider.get_tracer("ambrewick.assistant"), clock)    found = mlflow.search_traces(locations=[experiment])book = {row["span_id"]: row for row in receiver.rows()}other = {span["span"]: span for span in stored_spans(found)}receiver.stop()assert len(book) == len(other) == 3 and set(book) == set(other)  # the same spans in bothadded = set()for span_id, row in book.items():    kept = {key: value for key, value in other[span_id]["attributes"].items() if not key.startswith("mlflow.")}    assert kept == row["attributes"]  # every attribute the book stored is still there, unchanged    assert not any(key.startswith("mlflow.") for key in row["attributes"])  # the book's rows hold no mlflow.* keys    added |= set(other[span_id]["attributes"]) - set(row["attributes"])print("spans received by the book's receiver:", len(book))print("spans received by MLflow:", len(other))print("the same span IDs in both: yes (asserted)")print("the book's attributes equal in both, on every span: yes (asserted)")print("attributes MLflow adds, by name:", ", ".join(sorted(added)))print("mlflow.* attributes in the book's rows: none (asserted)")
輸出python same-spans-two-receivers.py
spans 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)
習題 5.5

為什麼接收端的資料列沒有 MLflow 鍵

+10 則證明

輸出顯示,本書的接收端沒有儲存任何 mlflow.* 屬性,但 MLflow 保存的同一批 span 卻有這些屬性。下列哪一項說明是正確的?

為什麼接收端的資料列沒有 MLflow 鍵:選出正確的說明
在 Python 3.13.16 上執行

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 通常就位於這個位置。它的概觀將其稱為「接收、處理並匯出遙測資料的廠商中立方式」,其元件頁面列出五種元件:接收器(receiver)、處理器(processor)、匯出器(exporter)、連接器(connector)與擴充套件(extension)。兩個頁面都在 2026-11-23 開啟,且皆未標示版本。Collector 的接收器是這五種元件之一,並不是本書的接收器;本書的接收器是本書自己的伺服器。

概觀也允許小型部署不使用 Collector,本書即採用這種做法。在此,span 直接送往本書的接收器或 MLflow,兩者都能直接接收 OTLP,因此本章不執行 Collector。

因此,更換後端就是修改匯出器。MLflow on SQLite中的雙接收器實驗,已經透過新增第二個處理器、並保持 span 程式碼不變,將同一個提供者的 span 送往兩個接收器。兩處的屬性相互一致。整個做法就是如此:instrumentation 與 span 維持不變,由匯出器上的端點與標頭決定它們送往何處。

Collector 在本書其餘部分有兩項工作,本書會在各自出現之處說明。第 11 章決定要保留哪些完整的追蹤,這需要同一條追蹤的所有 span 都集中在一處。tail-sampling 處理器在 contrib v0.140.0 的 README 給出了理由:「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,因為 Collector 是多一個需要執行並維持運作的躍點,本書只在規則需要時才付出這項成本。

正式環境中會出什麼問題

第 1 章已指明批次處理器(batch processor)是正式環境的選擇,而本章的匯出器(exporter)說明了原因。使用簡單處理器(simple processor)時,若端點速度緩慢或已關閉,結束某個 span 的請求會被卡住;在The exporter sends each span over OTLP所描述的探測中,以預設逾時計算約為 7 秒。使用批次處理器時,匯出會依處理器自己的排程執行,因此請求不必等待。批次處理器的代價則是第 1 章已指出的那一項:若行程終止,仍在其佇列中的 span 會遺失。以批次方式寫出 span 的伺服器,必須在結束前將這些 span 清空送出(flush),這一點在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。

開始 Labs

本書仍可免費閱讀。

查看價格

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 5 章,共 12 章: 將追蹤資料送到你能自行執行的後端

  1. The exporter sends each span over OTLP
  2. The book's receiver holds both processes' spans
  3. MLflow on SQLite takes the same spans
  4. What the other backends say
  5. 更換後端
  6. 正式環境中會出什麼問題
  7. 本章的決定

返回頂端所有章節