リクエストをトレースし、時間の行き先を問う

読了まで約32 分。7 節に6 例を収録。

第2026.11.2版 2026年11月23日時点で例が通過 80 例中 80 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.2)から翻訳した。 原文を読む

Labs

この章を実際に手を動かして学ぶ

すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。約 30 秒で開く。

すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。Labs が実行環境を用意する: 月40 時間。

Labで開く、新しいタブで開く

利用時間を確認しています…

Lab を確認しています…

自分のマシンで、無料: 書籍のノートブックをダウンロード、そのコードとデータを GitHub から取得する。

この章を終えると、1件のメッセージのトレースを手作業で組み立て、ツリーとして表示し、その時間とトークンがどこで使われたかを説明できるようになる。さらに、1日分のメッセージについても同じ集計を行い、どのステップが最も時間を要するかを答えられるようになる。

Ambrewick は、本書のために書かれたパーソナルアシスタントアプリのバックエンドである。ユーザーがメッセージを送ると、アシスタントはナレッジベース、ツール、または定型の返信のいずれかで応答する。ログには、メッセージごとに1行、返信ごとに1行が残るだけで、その間のことは何も記録されない。この章で再現する開発日、すなわち 2026-12-07 の20件のメッセージのうち、最も遅かったのはメッセージ 3271 であった。到着から返信まで 36,230.7 ms を要している。メッセージ 809 は、この章で最初にトレースするメッセージである。その内容は「brew coffee at noon」であり、到着から返信までの時間は 11,520.7 ms である。この時間が、経路の選択、ナレッジベースの検索、回答の作成にどう配分されたかは、ログからは分からない。トレースは、その配分を1つの時間計測されたステップごとに記録する。

1メッセージにつき1トレース

トレースをメッセージ単位で保持するのは、ユーザーの体験に関する問いがその単位で発せられるからである。メッセージ809がなぜ遅かったのかを知りたい人には、そのメッセージのステップがひとまとまりになっている必要がある。1日の時間がどこで費やされたのかを知りたい人には、20件すべてのメッセージのトレースを並べて見る必要がある。イベントごとに1行のログは、キーがなければこのようにグループ化できない。そのキーがトレースIDである。1つのメッセージのすべてのスパンがトレースIDを持つので、2つの問いはそれぞれ1回のクエリで済み、テキストを検索する必要はない。

トレースとは、1つのユーザーメッセージのために行われた作業の記録であり、そのために作られたすべてのスパンが1つのトレースIDを共有する。スパン同士は親リンクによって木構造につながり、親が欠けているスパンもそのトレースに属する。スパンとは、名前と所要時間を持ち、属性と親を備えた操作である。ただしルートには親がない。ルートはメッセージ全体を覆い、アシスタントが行う各ステップはその下のスパンとなり、それぞれ開始と終了を持つ。

Agent Harnessesの本もステップごとの記録を残しており、その記録をトレースと呼んでいる。そこでのトレースは、One line per eventが説明するとおり、1行に1つのJSONオブジェクトを持つファイルであり、エージェントの1回の実行の記録である。本書でのトレースはOpenTelemetryのスパンであり、1メッセージにつき1トレースで、その木は親リンクでできている。トレースの目的については2冊の本は一致しているが、形式は異なる。

Ambrewickは1つのメッセージを最大5つのステップで処理する。routeステップでは、モデルを1回呼び出して7つの経路から1つを選ぶ。経路のうちmessages、devices、mediaの3つは、回答の前にナレッジベースを検索し、その検索がretrieveステップである。answerステップでは、モデルを呼び出して返信を書く。answerの呼び出しは、返信する代わりにツールを要求することがある。その場合はtoolステップがツールを実行し、さらにanswerの呼び出しが返信を書く。fallbackにルーティングされたメッセージには、モデルを呼び出さずに固定の返信が返される。メッセージ809は5つのステップのうち、route、retrieve、answerの3つを実行する。そのトレースには4つのスパンがあり、messageという名前のルートと、各ステップに1つずつの子である。

