직접 실행할 수 있는 백엔드로 트레이스 보내기

읽는 데 약 44분, 7절에 5개 예제이(가) 있음.

2026.11.2판 예제 통과 2026년 11월 23 80개 예제 중 80개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.2판을 번역한 것이다. 원문 읽기

Labs

직접 해 보며 이 장을 배운다

모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. 약 30초 안에 열린다.

모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. Labs가 실행을 대신한다: 월 40시간.

Lab에서 열기, 새 탭에서

이용 시간을 확인하는 중…

Lab을 찾는 중…

자신의 컴퓨터에서, 무료로: 이 책의 노트북 내려받기, 코드와 데이터를 포함해 GitHub에서 받을 수 있다.

이 장을 마치면 두 프로세스의 스팬을 한 대의 머신에서 실행하는 하나의 수신기로 보낼 수 있다. 수신기가 익스포터가 보낸 행을 그대로 저장했는지 확인하고, 그 행을 SQL로 조회할 수 있다. 또한 이름이 알려진 각 백엔드가 무엇을 받아들이고 해당 백엔드의 문서 페이지가 무엇을 말하지 않는지 설명할 수 있다. 4장은 Ambrewick에 보낸 메시지 하나가 두 곳에 나뉘어 있는 상태로 끝났다. 어시스턴트의 스팬은 메모리에 있고, 연락처 서버는 자신의 스팬을 파일에 기록하며 어시스턴트는 서버가 종료된 뒤에야 그 파일을 읽는다. 어느 쪽도 메시지 전체에 대한 질문에 답하지 못한다. 두 팀에게는 내년에 바꿀 수 있으면서 두 스팬을 함께 조회할 수 있는 한 곳이 필요하다.

이 장의 모든 수치는 기록된 실행에서 예제가 출력한 값이다. 그 밖의 몇몇 수치는 프로브나 인용한 페이지에서 가져온 것이며, 본문에서 어느 쪽인지 밝힌다. 따라서 이 장에서는 두 프로세스를 위한 수신기 하나를 만들고, 그 수신기의 행을 익스포터의 행과 대조하며, 그 옆에 디스크 기반 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

본문이 프로토버프인 이유

+10 증명

예제는 요청마다 "content types of the requests: application/x-protobuf"라고 출력한다. 본문이 JSON이 아니라 프로토버프인 이유는 무엇인가?

본문이 프로토버프인 이유: 올바른 설명을 고른다
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

조인된 스팬을 부모 링크로 세기

+10 증명

37행은 contacts 서버 스팬을 그 스팬이 속한 트레이스를 기준으로 세지만, 레이블에는 어시스턴트 스팬 아래에 있다고 적혀 있다. 레이블이 설명하는 스팬을 세도록 37행을 고쳐라.

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 증명

출력은 메시지 루트가 없는 어시스턴트 트레이스를 보고하며, 예제는 이것이 시작 트레이스라고 설명한다. 어떤 설명이 올바른가?

메시지 루트가 없는 트레이스 설명하기: 올바른 설명을 고른다
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

토큰 총합 검사를 합계와 일치시키기

+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 사본에는 그 속성이 있다. 어느 설명이 옳은가?

수신기의 행에 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다. Collector의 개요는 Collector를 "텔레메트리 데이터를 수신, 처리, 내보내는 벤더 중립적인 방법"이라고 소개하며, 컴포넌트 페이지는 컴포넌트를 리시버, 프로세서, 익스포터, 커넥터, 익스텐션의 다섯 종류로 나열한다. 두 페이지는 모두 2026-11-23에 열람했으며 버전이 붙어 있지 않다. Collector의 리시버는 이 다섯 종류의 컴포넌트 가운데 하나다. 이 책의 리시버, 즉 이 책이 직접 만든 서버와는 다르다.

개요는 작은 구성이라면 Collector 없이 가도 된다고도 밝히며, 이 책은 그 방식을 따른다. 여기서는 스팬이 OTLP를 직접 받는 이 책의 리시버나 MLflow로 곧바로 가며, 이 장에서는 Collector를 실행하지 않는다.

따라서 백엔드를 바꾸는 일은 익스포터를 바꾸는 일이다. SQLite 위의 MLflow에서 수행한 두 리시버 실행은 프로세서를 하나 더 추가하고 스팬 코드는 그대로 두는 방식으로, 한 프로바이더의 스팬을 이미 두 리시버에 보냈다. 두 곳의 속성은 일치한다. 이것이 전부다. 계측과 스팬은 그대로 두고, 익스포터의 엔드포인트와 헤더가 스팬이 갈 곳을 정한다.

Collector는 이 책의 나머지 부분에서 두 가지 일을 하며, 책은 각각이 등장하는 곳에서 그 이름을 밝힌다. 11장은 어떤 트레이스를 통째로 남길지 결정하는데, 이를 위해서는 한 트레이스의 모든 스팬이 한곳에 있어야 한다. 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장은 개인 데이터가 프로세스를 떠나기 전에 스팬에서 제거한다. Collector의 개요는 Collector가 하는 일로 민감 데이터 필터링을 꼽으므로, 같은 단계를 실행할 수 있는 또 하나의 자리다. 12장은 마스킹을 먼저 프로세스 안에 두므로, Collector는 대체재가 아니라 두 번째 방어선이다.

