요청을 추적하고, 그 시간이 어디로 갔는지 묻기
읽는 데 약 26분, 7절에 6개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.2판을 번역한 것이다. 원문 읽기
Labs
직접 해 보며 이 장을 배운다
모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. 약 30초 안에 열린다.
모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. Labs가 실행을 대신한다: 월 40시간.
자신의 컴퓨터에서, 무료로: 이 책의 노트북 내려받기, 코드와 데이터를 포함해 GitHub에서 받을 수 있다.
책의 버전에서 코드 실행하기
이 장을 마치면 메시지 하나의 트레이스를 직접 만들고, 트리로 출력하고, 그 메시지의 시간과 토큰이 어디에 쓰였는지 말할 수 있다. 그런 다음 하루치 메시지에 같은 합계를 적용해 어느 단계가 가장 오래 걸리는지 말할 수 있다.
Ambrewick은 이 책을 위해 작성한 개인 비서 앱의 백엔드다. 사용자가 메시지를 보내면 어시스턴트는 지식 베이스, 도구, 또는 고정 응답으로 답한다. 로그에는 메시지마다 한 줄, 응답마다 한 줄이 남고 그 사이의 과정은 남지 않는다. 개발일, 즉 이 장에서 다시 재생하는 2026-12-07의 메시지 스무 개 중 가장 느렸던 것은 3271번 메시지였다. 이 메시지는 도착부터 응답까지 36,230.7 ms이 걸렸다. 809번 메시지는 이 장에서 처음으로 추적하는 메시지다. 내용은 "brew coffee at noon"이며, 도착부터 응답까지의 시간은 11,520.7 ms이다. 로그만으로는 이 시간이 경로 선택, 지식 베이스 검색, 답변 작성에 어떻게 나뉘었는지 알 수 없다. 트레이스는 그 나뉨을 시간이 측정된 단계 하나하나로 기록한다.
메시지 하나에 트레이스 하나
트레이스를 메시지 단위로 보관하는 이유는 사용자 경험에 관한 질문이 메시지를 단위로 던져지기 때문이다. 809번 메시지가 왜 느렸는지 묻는 사람에게는 그 메시지의 단계들이 한데 모여 있어야 하고, 하루의 시간이 어디에 쓰였는지 묻는 사람에게는 스무 개 메시지의 트레이스가 나란히 있어야 한다. 이벤트마다 로그 한 줄을 남기는 방식으로는 키 없이 이렇게 묶을 수 없으며, 트레이스 ID가 바로 그 키다. 한 메시지의 모든 스팬이 이 ID를 가지므로, 두 질문은 텍스트를 뒤지지 않고 각각 쿼리 하나로 해결된다.
트레이스는 사용자 메시지 하나를 처리한 작업의 기록이며, 그 메시지를 위해 만들어진 모든 스팬이 하나의 트레이스 ID를 공유한다. 스팬은 부모 링크로 이어져 트리를 이루고, 부모가 누락된 스팬도 그 트레이스에 속한다. 스팬은 이름과 시간, 속성, 부모를 가진 작업이며, 부모가 없는 루트만 예외다. 루트는 메시지 전체를 포괄하고, 어시스턴트가 거치는 각 단계는 루트 아래에서 자기만의 시작과 끝을 가진 스팬이 된다.
Agent Harnesses 책도 각 단계의 기록을 남기며, 그 기록을 트레이스라고 부른다. 그 책에서 트레이스는 한 줄에 JSON 객체 하나씩을 담은 파일이고, One line per event가 설명하듯 에이전트가 한 번 실행된 내용의 전사본이다. 이 책에서 트레이스는 OpenTelemetry의 스팬이고 메시지마다 트레이스가 하나이며, 그 트리는 부모 링크로 만들어진다. 두 책은 트레이스가 무엇을 위한 것인지에는 생각이 같지만, 형태는 다르다.
Ambrewick은 메시지 하나를 최대 다섯 단계로 처리한다. 라우트 단계는 모델을 한 번 호출해 일곱 개의 경로 중 하나를 고른다. 이 중 세 경로인 messages, devices, media는 답하기 전에 지식 베이스를 검색하며, 이 검색이 리트리브 단계다. 답변 단계는 모델을 호출해 응답을 작성한다. 답변 호출은 응답하는 대신 도구를 요청할 수 있으며, 그러면 도구 단계가 도구를 실행하고 이어지는 답변 호출이 응답을 작성한다. fallback로 라우팅된 메시지는 모델 호출 없이 고정된 응답을 받는다. 809번 메시지는 다섯 단계 중 라우트, 리트리브, 답변의 세 단계를 거친다. 이 메시지의 트레이스에는 스팬이 네 개 있으며, 이름이 message인 루트 하나와 각 단계에 해당하는 자식 하나씩이다.
메시지는 Amazon의 MASSIVE 데이터셋 1.1 버전에서 가져왔다. 영어 로케일인 en-US가 이 책의 트래픽 원천이다. 데이터셋의 한 행은 발화이고, 발화가 트래픽에 들어오면 메시지가 된다. MASSIVE의 데이터는 CC BY 4.0 라이선스이며, 데이터셋은 ACL 2023 학회 논문집에 실린 FitzGerald 외, 2023에 설명되어 있다. MASSIVE에는 52개의 로케일 파일이 있고, 그중 하나가 영어 시드다. 이 시드는 SLURP이며, Bastianelli 외, 2020이 설명하듯 크라우드 워커가 프롬프트를 보고 영어 텍스트를 작성한 음성 언어 데이터셋이다. SLURP의 텍스트 역시 CC BY 4.0이다. 크라우드 워커는 어시스턴트에게 말을 거는 사람의 어조로 이 텍스트를 데이터셋을 위해 작성했다. 이 텍스트는 어떤 실제 어시스턴트의 로그도 아니다. Ambrewick과 그 도구, 지식 베이스는 이 책이 직접 만든 것이다.
작업 규칙: 사용자 메시지마다 트레이스를 하나씩 만들고, 루트는 메시지의 전체 시간을 포괄하게 하며, 작업이 거친 단계마다 스팬을 하나씩 만든다. 여러 메시지의 실행을 한데 묶거나 일부 단계만 다루는 트레이스로는 메시지 하나에 관한 질문에 답할 수 없고, 트레이스 ID가 없는 로그 줄은 다른 로그와 연결할 수 없다.
재생과 가상 시계
메시지 809의 트레이스에는 각 단계의 시간이 필요하며, 여기서 그 시간은 시계가 아니라 녹화에서 나온다. 재생은 각 모델 호출에 녹화가 담고 있는 응답을 주고, 그 호출의 녹화된 시간과 토큰 수도 함께 준다. 여기서는 어떤 것도 모델을 기다리지 않고, 어떤 것도 측정되지 않는다. OpenTelemetry Specification, Trace API의 v1.52.0은 스팬의 타임스탬프가 연산이 실제로 걸린 시간을 반영하기를 요구한다. 따라서 이 책의 시간은 녹화된 시간을 재생한 것이며, 그렇게 하기로 선택한 것이다. 재생은 호출마다 녹화된 시간만큼 가상 시계를 전진시킨다. 시계는 UTC 기준 유닉스 에포크 이후의 나노초를 정수로 센 값이며, 메시지가 도착한 시점에서 시작한다. 재생이 끝나면 시계는 메시지가 얼마나 걸렸는지 알려 준다. 같은 녹화는 실행할 때마다 시계를 같은 양만큼 움직인다.
개발 일자는 메시지 스무 개로 이루어진 하루이며, 이 장에서 사용하는 유일한 날이다. 이 날의 각 모델 호출은 녹화 머신에서 한 번 녹화되었다. 녹화 머신은 2.10 GHz의 4-vCPU Intel Xeon이며, Q4_K_M GGUF 파일의 Qwen3-4B-Instruct-2507을 실행했다. 예제는 이 녹화를 재생한다. 각 모델 호출은 그 실행이 내놓은 응답을 녹화된 시간 및 토큰 수와 함께 받으며, 어떤 예제도 모델을 실행하지 않는다. 호스팅되는 모델은 다른 시간으로 응답한다. 아래의 방법은 그 모델에도 그대로 적용되지만, 수치는 그렇지 않다.
호출의 토큰 수는 시간이 아니므로 시계를 움직이지 않는다. 토큰 수는 녹화가 호출마다 담고 있는 속성이며, 스팬이 이를 지닌다. 캐시된 입력 토큰은 보고되는 값이 아니라 도출되는 값이다. 프롬프트 토큰에서 llama.cpp가 평가한 토큰을 뺀 값이며, llama.cpp의 성능 카운터에서 얻는다. 도출 과정은 6장에서 설명한다.
메시지 809를 재생하려면 모델 호출이 두 번 필요하며, 재생은 각 호출과 그 합계를 출력한다.
1"""Replay one dev-day message through the assistant, answering each model call from the recording, and print what each2call cost on the virtual clock. The printed times and token counts are the recording's; the point rests on the route3call and the answer call of this one message."""4from lib.dayrun import run_dev_day5from lib.report import fmt_int, fmt_ms67(run,) = run_dev_day(["809"]) # a device request: route, retrieve, answer8outcome = run.outcome910print("message text:", run.message.text)11print("route chosen:", outcome.route)12print("reply source:", outcome.source)13print("steps:", ", ".join(step.step for step in outcome.steps))14calls = [step for step in outcome.steps if step.step in ("route", "answer")] # retrieve takes no model time15for step in calls:16 print(f"{step.step} call, time:", fmt_ms(step.end_ns - step.start_ns))17 print(f"{step.step} call, input tokens:", fmt_int(step.prompt_tokens))18 print(f"{step.step} call, cached input tokens:", fmt_int(step.cached_tokens))19 print(f"{step.step} call, output tokens:", fmt_int(step.completion_tokens))20print("message, time in model calls:", fmt_ms(sum(s.end_ns - s.start_ns for s in calls)))21# The clock moved by exactly the steps' times, so the steps account for all of the message's time.22assert run.replied_ns - run.arrived_ns == sum(step.end_ns - step.start_ns for step in outcome.steps)23assert outcome.source == "model"
python replay-one-message.pymessage text: brew coffee at noon
route chosen: devices
reply source: model
steps: route, retrieve, answer
route call, time: 3,336.3 ms
route call, input tokens: 142
route call, cached input tokens: 6
route call, output tokens: 6
answer call, time: 8,184.4 ms
answer call, input tokens: 331
answer call, cached input tokens: 192
answer call, output tokens: 38
message, time in model calls: 11,520.7 ms
단계 검사가 간극을 보지 못하는 이유
+10 증명message에 기반한다. 출처는 1장 “메시지 하나에 트레이스 하나” 절이다.
trace에 기반한다. 출처는 1장 “메시지 하나에 트레이스 하나” 절이다.
이 연습이 다루던 내용이 새 판에서 바뀌었다. 2026.11.2판에서 바뀐 내용
기록에는 route 호출과 answer 호출 사이에 간극이 있었고 재생은 이를 버리는데도, 22행은 이 책의 데이터에서 통과한다. 검사는 왜 여전히 통과하는가?
작동 원리
route call, time: 3,336.3 ms
route call, input tokens: 142
route call, cached input tokens: 6
route call, output tokens: 6
answer call, time: 8,184.4 ms
answer call, input tokens: 331
answer call, cached input tokens: 192
answer call, output tokens: 38
message, time in model calls: 11,520.7 ms
라우트 호출은 3,336.3 ms이 걸리고, 답변 호출은 8,184.4 ms이 걸린다. 둘을 합하면 메시지가 모델 호출에 쓴 11,520.7 ms이 된다. 녹화에는 검색의 시간이 없으므로 재생은 검색 단계에 시간을 주지 않는다. 녹화된 실행은 라우트 호출이 끝난 뒤 답변 호출이 시작될 때까지 7.3 ms을 썼으며, 재생은 이 간격을 버린다. 시계에 대한 단언은 재생 코드만 검사한다. 시계는 단계 시간만으로 움직이므로, 녹화가 버린 간격은 찾아낼 수 없다.
작업 규칙: 녹화가 시계를 움직이게 하고, 단계의 시간을 손으로 더하지 않는다. 시계 옆에 시계의 움직임을 단계들과 대조하는 단언을 두어, 시간을 빠뜨린 단계가 실행을 실패시키도록 하고 짧은 합계로 독자에게 전달되지 않게 한다.
직접 만드는 스팬
리플레이의 단계와 시간을 확보했으므로(리플레이와 가상 시계) SDK로 스팬을 만들 수 있다. 이 장의 코드는 1.45.2 버전의 Python용 OpenTelemetry SDK를 사용한다. 스팬은 SDK의 트레이서가 만들고, 트레이서에 설정하는 두 구성 요소가 스팬이 가는 곳을 정한다. 스팬 프로세서는 각 스팬이 시작될 때와 끝날 때 호출되며, 끝날 때 스팬을 익스포터에 넘긴다. 익스포터는 스팬을 메모리, 파일, OTLP 엔드포인트 등 어딘가로 보낸다. 여기서는 스팬이 끝나는 순간 각 스팬을 내보내는 SimpleSpanProcessor를 사용한다. 반면 배치 프로세서는 타이머에 따라 나중에 묶음으로 내보내므로, 플러시 전에 출력하는 코드는 스팬을 하나도 찾지 못할 수 있고 큐가 가득 차면 스팬이 버려진다(OpenTelemetry Specification, Trace SDK, v1.52.0). 출력하는 시점에 모든 스팬이 이미 내보내져 있도록 단순 프로세서를 쓴다. 운영 환경에서는 배치 프로세서를 권장한다. 단순 프로세서는 스팬을 끝내는 스레드에서 익스포터를 호출하므로 익스포터가 느리면 요청도 느려지기 때문이다. 1.45.2에서 SimpleSpanProcessor.on_end의 SDK 소스는 그 호출을 직접 수행한다. 여기서 쓰는 익스포터는 프로세스 안의 리스트에 스팬을 보관하는 메모리 방식이다.
SDK는 스팬을 열 때 시작 시간을 취한다. start_span 호출에는 종료 시간을 받는 인자가 없으므로 종료는 별도 호출로 처리한다. lib/tracing.py의 헬퍼는 주어진 시간으로 두 가지를 모두 처리한다.
recorded = tracer.start_span(name, context=context, kind=kind, start_time=start_ns, attributes=attributes)
recorded.end(end_time=end_ns)
각 시간은 나노초 단위의 정수이며 모두 가상 시계에서 나온다. 가상 시계는 리플레이 절에서 설명한다. 여기에는 기계 자체의 시계를 읽는 코드가 없으므로, 같은 녹화는 실행할 때마다 같은 스팬을 낳는다.
종료 시간을 SDK에 맡겨도 실패하지는 않는다. 그러면 스팬은 end()가 호출된 시점의 기계 시계로 끝나는데, 그 시계는 실행마다 속도가 다르다. 그 결과 같은 메시지가 매번 다른 지속 시간을 출력하고, 그 값은 녹화와 아무 관계가 없게 된다. 헬퍼는 종료 시간을 호출자에게서 받아 이를 피하며, 시작보다 앞선 종료 시간은 음수 지속 시간이 출력되므로 거부한다.
트레이스 ID는 한 트레이스의 모든 스팬이 지니는 번호이고, 스팬 ID는 스팬 하나의 번호이다. SDK의 기본 생성기는 둘 다 무작위로 뽑으므로, lib/ids.py는 대신 1, 2, 3 순으로 세고 실행마다 다시 시작한다. 스팬의 부모는 그 스팬의 작업이 일부를 이루는 스팬이다. 스팬 컨텍스트, 주로 트레이스 ID, 스팬 ID, 트레이스 플래그는 다른 코드와 다른 프로세스가 스팬을 가리킬 수 있게 해 준다. 헬퍼는 부모 스팬을 받아 컨텍스트에 넣으므로 자식 스팬이 부모를 가리키게 된다.
리소스는 텔레메트리를 만든 대상을 설명하며, 한 트레이서 프로바이더가 만드는 모든 스팬에서 같다. service.name, service.version, service.instance.id가 그 예이다. 이 책에서 서비스는 ambrewick-assistant이고 버전은 녹화를 만든 때의 버전이다. 인스턴스 ID는 손으로 정한 고정 문자열이다. SDK의 기본값은 실행마다 새로 만들어지는 무작위 UUID이기 때문이다.
어트리뷰트는 스팬이나 리소스에 기록되는 키와 값이며 gen_ai.request.model가 그 예이다. 이 장의 어트리뷰트는 이 책 고유의 것이다. 모든 단계의 스팬은 그 스팬이 나온 단계를 알려 주는 ambrewick.step를 지닌다. 루트에는 ambrewick.step가 없고 ambrewick.route와 ambrewick.reply.source를 지니며, 그래서 트리는 루트에 (root)를 출력한다. 두 모델 호출은 ambrewick.tokens.input, ambrewick.tokens.cached, ambrewick.tokens.output도 지닌다. 스팬의 이름은 단계에 따라 route, retrieve, answer이고 루트의 이름은 message이다. 스팬 종류는 SDK의 기본값인 스팬 종류를 그대로 둔다. 이 이름들은 일부러 대충 지은 것이며, 2장에서 바꾼다.
1"""Build one dev-day message's trace by hand: a span per step, each with its explicit start and end times, from sequential2IDs, a synchronous processor and an in-memory exporter. The steps and their times come from the replay; the printed3lines rest on the span count and on every child span's parent."""4from lib.dayrun import RELEASE, run_dev_day5from lib.export import spans_to_rows6from lib.ids import SequentialIds7from lib.report import fmt_int8from lib.tracing import make_provider, span9from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1011(run,) = run_dev_day(["809"])12outcome = run.outcome1314# The resource names the service; service.instance.id is set, not drawn at random. Spans export as they end.15exporter = InMemorySpanExporter()16provider = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", run.clock, SequentialIds(),17 exporter, "https://opentelemetry.io/schemas/1.44.0")18tracer = provider.get_tracer("ambrewick.assistant")19# The root is the message. Its span is made first, and each step's span names it as parent.20root = span(tracer, "message", run.arrived_ns, run.replied_ns,21 attributes={"ambrewick.route": outcome.route, "ambrewick.reply.source": outcome.source})22for step in outcome.steps:23 name = f"tool {step.name}" if step.step == "tool" else step.step # named by step, not by the standard24 attributes = {"ambrewick.step": step.step}25 if step.step in ("route", "answer"): # model calls carry their token counts26 attributes |= {"ambrewick.tokens.input": step.prompt_tokens, "ambrewick.tokens.cached": step.cached_tokens,27 "ambrewick.tokens.output": step.completion_tokens}28 span(tracer, name, step.start_ns, step.end_ns, parent=root, attributes=attributes)2930rows = spans_to_rows(exporter) # sorted by (trace, start, span), so the order is fixed31root_row = next(row for row in rows if row["parent_span_id"] is None)32children = [row for row in rows if row["parent_span_id"] is not None]33assert len({row["trace_seq"] for row in rows}) == 1 # one message, one trace34assert all(row["parent_span_id"] == root_row["span_id"] for row in children)35print("spans in the trace:", fmt_int(len(rows)))36print("spans under the root:", fmt_int(len(children)))37route = next(row for row in children if row["name"] == "route")38print("route span, input tokens on the span:", fmt_int(route["attributes"]["ambrewick.tokens.input"]))
python build-one-trace.pyspans in the trace: 4
spans under the root: 3
route span, input tokens on the span: 142
809번 메시지의 스팬 네 개는 이 호출들에서 나온다. 각 자식은 루트를 부모로 삼아 한 줄로 만들어진다.
span(tracer, name, step.start_ns, step.end_ns, parent=root, attributes=attributes)
이어서 스크립트는 네 스팬이 모두 같은 트레이스 ID를 공유하는지, 그리고 모든 자식이 루트를 부모로 가리키는지 검증한다. 출력은 트레이스에 스팬이 4개 있고 그중 3개가 루트 아래에 있다고 보고하며, route 스팬의 입력 토큰은 142이다.
운영 환경에서 생기는 문제는 틀린 숫자보다 눈에 덜 띈다. 단순 프로세서는 스팬이 끝나자마자 익스포터에 넘기므로, 명세의 SDK 페이지가 말하듯 스팬은 끝날 때에만 내보내진다. 따라서 작업이 end() 호출에 이르지 못한 스팬은 아예 내보내지지 않는다. 실제 코드에서 루트는 메시지 전체를 감싸므로 가장 마지막에 끝나고, 메시지 처리 도중 프로세스가 죽으면 루트와 그때 실행 중이던 단계를 잃는다. 그러면 트레이스는 부모가 끝내 도착하지 않는, 끝난 단계들로 도착하며, 배치 프로세서를 쓰면 큐에 남아 있던 스팬도 함께 사라진다. 예제가 루트를 먼저 끝내는 것은 리플레이 이후에 스팬을 만들기 때문일 뿐이며, 실제 코드는 그렇게 하지 않는다. 부모가 없는 스팬이 정확히 하나인지 찾는 검사가 이런 트레이스를 잡아낸다.
작업 규칙: 리플레이에서는 모든 스팬을 리플레이 시계의 명시적 종료 시간으로 끝낸다. 실제 코드에서는 SDK가 두 시간을 모두 기계 시계에서 취하게 둔다. 어느 쪽이든 각 트레이스에 루트, 즉 부모가 없는 스팬이 정확히 하나 있는지 확인한다. 루트가 없는 트레이스는 프로세스가 비정상 종료될 때 남는 흔적이며, 실패가 아니라 짧은 단계 몇 개로 보이기 때문이다.
트레이스 하나의 트리
직접 만든 스팬에서 메시지 809를 위해 만든 네 개의 스팬은 부모 링크로 트리를 이룬다. 스크립트는 이어서 이 스팬들의 시간이 어떻게 합산되는지 검사한다. 트리에는 루트와 그 아래 세 단계가 나열되고, 그 뒤의 줄들에는 각 단계의 시간과 검사 결과가 나온다.
1"""Print one dev-day message's trace as a tree, with each span's step, then check how its times add up. The spans are the2ones build-one-trace makes. The steps run one after another, so none overlap and the message's time is their sum. Where3spans do overlap, a parent's duration is not the sum of its children's; this trace shows no overlap."""4from lib.dayrun import RELEASE, run_dev_day5from lib.export import spans_to_rows6from lib.ids import SequentialIds7from lib.report import fmt_ms8from lib.tracing import make_provider, span9from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1011(run,) = run_dev_day(["809"])12outcome = run.outcome1314exporter = InMemorySpanExporter()15provider = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", run.clock, SequentialIds(),16 exporter, "https://opentelemetry.io/schemas/1.44.0")17tracer = provider.get_tracer("ambrewick.assistant")18root = span(tracer, "message", run.arrived_ns, run.replied_ns,19 attributes={"ambrewick.route": outcome.route, "ambrewick.reply.source": outcome.source})20for step in outcome.steps:21 name = f"tool {step.name}" if step.step == "tool" else step.step22 span(tracer, name, step.start_ns, step.end_ns, parent=root, attributes={"ambrewick.step": step.step})2324rows = spans_to_rows(exporter)25root_row = next(row for row in rows if row["parent_span_id"] is None)26children = [row for row in rows if row["parent_span_id"] is not None]272829def print_tree(row, depth):30 """Print a span, then its children one level further in. Shows the shape of the trace, not its times."""31 print(" " * depth + f"{row['name']} step: {row['attributes'].get('ambrewick.step', '(root)')}")32 for child in (r for r in rows if r["parent_span_id"] == row["span_id"]):33 print_tree(child, depth + 1)343536print_tree(root_row, 0)37# Sorted by start, two steps overlap exactly when a step starts before the one before it has ended.38ordered = sorted(children, key=lambda row: row["start_ns"])39overlap = any(later["start_ns"] < earlier["end_ns"] for earlier, later in zip(ordered, ordered[1:]))40root_time = root_row["end_ns"] - root_row["start_ns"]41steps_time = sum(row["end_ns"] - row["start_ns"] for row in children)42print("message span, time:", fmt_ms(root_time))43print("steps, time added up:", fmt_ms(steps_time))44print("steps overlap in time:", "yes" if overlap else "no")45print("message time equals the sum of its steps:", "yes" if root_time == steps_time else "no")46assert not overlap and root_time == steps_time
python print-trace-tree.pymessage step: (root)
route step: route
retrieve step: retrieve
answer step: answer
message span, time: 11,520.7 ms
steps, time added up: 11,520.7 ms
steps overlap in time: no
message time equals the sum of its steps: yes
메시지 시간이 각 단계의 시간과 일치하는 이유
+10 증명트레이스 하나의 트리의 1장에서다시 읽는다
이 연습이 다루던 내용이 새 판에서 바뀌었다. 2026.11.2판에서 바뀐 내용
45번째 줄은 메시지 시간과 각 단계의 시간을 비교하여 yes를 출력한다. 이 재생(replay)에서 성립하는 설명은 무엇인가?
작동 원리
message step: (root)
route step: route
retrieve step: retrieve
answer step: answer
message span, time: 11,520.7 ms
steps, time added up: 11,520.7 ms
steps overlap in time: no
message time equals the sum of its steps: yes
들여쓰기가 부모 링크를 나타내므로, 메시지 809의 세 단계는 루트보다 한 수준 아래에 놓인다. OpenTelemetry Specification은 트레이스를 스팬의 방향 비순환 그래프라고 부르는데, 부모 링크가 있으면 스팬마다 부모가 하나이므로 이 그래프는 트리가 된다. 트리에는 시간이 나오지 않으므로 시간은 다음 줄들에서 얻는다.
자식 스팬은 부모보다 늦게 끝날 수 있다. 사양의 개요에는 그런 경우를 그린 그림이 있으며, 이를 금지하는 규칙은 없다(OpenTelemetry Specification, Overview: Traces, Spans, SpanContext, 태그 v1.52.0). 따라서 자식 스팬이 서로 겹치면 부모의 지속 시간은 자식들의 합과 같지 않고, 자식 사이에 빈틈이 있어도 합과 다를 수 있다. 이번 재현에서 메시지 809의 단계들은 겹치지도 않고 빈틈도 없다. 경로가 끝나는 시점에 답변이 시작된다. 스크립트가 이를 검사하며, 출력은 메시지의 시간을 11,520.7 ms, 단계들의 시간을 11,520.7 ms로 내놓는다. 두 값은 같은 수이다.
독자는 부모의 막대를 자식들이 한 작업으로 읽고 싶어지기 쉽다. 막대는 부모가 언제 시작하고 멈췄는지만 보여 주며, 빈틈은 어떤 자식도 기록하지 않은 작업이다. 이번 재현에는 두 경우 모두 없다.
그림 1.1은 같은 트레이스를 워터폴로 그린 것이다. 시간 축 위에 스팬마다 막대 하나를 놓은 워터폴은 트레이싱 도구가 그리는 보기이며, 사양의 개요에도 스케치가 있다. 다만 사양은 이를 형식으로 정의하지 않으며, 이 그림은 이 책이 직접 그린 것이다. 그림에는 스팬마다 막대가 하나씩 있고, 막대는 스팬의 시작부터 끝까지를 메시지가 도착한 뒤의 초 단위로 나타낸다. 맨 위에는 메시지 전체의 막대가 있고, 그 아래에 도착 시점부터 시작하는 경로 막대, 경로가 끝나는 지점의 눈금으로 표시한 검색 단계, 그 지점부터 메시지 끝까지 이어지는 더 긴 답변 막대가 있다.
1"""Draw one dev-day message's trace as a waterfall: each span a bar from its start to its end, after the message arrives.2The bars are the spans of build-one-trace, from the replay's recorded times, so the figure shows the order and length of3the steps. The printed lines are the values the figure's text quotes."""4from lib.dayrun import run_dev_day5from lib.figures import ACCENT, INK, MUTED, new_figure, save6from lib.report import fmt_ms78(run,) = run_dev_day(["809"])9outcome, arrived = run.outcome, run.arrived_ns1011# One bar per span: the message first, then its steps in order. The answer is the accent; the route is ink.12bars = [("message", arrived, run.replied_ns, MUTED)]13bars += [(s.step, s.start_ns, s.end_ns, ACCENT if s.step == "answer" else INK) for s in outcome.steps]14fig, ax = new_figure(height=2.4)15for row, (label, start, end, colour) in enumerate(bars):16 left, width = (start - arrived) / 1e9, (end - start) / 1e9 # seconds after arrival17 if width > 0:18 ax.barh(row, width, left=left, height=0.6, color=colour)19 else: # a step with no time is a tick, not a bar20 ax.plot([left], [row], marker="|", markersize=10, color=colour)21ax.set_yticks(range(len(bars)), [label for label, _, _, _ in bars])22ax.invert_yaxis()23ax.set_xlabel("seconds after the message arrives")24save(fig, "dev-day-waterfall")2526steps = {s.step: s for s in outcome.steps} # one span per step in this message27route, answer = steps["route"], steps["answer"]28print("message, time from arrival to reply:", fmt_ms(run.replied_ns - arrived))29print("route span, time:", fmt_ms(route.end_ns - route.start_ns))30print("retrieve span, time:", fmt_ms(steps["retrieve"].end_ns - steps["retrieve"].start_ns))31print("answer span, time:", fmt_ms(answer.end_ns - answer.start_ns))32print("answer span starts, after arrival:", fmt_ms(answer.start_ns - arrived))33# The steps run one after another: the answer starts exactly when the route ends, so the bars do not overlap.34assert answer.start_ns == route.end_ns
python figure-dev-day-waterfall.pyfigure: figures/dev-day-waterfall.svg
message, time from arrival to reply: 11,520.7 ms
route span, time: 3,336.3 ms
retrieve span, time: 0.0 ms
answer span, time: 8,184.4 ms
answer span starts, after arrival: 3,336.3 ms
답변 스팬은 도착 후 3,336.3 ms에 시작하며, 이때가 경로가 끝나는 시점이다. 그림의 순서는 단계가 실행된 순서이고, 길이는 시계가 기록한 시간이다.
작업 규칙: 트레이스를 부모 링크의 트리로 출력하고, 자식들의 시간을 합하기 전에 자식들이 겹치지 않고 빈틈도 없는지 확인한다. 겹치거나 빈틈이 있으면 부모의 시간과 자식들의 시간을 따로 보고한다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Where the time went in twenty messages
Message 809 is one trace, and the dev day is twenty of them. One message, one trace keeps each message's steps together, so the day's steps can be added up. A fallback reply is the fixed text Ambrewick sends when the router chooses fallback; no model writes it, and its span says so. On the dev day, 6 of 20 messages got one. A fallback reply is the right answer only for a message that no tool or article can resolve.
1"""Replay all 20 dev-day messages and add up each model step over the day: its calls, its recorded time, its tokens, and its2share of the day's model time and tokens. Tool time is not in the recording (the tools are modelled), so it is counted3and left out of the shares; retrieve and fallback take no time. The route-to-answer gap is the recorder's, not the replay's."""4from collections import Counter5from lib.dayrun import recorded_gap_ns, run_dev_day6from lib.report import fmt_int, fmt_ms, fmt_share78MODEL_STEPS = ("route", "answer")9runs = run_dev_day() # all 20 messages, in arrival order10calls, time_ns, tokens = Counter(), Counter(), Counter()11cached, overlapping, fallbacks = Counter(), 0, 012for run in runs:13 ordered = sorted(run.outcome.steps, key=lambda s: s.start_ns)14 overlapping += any(later.start_ns < earlier.end_ns for earlier, later in zip(ordered, ordered[1:]))15 fallbacks += run.outcome.source == "fallback"16 for step in run.outcome.steps:17 calls[step.step] += 118 if step.step in MODEL_STEPS: # the recording's times and tokens; input counts cached tokens too19 time_ns[step.step] += step.end_ns - step.start_ns20 tokens[step.step] += step.prompt_tokens + step.completion_tokens21 cached[step.step] += step.cached_tokens22 tokens[f"{step.step} input"] += step.prompt_tokens2324slowest = max(runs, key=lambda run: run.replied_ns - run.arrived_ns) # the first of the slowest, if two tie25total_time, total_tokens = sum(time_ns[s] for s in MODEL_STEPS), sum(tokens[s] for s in MODEL_STEPS)26input_total = sum(tokens[f"{s} input"] for s in MODEL_STEPS)27print("messages in the dev day:", fmt_int(len(runs)))28print("messages whose steps overlap in time:", f"{overlapping} of {len(runs)}")29print("messages answered by the fallback reply:", f"{fallbacks} of {len(runs)}")30print("slowest message:", slowest.message.message_id)31print("slowest message time:", fmt_ms(slowest.replied_ns - slowest.arrived_ns))32print("slowest message route:", slowest.outcome.route)33for step in MODEL_STEPS:34 print(f"{step} calls:", fmt_int(calls[step]))35 print(f"{step}, recorded time:", fmt_ms(time_ns[step]))36 print(f"{step}, share of model time:", fmt_share(time_ns[step], total_time))37 print(f"{step}, share of tokens (input plus output):", fmt_share(tokens[step], total_tokens))38print("tool calls:", fmt_int(calls["tool"]))39print("retrieve calls:", fmt_int(calls["retrieve"]))40print("route to answer gap, message 809:", fmt_ms(recorded_gap_ns("809", "route", "answer")))41print("input tokens, total:", fmt_int(input_total))42print("cached input tokens, total:", fmt_int(sum(cached[s] for s in MODEL_STEPS)))43print("output tokens, total:", fmt_int(total_tokens - input_total))44assert calls["route"] == len(runs) # every message is routed once45assert overlapping == 0 # the steps never overlap in the replay
python sum-dev-day-steps.pymessages in the dev day: 20
messages whose steps overlap in time: 0 of 20
messages answered by the fallback reply: 6 of 20
slowest message: 3271
slowest message time: 36,230.7 ms
slowest message route: alarms
route calls: 20
route, recorded time: 35,500.6 ms
route, share of model time: 16.7%
route, share of tokens (input plus output): 21.2%
answer calls: 17
answer, recorded time: 176,519.9 ms
answer, share of model time: 83.3%
answer, share of tokens (input plus output): 78.8%
tool calls: 3
retrieve calls: 8
route to answer gap, message 809: 7.3 ms
input tokens, total: 13,417
cached input tokens, total: 8,299
output tokens, total: 775
각 모델 단계의 입력 토큰과 출력 토큰 세기
+10 증명Where the time went in twenty messages의 1장에서다시 읽는다
이 연습이 다루던 내용이 새 판에서 바뀌었다. 2026.11.2판에서 바뀐 내용
20행은 각 모델 호출이 쓴 내용만 더하므로, 토큰 비중에서 그날의 입력이 빠진다. 각 모델 단계의 토큰이 입력과 출력의 합이 되도록 20행을 고친다.
작동 원리
The script replays all twenty messages, one after another, and adds up each model step over the day. The day's tool calls went to the in-process tools, the calendar, alarm and list tools, whose durations are modelled from a table in the book's configuration, not recorded, so the shares leave them out and count them only as calls. Retrieve takes no recorded time either. The script also counts the messages whose steps overlap in time, and the count is 0 of 20. So the day's sums are sums of step times, and they are not splits of each message's root time.
The answer step holds most of the day's model time, 83.3%, while the route step holds 21.2% of the tokens against 16.7% of the time. Answer calls outnumber the messages a model answered, because each message that called a tool needed a further answer call after the tool returned, so the answer step ran 17 times. The shares are over the day's model time and its tokens, input plus output, and the output prints both totals.
그림 1.2 draws the two shares for each model step. Time and tokens do not share a shape, as the figure shows.
1"""Draw each model step's share of the dev day's model time, beside its share of the tokens (input plus output), over all220 messages. Each bar is labelled with the share the example prints, so the figure and the printed lines are one set of3numbers. Tool time is not in the recording, so the tool step is not drawn."""4from collections import Counter5from lib.dayrun import run_dev_day6from lib.figures import ACCENT, INK, new_figure, save7from lib.report import fmt_int, fmt_ms, fmt_share89MODEL_STEPS = ("route", "answer")10runs = run_dev_day()11calls, time_ns, tokens = Counter(), Counter(), Counter()12for run in runs:13 for step in (s for s in run.outcome.steps if s.step in MODEL_STEPS):14 calls[step.step] += 115 time_ns[step.step] += step.end_ns - step.start_ns16 tokens[step.step] += step.prompt_tokens + step.completion_tokens # input plus output1718total_time, total_tokens = sum(time_ns.values()), sum(tokens.values())19time_labels = [fmt_share(time_ns[s], total_time) for s in MODEL_STEPS]20token_labels = [fmt_share(tokens[s], total_tokens) for s in MODEL_STEPS]21fig, ax = new_figure(height=2.6)22positions = list(range(len(MODEL_STEPS)))23time_bars = ax.bar([p - 0.2 for p in positions], [100 * time_ns[s] / total_time for s in MODEL_STEPS], width=0.4,24 color=ACCENT, label="share of model time")25token_bars = ax.bar([p + 0.2 for p in positions], [100 * tokens[s] / total_tokens for s in MODEL_STEPS], width=0.4,26 color=INK, label="share of tokens")27ax.bar_label(time_bars, labels=time_labels, padding=2)28ax.bar_label(token_bars, labels=token_labels, padding=2)29ax.set_xticks(positions, list(MODEL_STEPS))30ax.set_ylim(0, 100)31ax.set_ylabel("percent of the dev day")32ax.legend(loc="upper left") # the route bars reach only about 21 percent, so the top left is clear of labels33save(fig, "dev-day-step-shares")3435print("messages in the dev day:", fmt_int(len(runs)))36for step, time_label, token_label in zip(MODEL_STEPS, time_labels, token_labels):37 print(f"{step} calls:", fmt_int(calls[step]))38 print(f"{step}, recorded time:", fmt_ms(time_ns[step]))39 print(f"{step}, share of model time:", time_label)40 print(f"{step}, tokens, input plus output:", fmt_int(tokens[step]))41 print(f"{step}, share of tokens:", token_label)42print("model time, total:", fmt_ms(total_time))43print("tokens, input plus output, total:", fmt_int(total_tokens))44assert sum(calls.values()) == 37 # 20 route calls and 17 answer calls, as the recording holds
python figure-dev-day-step-shares.pyfigure: figures/dev-day-step-shares.svg
messages in the dev day: 20
route calls: 20
route, recorded time: 35,500.6 ms
route, share of model time: 16.7%
route, tokens, input plus output: 3,003
route, share of tokens: 21.2%
answer calls: 17
answer, recorded time: 176,519.9 ms
answer, share of model time: 83.3%
answer, tokens, input plus output: 11,189
answer, share of tokens: 78.8%
model time, total: 212,020.5 ms
tokens, input plus output, total: 14,192
A step's share of time says where the day's waiting went, and its share of tokens says where the day's input and output came from. The two are different questions, and this chapter answers both; which step costs the most money is chapter 6's question, and it needs the prices as well as the tokens.
Working rule: Sum each step's recorded time and tokens over the messages, and print each share beside its denominator. Name any step whose time is not recorded and leave it out of the shares, so that a reader can see which part of the day the sums do not cover.
이 버전이 아직 하지 못하는 것
이 버전은 거칠게 만든 것이며, 각 부분은 이를 견고하게 만드는 뒤의 장이 따로 있다. 순서대로 보면 다음과 같다.
- 이름. 스팬의 이름은 이 책이 정한 단계에 따라 붙인다. 2장에서는 각 스팬에 표준이 정한 이름을 붙이고, 종류를 설정하고, 검증기로 확인한다. 여기의 스팬은 모두 이 검증을 통과하지 못한다.
- 모델 호출. 스팬은 직접 만든다. 3장에서는 같은 종류의 호출에 대해
openai클라이언트 라이브러리의 공식 계측이 무엇을 내보내는지 보여 준다. - 두 번째 프로세스. 이 트레이스는 한 프로세스의 기록이다. 4장에서는 별도의 프로세스로 실행되는 연락처 팀 서버의 스팬을 이 트레이스에 연결한다.
- 저장. 스팬은 메모리에만 있으며 프로세스가 끝나면 사라진다. 5장에서는 스팬을 저장하는 백엔드로 스팬을 보낸다.
- 꼬리. 메시지 스무 개로는 꼬리 백분위수를 확신할 수 있게 구할 수 없다. 7장에서는 백분위수를 건수와 구간과 함께 제시한다.
- 샘플링. 모든 트레이스를 보관한다. 11장에서는 어떤 트레이스를 보관할지와 그 이유를 정한다.
- 프롬프트. 스팬에는 프롬프트 텍스트를 일부러 담지 않았다. 3장에서는 프롬프트를 기록하게 하는 스위치를 소개하고, 12장에서는 그 스위치가 무엇을 유출하는지 다룬다.
- 잘못된 경로. 개발자의 날 메시지 6 of 20개가 대체 응답을 받았으며, 이 장은 각 경로가 올바랐는지 확인하지 않는다. 8장에서 확인한다.
이 장에서 내린 결정
이 결정들은 이 책의 나머지 부분을 규정한다.
- 스팬의 이름은 당분간 단계별로 붙인다. 2장부터는 책이 표준의 이름을 사용한다.
- 각 소요 시간은 기록된 값이며 실시간으로 측정한 값이 아니다. 따라서 출력되는 모든 시간은 다시 실행하여 대조할 수 있다.
- 스팬은 끝나는 순간에 동기 프로세서가 내보낸다. 그래야 모든 스팬이 출력되는 시점에 이미 내보내진 상태가 된다.
- 비율은 분모와 함께 출력하며, 시간이 기록되지 않은 단계는 추정하지 않고 비율에서 제외한다.
- 각 트레이스는 메시지 하나의 것이며, 하루 동안의 합계는 기록에 있는 메시지별 단계를 그대로 더한 값이다. 스팬으로부터 만든 다른 척도는 쓰지 않는다.
작업 규칙: 메시지 하나에 대한 질문에는 그 메시지의 트레이스만으로 답한다. 메시지의 모든 스팬은 같은 트레이스 ID를 공유하고 루트가 메시지의 전체 시간을 포괄하므로, 트레이스에는 그 메시지의 단계만 있고 다른 메시지의 단계는 없다. ID가 없는 스팬이나 로그 줄은 답에 넣을 자리를 정할 수 없으므로, 어느 메시지의 것인지 추측하지 말고 제외하고 그 사실을 밝힌다. 추측하면 한 메시지의 시간이 다른 메시지의 합계에 들어가게 된다.
이 판의 이 장
2026.11.2판예제 통과 2026년 11월 236 of 6개 예제 in this chapter pass
영어판 2026.11.2판을 번역한 것이다.