メッセージはAmazonのMASSIVEデータセットのバージョン1.1から取っている。その英語ロケールであるen-USが、本書のトラフィックの出どころである。データセットの1行は発話であり、発話はトラフィックに入った時点でメッセージとなる。MASSIVEのデータはCC BY 4.0でライセンスされており、データセットはACL 2023のProceedingsに掲載されたFitzGeraldら、2023に記述されている。MASSIVEには52のロケールファイルがあり、そのうち1つが英語のシードである。そのシードはSLURPであり、Bastianelliら、2020が述べるとおり、クラウドワーカーがプロンプトから英語のテキストを書いた音声言語データセットである。SLURPのテキストもCC BY 4.0である。クラウドワーカーは、アシスタントに話しかける人の口調で、データセットのためにこれらのテキストを書いた。これらは実在するアシスタントのログではない。Ambrewick、そのツール、そしてナレッジベースは、本書独自のものである。

実践ルール: ユーザーメッセージ1件につき1つのトレースを作り、メッセージの全所要時間を覆うルートと、その作業が通った各ステップに1つずつのスパンを持たせる。複数のメッセージの連なりや一部のステップだけを覆うトレースは、1つのメッセージに関する問いに答えられない。また、トレースIDを欠くログ行は、他のログ行と結び付けることができない。

リプレイと仮想クロック

メッセージ 809 のトレースには各ステップの時刻が必要であるが、ここでの時刻は時計から得たものではなく、記録から得たものである。リプレイは、各モデル呼び出しに、記録が保持する応答を、その呼び出しの記録された時間およびトークン数とともに与える。ここではモデルを待つことはなく、何も計測しない。OpenTelemetry Specification, Trace API(v1.52.0)は、スパンのタイムスタンプが操作に実際に経過した時間を反映することを求めている。したがって本書の時間は、記録のものをリプレイしたものであり、これは意図的な選択である。リプレイは、各呼び出しの記録された時間だけ仮想クロックを進める。クロックは UTC の Unix エポックからの経過ナノ秒を表す整数であり、メッセージの到着時刻から始まる。リプレイが終わると、クロックはそのメッセージにかかった時間を示す。同じ記録は、実行のたびに同じ量だけクロックを進める。

開発日は 20 件のメッセージからなる 1 日分であり、本章で使うのはこの日だけである。この日の各モデル呼び出しは、記録用マシン上で一度だけ記録された。このマシンは 2.10 GHz の 4 vCPU Intel Xeon で、Qwen3-4B-Instruct-2507 を Q4_K_M の GGUF ファイルで実行した。各例はこの記録をリプレイする。各モデル呼び出しには、その実行が返した応答が、記録された時間とトークン数とともに与えられ、どの例もモデルを実行しない。ホスト型モデルの応答時間は異なる。以下の方法はそのまま当てはまるが、数値は当てはまらない。

呼び出しのトークン数は時間ではないため、クロックを進めない。トークン数は、記録が各呼び出しについて保持する属性であり、スパンが持つ。キャッシュされた入力トークンは報告された値ではなく導出した値であり、プロンプトトークン数から、llama.cpp がそのパフォーマンスカウンターで報告する評価済みトークン数を引いたものである。導出方法は第 6 章で説明する。

メッセージ 809 のリプレイにはモデル呼び出しが 2 回あり、リプレイはそれぞれと合計を出力する。

replay-one-message.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 one dev-day message through the assistant, answering each model call from the recording, and print what eachcall cost on the virtual clock. The printed times and token counts are the recording's; the point rests on the routecall and the answer call of this one message."""from lib.dayrun import run_dev_dayfrom lib.report import fmt_int, fmt_ms(run,) = run_dev_day(["809"])                          # a device request: route, retrieve, answeroutcome = run.outcomeprint("message text:", run.message.text)print("route chosen:", outcome.route)print("reply source:", outcome.source)print("steps:", ", ".join(step.step for step in outcome.steps))calls = [step for step in outcome.steps if step.step in ("route", "answer")]   # retrieve takes no model timefor step in calls:    print(f"{step.step} call, time:", fmt_ms(step.end_ns - step.start_ns))    print(f"{step.step} call, input tokens:", fmt_int(step.prompt_tokens))    print(f"{step.step} call, cached input tokens:", fmt_int(step.cached_tokens))    print(f"{step.step} call, output tokens:", fmt_int(step.completion_tokens))print("message, time in model calls:", fmt_ms(sum(s.end_ns - s.start_ns for s in calls)))# The clock moved by exactly the steps' times, so the steps account for all of the message's time.assert run.replied_ns - run.arrived_ns == sum(step.end_ns - step.start_ns for step in outcome.steps)assert outcome.source == "model"
出力python replay-one-message.py
message 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
演習 1.1