작업 규칙: 익스포터에 엔드포인트와 헤더를 설정하고 스팬 코드는 건드리지 않아서, 백엔드를 바꾸는 일이 설정 변경이 되도록 한다. 규칙이 트레이스 전체를 봐야 하거나 데이터가 떠나기 전에 바꿔야 할 때 Collector를 추가하며, 그 전에는 추가하지 않는다. 작은 구성은 Collector 없이도 갈 수 있다. 규칙이 트레이스 전체를 필요로 하기 전까지는 Collector를 추가하지 않는다. Collector는 실행하고 동작을 유지해야 할 홉이 하나 더 늘어나는 것이고, 이 책은 규칙이 필요로 할 때만 그 비용을 치르기 때문이다.

운영 환경에서 발생하는 문제

1장에서는 운영 환경의 선택지로 배치 프로세서를 지목했으며, 이 장의 익스포터는 그 이유를 보여 준다. 단순 프로세서를 사용하면 엔드포인트가 느리거나 닫혀 있을 때 스팬을 끝내는 요청이 대기하게 된다. The exporter sends each span over OTLP에서 설명한 프로브에서 기본 타임아웃일 때 그 대기 시간은 약 7초이다. 배치 프로세서를 사용하면 내보내기가 프로세서 자체의 일정에 따라 실행되므로 요청이 기다리지 않는다. 배치 프로세서의 비용은 1장에서 언급한 것과 같다. 프로세스가 죽으면 큐에 남아 있던 스팬이 유실된다. 배치를 통해 스팬을 기록하는 서버는 종료하기 전에 스팬을 플러시해야 하며, 이는 The contacts server is another process에서 contacts 서버를 예로 설명한다.

다른 실패는 더 조용하게 일어나며 애플리케이션은 이를 전혀 알지 못한다. 익스포터는 유실된 배치를 로그에 남기고 다음 작업으로 넘어간다. 또한 패키지의 소스에 따르면, 익스포터의 기본 요청 한도인 64 MiB보다 큰 배치는 나뉘지 않고 통째로 버려진다. 따라서 운영 환경에서 유실된 배치는 익스포터의 로그에 나타나며, 유실을 알고자 하는 팀은 그 로그를 읽거나 그에 대한 알림을 설정해야 한다.

작업 규칙: 운영 환경에서는 배치 프로세서를 유지하고, 각 서버가 종료하기 전에 플러시하도록 하며, 버려진 배치가 있는지 익스포터의 로그를 확인한다. 익스포터는 유실을 애플리케이션에 예외로 알리지 않으므로, 애플리케이션이 유실을 보고해 주리라고 기대해서는 안 된다.

이 장에서 결정한 것

  • 각 프로세스의 스팬을 OTLP/HTTP로 수신기에 보내며, 이 책의 경로에서는 Collector를 실행하지 않는다. 이 규모에서는 Collector가 필요하지 않으며, 11장과 12장은 Collector를 실행하지 않고도 Collector가 놓일 위치를 설명할 수 있다.
  • 이 책의 수신기는 한 번의 실행 동안 행을 메모리에 보관하고, MLflow는 행을 디스크의 SQLite에 보관한다. 둘 다 exporter가 보낸 스팬을 같은 ID와 속성으로 보관하며, 이후의 모든 질의는 수신기의 행을 읽는다.
  • 출력되는 검사는 simple processor에서 실행한다. simple processor는 스팬이 끝나는 즉시 모든 스팬을 exporter에 넘긴다. 운영 환경에서는 batch processor를 사용한다.
  • 조인과 고아 스팬의 수는 독자의 눈에 맡기지 않고 숫자로 출력한다. 따라서 조인을 깨뜨리는 변경은 수치가 변하는 개수로 드러난다.
  • 각 백엔드에는 고유한 exporter가 있으며, 백엔드가 저장한 행은 앞의 항목에서 말했듯이 exporter의 행과 대조하여 확인한다.
  • 이름을 든 백엔드는 우리가 읽은 페이지를 바탕으로 그 날짜 또는 버전과 함께 설명하며, 어느 것도 실행하거나 순위를 매기지 않는다.
  • MLflow GenAI 플래그는 이 책의 경로에 적용되지 않으므로 꺼 둔다.
  • 백엔드가 OpenTelemetry 이름을 읽는다는 주장은 해당 페이지에서 확인하지 않고, 백엔드가 저장한 행을 exporter의 행과 비교하여 확인한다.

이 판의 이 장

2026.11.2판예제 통과 2026년 11월 235 of 5개 예제 in this chapter pass

영어판 2026.11.2판을 번역한 것이다.

Labs 시작

도서는 계속 무료로 읽을 수 있다.

요금 보기

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

12장 중 5장: 직접 실행할 수 있는 백엔드로 트레이스 보내기

  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. 이 장에서 결정한 것

맨 위로 돌아가기전체 장