ステップ検査が欠落を検出できない理由

+10 件の検証

22行目の検査は、記録に route 呼び出しと answer 呼び出しの間の欠落があり、リプレイがそれを取り除いているにもかかわらず、本書のデータでは成功する。それでもこの検査が成功するのはなぜか。

ステップ検査が欠落を検出できない理由:正しい説明を選ぶ
Python 3.13.16 で実行される
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 が、このメッセージがモデル呼び出しに費やした時間である。記録には検索の時間が含まれていないため、リプレイは retrieve ステップに時間を与えない。記録された実行では、ルート呼び出しの終了から回答呼び出しの開始までに 7.3 ms が費やされており、リプレイはこの間隔を落とす。クロックに対するアサーションが検査するのはリプレイのコードだけである。クロックはステップの時間だけで進むため、記録が落とした間隔は見つけられない。

実践ルール: クロックは記録に進めさせ、ステップの時間を手作業で足してはならない。クロックの隣に、その動きをステップと照合するアサーションを置く。そうすれば、時間を落としたステップは実行時に失敗し、短い合計として読者の目に触れることはない。

スパンを手作業で作る

リプレイのステップと時刻が手元にそろえば(リプレイと仮想クロック)、SDK でスパンを作れる。この章のコードは、1.45.2 の Python 向け OpenTelemetry SDK を用いる。スパンを作るのは SDK のトレーサーであり、スパンの送り先は、トレーサーに設定する二つの部品が決める。スパンプロセッサは、各スパンの開始時と終了時に呼び出され、終了時にはスパンをエクスポーターに渡す。エクスポーターはスパンをメモリ、ファイル、OTLP エンドポイントなどへ送る。ここでは SimpleSpanProcessor を用いる。これは、各スパンが終了した時点でそのスパンをエクスポートする。これに対してバッチプロセッサは、タイマーに従って後からまとめてエクスポートする。そのため、フラッシュの前に出力するコードではスパンが一つも見つからないことがあり、キューが満杯になるとスパンは破棄される(OpenTelemetry Specification, Trace SDK、v1.52.0)。ここでシンプルプロセッサを使うのは、出力する時点ですべてのスパンがエクスポート済みになるようにするためである。本番ではバッチプロセッサを推奨する。シンプルプロセッサは、スパンを終了させたスレッド上でエクスポーターを呼び出すため、エクスポーターが遅いとリクエストも遅くなるからである。1.45.2 にある SDK のソースでは、SimpleSpanProcessor.on_end がこの呼び出しを直接行っている。ここでのエクスポーターはインメモリのもので、プロセス内のリストにスパンを保持する。

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 章で置き換える。

build-one-trace.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 合格
"""Build one dev-day message's trace by hand: a span per step, each with its explicit start and end times, from sequentialIDs, a synchronous processor and an in-memory exporter. The steps and their times come from the replay; the printedlines rest on the span count and on every child span's parent."""from lib.dayrun import RELEASE, run_dev_dayfrom lib.export import spans_to_rowsfrom lib.ids import SequentialIdsfrom lib.report import fmt_intfrom lib.tracing import make_provider, spanfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter(run,) = run_dev_day(["809"])outcome = run.outcome# The resource names the service; service.instance.id is set, not drawn at random. Spans export as they end.exporter = InMemorySpanExporter()provider = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", run.clock, SequentialIds(),                         exporter, "https://opentelemetry.io/schemas/1.44.0")tracer = provider.get_tracer("ambrewick.assistant")# The root is the message. Its span is made first, and each step's span names it as parent.root = span(tracer, "message", run.arrived_ns, run.replied_ns,            attributes={"ambrewick.route": outcome.route, "ambrewick.reply.source": outcome.source})for step in outcome.steps:    name = f"tool {step.name}" if step.step == "tool" else step.step      # named by step, not by the standard    attributes = {"ambrewick.step": step.step}    if step.step in ("route", "answer"):                                  # model calls carry their token counts        attributes |= {"ambrewick.tokens.input": step.prompt_tokens, "ambrewick.tokens.cached": step.cached_tokens,                       "ambrewick.tokens.output": step.completion_tokens}    span(tracer, name, step.start_ns, step.end_ns, parent=root, attributes=attributes)rows = spans_to_rows(exporter)                 # sorted by (trace, start, span), so the order is fixedroot_row = next(row for row in rows if row["parent_span_id"] is None)children = [row for row in rows if row["parent_span_id"] is not None]assert len({row["trace_seq"] for row in rows}) == 1                       # one message, one traceassert all(row["parent_span_id"] == root_row["span_id"] for row in children)print("spans in the trace:", fmt_int(len(rows)))print("spans under the root:", fmt_int(len(children)))route = next(row for row in children if row["name"] == "route")print("route span, input tokens on the span:", fmt_int(route["attributes"]["ambrewick.tokens.input"]))
出力python build-one-trace.py
spans in the trace: 4
spans under the root: 3
route span, input tokens on the span: 142

メッセージ 809 の四つのスパンは、これらの呼び出しから作られる。各子スパンは、次の 1 行でルートを親として作られる。

span(tracer, name, step.start_ns, step.end_ns, parent=root, attributes=attributes)

続いてスクリプトは、四つのスパンがすべて同じトレース ID を共有していること、およびすべての子がルートを親として指名していることを検証する。出力は、トレース内のスパン数 4、そのうちルートの下にあるもの 3、そして route スパン上の入力トークンが 142 であることを報告する。

本番で起こる問題は、誤った数値よりも気づきにくい。スパンは終了したときにのみエクスポートされる。仕様の SDK のページにあるとおり、シンプルプロセッサは各スパンが終わるとすぐにエクスポーターへ渡すため、作業が end() の呼び出しに到達しなかったスパンは、まったくエクスポートされない。実際のコードではルートがメッセージ全体を覆うので最後に終了し、メッセージの途中でクラッシュしたプロセスは、ルートと実行中だったステップを失う。するとトレースは、親が届かないまま終了済みのステップだけが届く形になる。バッチプロセッサの場合は、キューに残っていたスパンも失われる。例でルートを最初に終了させているのは、リプレイの後でスパンを作っているからにすぎず、実際のコードではそうはならない。親を持たないスパンをちょうど一つ探す検査が、このようなトレースを見つける。

実践ルール: リプレイでは、すべてのスパンをリプレイのクロックから得た明示的な終了時刻で終了させる。実際のコードでは、SDK に開始と終了の両方の時刻をマシンのクロックから取らせる。いずれの場合も、各トレースにルート、すなわち親を持たないスパンがちょうど一つあることを検査する。ルートのないトレースはクラッシュが残すものであり、失敗ではなく、短いステップがいくつかあるだけのように見えるからである。

1本のトレースのツリー

Spans by handがメッセージ809に対して作った4つのスパンは、親へのリンクによってツリーを成す。スクリプトは続いて、それらの時間がどのように合計されるかを検査する。ツリーにはルートとその3つのステップが並び、その後の行にそれぞれの時間と検査結果が示される。

演習 1.2

メッセージ時間がステップの時間と一致する理由

+10 件の検証

45行目は、メッセージ時間とステップの時間を比較して yes を出力する。このリプレイについて、成り立つ説明はどれか。

メッセージ時間がステップの時間と一致する理由:正しい説明を選ぶ
Python 3.13.16 で実行される
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の3つのステップはルートの一段下に置かれる。OpenTelemetry Specificationはトレースをスパンの有向非巡回グラフと呼ぶが、親へのリンクによってそのグラフは、各スパンに親が1つだけあるツリーになる。ツリーは時間を示さないので、時間は次の行から得る。

子スパンが親スパンより後に終わることもある。仕様の概要はそのような例を図示しており、それを禁じる規則は設けていない(OpenTelemetry Specification, Overview: Traces, Spans, SpanContext、タグ v1.52.0)。したがって、子どうしが重なる場合、親の継続時間は子の継続時間の合計にならない。子の間に隙間がある場合も、合計と異なりうる。このリプレイでは、メッセージ809のステップは重ならず、隙間もない。ルートが終わるときに回答が始まる。スクリプトはこれを検査し、出力はメッセージの時間を11,520.7 ms、ステップの時間を11,520.7 msとして示す。この2つは同じ数である。

親のバーを、子が行った作業そのものとして読みたくなることがある。バーが示すのは親が開始し停止した位置だけであり、隙間はどの子にも記録されない作業である。このリプレイにはどちらの場合もない。

図 1.1は同じトレースをウォーターフォールとして描いたものである。ウォーターフォールとは、時間軸上にスパンごとに1本のバーを置く表示であり、トレース用ツールが描く表示である。仕様の概要もこれをスケッチしている。ただし、仕様はこれを形式として定義してはおらず、この図は本書独自の描画である。図には各スパンにつき1本のバーがあり、スパンの開始から終了までを、メッセージの到着後の秒数で表す。最上段にメッセージ全体のバーがあり、次に到着時点から始まるルートのバー、ルートが終わる位置の目盛りとして示されるretrieveステップ、そこからメッセージの終わりまで続くより長い回答のバーが並ぶ。

024681012seconds after the message arrivesmessagerouteretrieveanswer
図 1.1 メッセージ809のスパン(到着後の秒数)
figure-dev-day-waterfall.py Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · 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 合格
"""Draw one dev-day message's trace as a waterfall: each span a bar from its start to its end, after the message arrives.The bars are the spans of build-one-trace, from the replay's recorded times, so the figure shows the order and length ofthe steps. The printed lines are the values the figure's text quotes."""from lib.dayrun import run_dev_dayfrom lib.figures import ACCENT, INK, MUTED, new_figure, savefrom lib.report import fmt_ms(run,) = run_dev_day(["809"])outcome, arrived = run.outcome, run.arrived_ns# One bar per span: the message first, then its steps in order. The answer is the accent; the route is ink.bars = [("message", arrived, run.replied_ns, MUTED)]bars += [(s.step, s.start_ns, s.end_ns, ACCENT if s.step == "answer" else INK) for s in outcome.steps]fig, ax = new_figure(height=2.4)for row, (label, start, end, colour) in enumerate(bars):    left, width = (start - arrived) / 1e9, (end - start) / 1e9             # seconds after arrival    if width > 0:        ax.barh(row, width, left=left, height=0.6, color=colour)    else:                                                                  # a step with no time is a tick, not a bar        ax.plot([left], [row], marker="|", markersize=10, color=colour)ax.set_yticks(range(len(bars)), [label for label, _, _, _ in bars])ax.invert_yaxis()ax.set_xlabel("seconds after the message arrives")save(fig, "dev-day-waterfall")steps = {s.step: s for s in outcome.steps}                                 # one span per step in this messageroute, answer = steps["route"], steps["answer"]print("message, time from arrival to reply:", fmt_ms(run.replied_ns - arrived))print("route span, time:", fmt_ms(route.end_ns - route.start_ns))print("retrieve span, time:", fmt_ms(steps["retrieve"].end_ns - steps["retrieve"].start_ns))print("answer span, time:", fmt_ms(answer.end_ns - answer.start_ns))print("answer span starts, after arrival:", fmt_ms(answer.start_ns - arrived))# The steps run one after another: the answer starts exactly when the route ends, so the bars do not overlap.assert answer.start_ns == route.end_ns
出力python figure-dev-day-waterfall.py
figure: 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後に始まり、これはルートが終わる時点である。図の順序はステップが実行された順序であり、その長さは時計が記録した時間である。

実践ルール: トレースは親へのリンクのツリーとして出力し、子の時間を足し合わせる前に、子が重なっておらず隙間もないことを確かめる。重なりや隙間がある場合は、親の時間と子の時間を別々に報告する。

20件のメッセージで時間はどこに使われたか

メッセージ809は1つのトレースであり、開発日はそのようなトレース20件から成る。1メッセージにつき1トレースによって各メッセージのステップがまとめて保たれるので、その日のステップを合計できる。フォールバック応答とは、ルーターがfallbackを選んだときに Ambrewick が送る固定文である。モデルはこれを書かず、そのスパンにもその旨が記録される。開発日には、6 of 20件のメッセージがこの応答を受け取った。フォールバック応答が正しい答えになるのは、ツールにも記事にも解決できないメッセージに限られる。

sum-dev-day-steps.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 all 20 dev-day messages and add up each model step over the day: its calls, its recorded time, its tokens, and itsshare of the day's model time and tokens. Tool time is not in the recording (the tools are modelled), so it is countedand left out of the shares; retrieve and fallback take no time. The route-to-answer gap is the recorder's, not the replay's."""from collections import Counterfrom lib.dayrun import recorded_gap_ns, run_dev_dayfrom lib.report import fmt_int, fmt_ms, fmt_shareMODEL_STEPS = ("route", "answer")runs = run_dev_day()                                   # all 20 messages, in arrival ordercalls, time_ns, tokens = Counter(), Counter(), Counter()cached, overlapping, fallbacks = Counter(), 0, 0for run in runs:    ordered = sorted(run.outcome.steps, key=lambda s: s.start_ns)    overlapping += any(later.start_ns < earlier.end_ns for earlier, later in zip(ordered, ordered[1:]))    fallbacks += run.outcome.source == "fallback"    for step in run.outcome.steps:        calls[step.step] += 1        if step.step in MODEL_STEPS:       # the recording's times and tokens; input counts cached tokens too            time_ns[step.step] += step.end_ns - step.start_ns            tokens[step.step] += step.prompt_tokens + step.completion_tokens            cached[step.step] += step.cached_tokens            tokens[f"{step.step} input"] += step.prompt_tokensslowest = max(runs, key=lambda run: run.replied_ns - run.arrived_ns)     # the first of the slowest, if two tietotal_time, total_tokens = sum(time_ns[s] for s in MODEL_STEPS), sum(tokens[s] for s in MODEL_STEPS)input_total = sum(tokens[f"{s} input"] for s in MODEL_STEPS)print("messages in the dev day:", fmt_int(len(runs)))print("messages whose steps overlap in time:", f"{overlapping} of {len(runs)}")print("messages answered by the fallback reply:", f"{fallbacks} of {len(runs)}")print("slowest message:", slowest.message.message_id)print("slowest message time:", fmt_ms(slowest.replied_ns - slowest.arrived_ns))print("slowest message route:", slowest.outcome.route)for step in MODEL_STEPS:    print(f"{step} calls:", fmt_int(calls[step]))    print(f"{step}, recorded time:", fmt_ms(time_ns[step]))    print(f"{step}, share of model time:", fmt_share(time_ns[step], total_time))    print(f"{step}, share of tokens (input plus output):", fmt_share(tokens[step], total_tokens))print("tool calls:", fmt_int(calls["tool"]))print("retrieve calls:", fmt_int(calls["retrieve"]))print("route to answer gap, message 809:", fmt_ms(recorded_gap_ns("809", "route", "answer")))print("input tokens, total:", fmt_int(input_total))print("cached input tokens, total:", fmt_int(sum(cached[s] for s in MODEL_STEPS)))print("output tokens, total:", fmt_int(total_tokens - input_total))assert calls["route"] == len(runs)               # every message is routed onceassert overlapping == 0                          # the steps never overlap in the replay
出力python sum-dev-day-steps.py
messages 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
演習 1.3

各モデルステップの入力トークンと出力トークンを数える

+10 件の検証

20行目は各モデル呼び出しが書き出した分だけを加算しているため、トークンの割合にその日の入力が含まれない。各モデルステップのトークンが入力と出力の合計になるように、20行目を修正する。

        calls[step.step] += 1        if step.step in MODEL_STEPS:       # the recording's times and tokens; input counts cached tokens too            time_ns[step.step] += step.end_ns - step.start_ns            cached[step.step] += step.cached_tokens            tokens[f"{step.step} input"] += step.prompt_tokens
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 で実行される

このスクリプトは20件のメッセージを1件ずつ順に再生し、その日の各モデルステップを合計する。その日のツール呼び出しはプロセス内ツール、すなわちカレンダー、アラーム、リストの各ツールに向かった。これらの所要時間は記録された値ではなく、本書の設定にある表から求めたモデル値である。そのため、割合の計算には含めず、呼び出し回数としてのみ数える。Retrieve にも記録された時間はない。スクリプトは、ステップが時間的に重なるメッセージの数も数えており、その数は0 of 20である。したがって、その日の合計はステップ時間の合計であり、各メッセージのルート時間を分割したものではない。

answer ステップはその日のモデル時間の大半を占め、その割合は83.3%である。一方、route ステップはトークンの21.2%を占めるが、時間では16.7%にとどまる。answer の呼び出し回数がモデルの回答したメッセージ数を上回るのは、ツールを呼び出した各メッセージで、ツールが結果を返した後にさらに answer の呼び出しが必要になったためである。その結果、answer ステップは17回実行された。割合の分母はその日のモデル時間と、入力と出力を合わせたトークンであり、出力には両方の合計が表示される。

図 1.2は、各モデルステップの2つの割合を描いたものである。図が示すように、時間とトークンは同じ形にはならない。

routeanswer020406080100percent of the dev day16.7%83.3%21.2%78.8%share of model timeshare of tokens
図 1.2 開発日のモデル時間とトークンに占める各モデル呼び出しの割合(20件のメッセージ)
figure-dev-day-step-shares.py Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · 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 合格
"""Draw each model step's share of the dev day's model time, beside its share of the tokens (input plus output), over all20 messages. Each bar is labelled with the share the example prints, so the figure and the printed lines are one set ofnumbers. Tool time is not in the recording, so the tool step is not drawn."""from collections import Counterfrom lib.dayrun import run_dev_dayfrom lib.figures import ACCENT, INK, new_figure, savefrom lib.report import fmt_int, fmt_ms, fmt_shareMODEL_STEPS = ("route", "answer")runs = run_dev_day()calls, time_ns, tokens = Counter(), Counter(), Counter()for run in runs:    for step in (s for s in run.outcome.steps if s.step in MODEL_STEPS):        calls[step.step] += 1        time_ns[step.step] += step.end_ns - step.start_ns        tokens[step.step] += step.prompt_tokens + step.completion_tokens      # input plus outputtotal_time, total_tokens = sum(time_ns.values()), sum(tokens.values())time_labels = [fmt_share(time_ns[s], total_time) for s in MODEL_STEPS]token_labels = [fmt_share(tokens[s], total_tokens) for s in MODEL_STEPS]fig, ax = new_figure(height=2.6)positions = list(range(len(MODEL_STEPS)))time_bars = ax.bar([p - 0.2 for p in positions], [100 * time_ns[s] / total_time for s in MODEL_STEPS], width=0.4,                   color=ACCENT, label="share of model time")token_bars = ax.bar([p + 0.2 for p in positions], [100 * tokens[s] / total_tokens for s in MODEL_STEPS], width=0.4,                    color=INK, label="share of tokens")ax.bar_label(time_bars, labels=time_labels, padding=2)ax.bar_label(token_bars, labels=token_labels, padding=2)ax.set_xticks(positions, list(MODEL_STEPS))ax.set_ylim(0, 100)ax.set_ylabel("percent of the dev day")ax.legend(loc="upper left")          # the route bars reach only about 21 percent, so the top left is clear of labelssave(fig, "dev-day-step-shares")print("messages in the dev day:", fmt_int(len(runs)))for step, time_label, token_label in zip(MODEL_STEPS, time_labels, token_labels):    print(f"{step} calls:", fmt_int(calls[step]))    print(f"{step}, recorded time:", fmt_ms(time_ns[step]))    print(f"{step}, share of model time:", time_label)    print(f"{step}, tokens, input plus output:", fmt_int(tokens[step]))    print(f"{step}, share of tokens:", token_label)print("model time, total:", fmt_ms(total_time))print("tokens, input plus output, total:", fmt_int(total_tokens))assert sum(calls.values()) == 37     # 20 route calls and 17 answer calls, as the recording holds
出力python figure-dev-day-step-shares.py
figure: 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
演習 1.4

入力トークンと出力トークンをあわせて数える

+10 件の検証

16行目は各呼び出しの completion トークンだけを数えているが、シェアは入力と出力の合計として数えたトークンに対して求められる。16行目を修正し、各呼び出しが入力トークンと出力トークンの両方を加算するようにせよ。

    for step in (s for s in run.outcome.steps if s.step in MODEL_STEPS):        calls[step.step] += 1        time_ns[step.step] += step.end_ns - step.start_nstotal_time, total_tokens = sum(time_ns.values()), sum(tokens.values())time_labels = [fmt_share(time_ns[s], total_time) for s in MODEL_STEPS]
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 で実行される
演習 1.5

各割合の分母となる合計を書く

+10 件の検証

18行目は空白である。2つの分母が、その日のモデル時間と、その日の入力トークンと出力トークンの合計になるように、この行を書く。いずれも、11行目の time_ns カウンタと tokens カウンタに入っているモデルステップごとの値を、モデルステップについて合計したものとする。

        time_ns[step.step] += step.end_ns - step.start_ns        tokens[step.step] += step.prompt_tokens + step.completion_tokens      # input plus outputtime_labels = [fmt_share(time_ns[s], total_time) for s in MODEL_STEPS]token_labels = [fmt_share(tokens[s], total_tokens) for s in MODEL_STEPS]fig, ax = new_figure(height=2.6)
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 で実行される

ステップの時間の割合は、その日の待ち時間がどこに使われたかを示し、トークンの割合は、その日の入力と出力がどこから生じたかを示す。この2つは別々の問いであり、本章は両方に答える。どのステップに最も費用がかかるかは第6章の問いであり、その答えにはトークンに加えて価格も必要になる。

実践ルール: 各ステップの記録された時間とトークンをメッセージ全体で合計し、各割合をその分母とともに表示する。時間が記録されていないステップは名前を挙げて割合から除外し、合計がその日のどの部分を覆っていないかを読者が確認できるようにする。

このバージョンがまだ行わないこと

このバージョンは粗いものであり、各部分には、それを堅牢にする後の章がある。順に示す。

  • 名前。 スパンには、本書独自の手順で名前を付けている。第2章では、標準が定める名前で各スパンに名前を付け、種別を設定し、バリデータで検査する。ここにあるスパンはすべて、その検査に失敗する。
  • モデル呼び出し。 スパンは手作業で作っている。第3章では、同種の呼び出しに対して、openai クライアントライブラリの公式インストルメンテーションが何を出力するかを示す。
  • 第2のプロセス。 このトレースは1つのプロセスの記録である。第4章では、別プロセスとして動くコンタクトチームのサーバのスパンを、このトレースに結合する。
  • 保存。 スパンはメモリ上にあり、プロセスが終了すると消える。第5章では、スパンを保存するバックエンドに送る。
  • テール。 20件のメッセージからは、確信をもってテールのパーセンタイルを求めることはできない。第7章では、件数と区間を添えてパーセンタイルを示す。
  • サンプリング。 すべてのトレースを保持している。第11章では、どのトレースを保持するかを、その理由とともに決める。
  • プロンプト。 スパンにはプロンプトのテキストを意図的に含めていない。第3章では、それを記録するスイッチの名前を示し、第12章では、そのスイッチが何を漏らすかを扱う。
  • 誤ったルート。 開発日のメッセージのうち 6 of 20 件がフォールバック応答を受け取ったが、この章では各ルートが正しかったかどうかは検査しない。第8章で検査する。

本章で行った決定

次の決定は、本書の残りの部分を方向づける。

  • スパンは当面、ステップごとに名前を付ける。第2章以降は、標準の名前を用いる。
  • 各所要時間は記録された値であり、実行時の計測値ではない。したがって、表示されるすべての時間は再実行して照合できる。
  • スパンは終了した時点で同期プロセッサによってエクスポートされる。これにより、すべてのスパンは、表示される時点までにエクスポート済みになっている。
  • 割合は分母とともに表示する。時間が記録されていないステップは、推定せずに割合の対象から除く。
  • 各トレースは1件のメッセージのものである。1日分の合計は、記録に保持されたとおりにメッセージのステップを足し合わせたものであり、スパンから作る別の指標は用いない。

実践ルール: 1件のメッセージに関する問いには、そのメッセージのトレースだけで答える。メッセージのすべてのスパンはトレースIDを共有し、ルートはその全体の時間を覆う。したがって、トレースにはそのメッセージのステップだけがあり、他のメッセージのステップはない。IDのないスパンやログ行は、答えの中に位置づけられない。そのため、どのメッセージに属するかを推測せず、除外したうえで、除外したことを明記する。推測すると、あるメッセージの時間が別のメッセージの合計に入り込むことになる。

この版における本章

第2026.11.2版2026年11月23日時点で例が通過この章の6 例件のうち6件が合格

英語版の書籍(版2026.11.2)から翻訳した。

Labs を開始

書籍は引き続き無料で読める。

料金を見る

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全12章中の第1章: リクエストをトレースし、時間の行き先を問う

  1. 1メッセージにつき1トレース
  2. リプレイと仮想クロック
  3. スパンを手作業で作る
  4. 1本のトレースのツリー
  5. 20件のメッセージで時間はどこに使われたか
  6. このバージョンがまだ行わないこと
  7. 本章で行った決定

ページの先頭に戻るすべての章