遅延の発生源を見つける

読了まで約50 分。9 節に9 例を収録。

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

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

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

Labs

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

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

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

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

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

Lab を確認しています…

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

この章を読み終えると、メッセージの所要時間をどの手順が決めているかを、中央値と裾の両方について言えるようになる。さらに、各数値を件数と、その周りの区間とともに出力できるようになる。Ambrewick のアシスタントは、1 件のメッセージに最大 5 つの手順で応答する。トレースにはメッセージの各手順が記録されているが、どの手順がそのメッセージの終了時刻を決めているかは記録されていない。基準日 1 日目について、この章が読む 200 件のメッセージでは、中央値のメッセージは 8,099.3 ms を要し、95 パーセンタイルは 18,351.2 ms を要した。この時間は、記事の読み込み、返信の記述、ツールの待機のうち、どれに費やされたのか。

ここでの時間はすべて、1 台の記録用マシンで得たものである。このマシンは 4 vCPU、2.10 GHz の Intel Xeon で、Qwen3-4B-Instruct-2507(以下、4B)を動かした。各時間は、1 回の呼び出しに記録された時間か、それらを リプレイと仮想クロック で述べた仮想クロック上で合計したもののどちらかである。ここでのメッセージの時間は、そのメッセージが行った各呼び出しの記録時間に、プロセス内ツールのモデル化した時間と、contacts 呼び出しの記録時間を加え、そのクロック上で合計したものである。記録器は呼び出しの間の時間も保存していたが、リプレイはそれを含めない。その時間は 1 日全体で合計 651.4 ms になる。各節では、数値がこの 2 つのどちらにあたるかを示す。

この章では、メッセージの終了時刻を決める呼び出しの連鎖を構築し、続いて各モデル呼び出しを読み込みと書き出しに分け、最後に裾を扱う。裾では、経路ごとにパーセンタイルとその区間を求める。

クリティカルパスが終了時刻を決める

メッセージのトレースは、時間を持つスパンの木であり、ルートスパンは返信が送られた時点で終わる。大半のスパンはルートの内側に収まり、その大半は終了時刻を決めていない。終了時刻を決めるスパンを見つけるには、ルートの終了時刻から逆にたどる。最後に終わる子スパンを取り、次にその子スパンが始まるより前で最後に終わる子スパンを取る。これを、たどった先がルートの開始時刻に達するまで続ける。クリティカルパスとは、メッセージの終了時刻を決めるスパンの連鎖である。それ以外のスパンを短縮しても、メッセージは早く終わらない。連鎖上のスパンを短縮すれば、別の連鎖のほうが長くなるまで、メッセージは短くなる。

critical-path-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 the slowest message of baseline day 1 and list the chain of spans that sets its end time. The replay runs thecalls one after another, so every call is on the chain, and shortening any one of them shortens this message: the pointrests on the path lines and the assert that the path covers the whole message. The recorder's gaps between calls arenot in the replay; the day's total of them is printed beside it. The tool's time is modelled, a few microseconds, so itprints as 0.0 ms."""from lib.critical_path import critical_pathfrom lib.dayrun import DATA, run_day, run_day_tracedfrom lib.report import fmt_ms, fmt_shareimport jsonDAY = "2026-12-08"runs = run_day(DAY)                                                      # all 200 messages, in arrival orderslowest = max(runs, key=lambda run: run.replied_ns - run.arrived_ns)     # the longest of the day; no other message ties with ittraced = run_day_traced(DAY, [slowest.message.message_id], live=False)   # its spans, replayed the same wayby_id = {row["span_id"]: row for row in traced.spans}path = critical_path(traced.spans)                                       # root first, then the chain in time ordermessage = by_id[path[0]]message_time = message["end_ns"] - message["start_ns"]chain = [by_id[span_id] for span_id in path[1:]]covered = sum(row["end_ns"] - row["start_ns"] for row in chain)print("message:", slowest.message.message_id)print("route:", slowest.outcome.route)print("message time:", fmt_ms(message_time))for number, row in enumerate(chain, start=1):    # The inference spans carry their prompt's name, so the route call and the answer calls read apart.    name = row["attributes"].get("gen_ai.prompt.name", row["name"])    print(f"on the path, {number}: {name}, time: {fmt_ms(row['end_ns'] - row['start_ns'])}")print("share of the message time on the path:", fmt_share(covered, message_time))# The recorder's own offsets give the gaps the replay does not keep: each message's span minus its calls' times.rows = [json.loads(line) for line in (DATA / "baseline-day-1" / "traces.jsonl").read_text(encoding="utf-8").splitlines()]gap_ns = 0for message_id in sorted({row["message_id"] for row in rows}):    calls = [row for row in rows if row["message_id"] == message_id]    span = max(c["offset_ns"] + c["total_ns"] for c in calls) - min(c["offset_ns"] for c in calls)    gap_ns += span - sum(c["total_ns"] for c in calls)print("gaps between calls, recorded, all messages of the day:", fmt_ms(gap_ns))# A constructed tree, not the recording: two calls that overlap. The one that ends last sets the end, and the other# is off the path, since the walk back from the end reaches the later call's start before it reaches the earlier one.toy = [    {"span_id": "a", "parent_span_id": None, "start_ns": 0, "end_ns": 10, "span_seq": 1},    {"span_id": "b", "parent_span_id": "a", "start_ns": 0, "end_ns": 6, "span_seq": 2},    {"span_id": "c", "parent_span_id": "a", "start_ns": 2, "end_ns": 9, "span_seq": 3},]toy_covered = sum(row["end_ns"] - row["start_ns"] for row in toy if row["span_id"] in critical_path(toy)[1:])print("constructed overlap, span IDs on the path:", ", ".join(critical_path(toy)))print("constructed overlap, share of the root's time on the path:", fmt_share(toy_covered, toy[0]["end_ns"] - toy[0]["start_ns"]))assert critical_path(toy) == ["a", "c"]assert covered == message_time                 # the chain's calls cover the whole message, with no gapassert len(chain) == len(traced.spans) - 1     # every call of the message is on the path
出力python critical-path-one-message.py
message: 7055
route: calendar
message time: 24,305.8 ms
on the path, 1: ambrewick.route, time: 1,666.5 ms
on the path, 2: ambrewick.answer, time: 14,993.5 ms
on the path, 3: execute_tool add_event, time: 0.0 ms
on the path, 4: ambrewick.answer, time: 7,645.8 ms
share of the message time on the path: 100.0%
gaps between calls, recorded, all messages of the day: 651.4 ms
constructed overlap, span IDs on the path: a, c
constructed overlap, share of the root's time on the path: 70.0%
演習 7.1

メッセージ自身のスパンをチェーンから除く

+10 件の検証

20行目はパス全体からチェーンを作るため、メッセージ自身のルートスパンがリンクとして数えられている。20行目を変更し、チェーンにはルートの下で探索が到達する呼び出しだけが入るようにせよ。

path = critical_path(traced.spans)                                       # root first, then the chain in time ordermessage = by_id[path[0]]message_time = message["end_ns"] - message["start_ns"]covered = sum(row["end_ns"] - row["start_ns"] for row in chain)print("message:", slowest.message.message_id)
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 で実行される

この実行では、メッセージ 7055 を再現する。これはその日で最も長いメッセージであり、calendar ルートを通り、スパンは保持されている。たどると、ルート呼び出し、回答呼び出し、add_event ツール、2 回目の回答呼び出しの 4 つのリンクが得られる。出力はそれぞれの時間を示し、4 つの合計はメッセージの 24,305.8 ms になる。パス上の時間の割合は 100.0% であり、実行は連鎖がメッセージ全体を覆っていることをアサートする。

再現でこの割合を示せるのは、呼び出しが 1 つずつ順に実行され、その間に何もないからである。レコーダーの隙間には固有のスパンがないため、スパンから作るパスはそれを含めない。このメッセージの再現には、その日の隙間のどれも含まれていない。パスが覆うのは、モデル呼び出し、プロセス内ツールのモデル化された時間、contacts 呼び出しの記録された時間であり、それ以外は含まない。retrieve ステップも、スパンの開始と終了が同一の時点であるため、時間を持たない。

重なりは、再現では示せないケースである。記録されたメッセージには 2 つの呼び出しが同時に動くものがないため、この実行では小さな木を手で作る。スパン a がルートで、10 で終わる。スパン b は 0 から 6 まで、スパン c は 2 から 9 まで動く。終了時刻から逆にたどると最初に c に着き、b には戻らないので、パスは a, c になる。スパン b はパス上になく、b を短縮しても終了時刻は動かない。これはこの木に限って成り立つ。パスがルートの時間のうち覆うのは 70.0% であり、パス上のスパンが説明できる時間もその分だけである。これが、実践ルールの警告する低い割合である。

実践ルール: トレースを調整する前にクリティカルパスをたどり、パス上のスパンだけを変更する。まず、メッセージの時間に対するパスの割合を読む。割合が低いなら、手元のスパンでは時間を説明できておらず、残りはどのスパンにも属していない。再現のパスは常にそのメッセージ全体を覆うので、重なり合う 2 つの呼び出しのどちらが重要かは、再現からは分からない。

この部分はまだ翻訳されていないため、英語で表示している。

Time to first chunk

The answer calls hold most of the path, so the next question is where inside a call the time goes. Time to first chunk is the time from sending a model call to receiving the first streamed piece of its reply. The conventions at tag 0.1.0 measure that wait with the metric gen_ai.client.inference.time_to_first_chunk, which is a histogram in seconds, on streaming calls only and only when a chunk arrives. The span attribute gen_ai.response.time_to_first_chunk measures from the start of the logical operation, before authentication and the first attempt, so a hosted client's retries count toward it. Chapter 3's name table maps the package's name for the metric to the standard's.

The numbers in this section come from the recorder, not from the metric, which these examples do not run. The recorder timed the first stream event of each streamed reply, which this runtime sends together with the first content. A local model has no authentication step to add.

Each median in this section comes with a 95% interval, which tail percentiles with intervals defines.

time-to-first-chunk-by-route.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 合格
"""Take each message's last answer call on baseline day 1, the one that writes the reply the user reads, and compare its timeto first chunk with its total time, by route. Fallback replies make no answer call, so they have no first chunk, and eachinterval resamples messages, not calls (PL-6)."""from lib.dayrun import DATA, run_dayfrom lib.report import fmt_int, fmt_ms, fmt_sharefrom lib.stats import bootstrap_interval, nearest_rankimport jsonfrom collections import defaultdictruns = run_day("2026-12-08")routes = {run.message.message_id: run.outcome.route for run in runs}rows = [json.loads(line) for line in (DATA / "baseline-day-1" / "traces.jsonl").read_text(encoding="utf-8").splitlines()]# A first chunk comes before the call ends, and the recorder keeps both times for every call.assert all(row["ttfc_ns"] <= row["total_ns"] for row in rows)last_answer = {}for row in sorted(rows, key=lambda r: r["seq"]):          # the sequence numbers give the order the calls were made    if row["step"] == "answer":        last_answer[row["message_id"]] = row               # the later call overwrites the earlier oneby_route = defaultdict(list)for message_id, row in last_answer.items():    by_route[routes[message_id]].append(row)assert not any(routes[message_id] == "fallback" for message_id in last_answer)print("interval method: bootstrap over messages, 2,000 resamples, seed 20261207, 95%")for route in sorted(by_route):    calls = by_route[route]    ttfc = [call["ttfc_ns"] for call in calls]    total = [call["total_ns"] for call in calls]    low, high = bootstrap_interval(calls, lambda units: nearest_rank([u["ttfc_ns"] for u in units], 50))    print(f"{route}, messages with an answer call: {fmt_int(len(calls))}")    print(f"{route}, time to first chunk, median: {fmt_ms(nearest_rank(ttfc, 50))}")    print(f"{route}, time to first chunk, 95% interval: {fmt_ms(low)} to {fmt_ms(high)}")    print(f"{route}, total time of the answer call, median: {fmt_ms(nearest_rank(total, 50))}")    print(f"{route}, time to first chunk, share of the call's time: {fmt_share(sum(ttfc), sum(total))}")route_calls = [row for row in rows if row["step"] == "route"]print("route calls, time to first chunk, median, all messages:", fmt_ms(nearest_rank([c["ttfc_ns"] for c in route_calls], 50)))print("route calls, n:", fmt_int(len(route_calls)))print("messages with no answer call:", fmt_int(len(runs) - len(last_answer)))
出力python time-to-first-chunk-by-route.py
interval method: bootstrap over messages, 2,000 resamples, seed 20261207, 95%
alarms, messages with an answer call: 16
alarms, time to first chunk, median: 5,985.6 ms
alarms, time to first chunk, 95% interval: 1,514.8 ms to 6,456.4 ms
alarms, total time of the answer call, median: 9,744.4 ms
alarms, time to first chunk, share of the call's time: 49.6%
calendar, messages with an answer call: 27
calendar, time to first chunk, median: 6,818.8 ms
calendar, time to first chunk, 95% interval: 1,120.5 ms to 7,322.9 ms
calendar, total time of the answer call, median: 10,676.0 ms
calendar, time to first chunk, share of the call's time: 48.8%
devices, messages with an answer call: 17
devices, time to first chunk, median: 6,090.0 ms
devices, time to first chunk, 95% interval: 4,377.7 ms to 6,616.4 ms
devices, total time of the answer call, median: 11,326.7 ms
devices, time to first chunk, share of the call's time: 47.7%
lists, messages with an answer call: 13
lists, time to first chunk, median: 8,563.7 ms
lists, time to first chunk, 95% interval: 8,397.1 ms to 8,866.0 ms
lists, total time of the answer call, median: 12,256.8 ms
lists, time to first chunk, share of the call's time: 69.5%
media, messages with an answer call: 31
media, time to first chunk, median: 5,911.4 ms
media, time to first chunk, 95% interval: 5,663.0 ms to 6,128.4 ms
media, total time of the answer call, median: 11,073.2 ms
media, time to first chunk, share of the call's time: 49.8%
messages, messages with an answer call: 7
messages, time to first chunk, median: 9,289.0 ms
messages, time to first chunk, 95% interval: 485.7 ms to 12,842.8 ms
messages, total time of the answer call, median: 13,865.7 ms
messages, time to first chunk, share of the call's time: 59.4%
route calls, time to first chunk, median, all messages: 530.2 ms
route calls, n: 200
messages with no answer call: 89
演習 7.2

メッセージごとに最新の応答呼び出しを保持する

+10 件の検証

20行目はメッセージごとに応答呼び出しを1つだけ保持しているが、この節では、出力はメッセージの応答呼び出しのうち特定の1つを使うとされている。各メッセージが節で指定された呼び出しを保持するように、20行目を変更せよ。

last_answer = {}for row in sorted(rows, key=lambda r: r["seq"]):          # the sequence numbers give the order the calls were made    if row["step"] == "answer":by_route = defaultdict(list)for message_id, row in last_answer.items():    by_route[routes[message_id]].append(row)
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 で実行される

The output takes each message's last answer call, the one that writes the reply the user reads, and sets its time to first chunk beside its total time, by route. Messages routed to the fallback reply make no answer call, which chapter 1 describes, so the output counts them apart: 89 of them. The 200 route calls, which pick a route, reach their first chunk at a median of 530.2 ms.

Answer calls take longer to produce that first chunk. Leaving aside the messages route, which has 7, lists has the largest median first chunk, 8,563.7 ms, from 13 messages. Its 95% interval, 8,397.1 ms to 8,866.0 ms, sits above every other route's but messages'.

On lists, the first chunk takes 69.5% of the call's time. On the other routes that share runs from 47.7% to 59.4%.

The messages route needs the most care. Its median first chunk is 9,289.0 ms, from 7 messages, and its 95% interval, 485.7 ms to 12,842.8 ms, is the widest in the output.

Working rule: Print time to first chunk beside the total time of the same call, and read the two together. An early first chunk means the user sees output early. It does not mean the call was cheap. Compare routes on their intervals and on the share, and do not name a route's first chunk from a handful of messages.

プレフィルと生成

最初のチャンクはプロンプトを待つ。そこで次の問いは、その待ち時間のうちどれだけがプロンプトの読み込みで、どれだけがそれ以外なのか、である。プレフィルとはモデルがプロンプトを読むことであり、生成とはモデルが返答を1トークンずつ書くことである。GPU 向けのサービング論文も同じ区分を採っている。プレフィルは計算資源をふさぎ続け、デコードの各ステップではその大半が遊ぶ(Agrawal et al., Sarathi-Serve、OSDI 2024。1回の反復で出力トークンを1つとする点については Yu et al., Orca、OSDI 2022)。

この節で使う数には新たな定義は要らない。第6章は入力トークンと出力トークンの出どころを説明しており、キャッシュされた入力の節はキャッシュ分の割合の導き方を説明している。評価されたトークンとは、入力からキャッシュ済みの接頭辞を除いた残りであり、モデルが実際に読んだ入力である。

カウンタは llama-cpp-python から得る。llama-cpp-python は、コンテキストごとの llama.cpp のカウンタを公開している。評価されたプロンプトトークンとそれに要した時間、生成されたトークンとそれに要した時間である。カウンタは加算されるだけなので、レコーダは各呼び出しの前後の差を取る。各プロセスの最初の記録対象メッセージより前に行う4回のウォームアップ呼び出しは、この区分に含めない。

prefill-generation-split.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 合格
"""Split the recorded compute of each model call on baseline day 1 into prefill (the prompt the model read) and generation(the tokens it wrote), from llama.cpp's counters on the recording machine. The split is the method's output: the numbersbelong to that machine, and the method carries to other hardware. The recorder's warm-up call, made before eachprocess's first recorded message, is not recorded, so it is not in the split. Rates are computed from the recorded counts."""from lib.dayrun import DATAfrom lib.report import fmt_int, fmt_shareimport jsonrows = [json.loads(line) for line in (DATA / "baseline-day-1" / "traces.jsonl").read_text(encoding="utf-8").splitlines()]for step in ("route", "answer"):    calls = [row for row in rows if row["step"] == step]    prefill = sum(call["prefill_ns"] for call in calls)    generation = sum(call["gen_ns"] for call in calls)    first_chunk = sum(call["ttfc_ns"] for call in calls)    evaluated = sum(call["tokens_evaluated"] for call in calls)   # the prompt's tokens the model read, minus cached ones    written = sum(call["completion_tokens"] for call in calls)    assert all(call["prefill_ns"] <= call["ttfc_ns"] for call in calls)   # the first chunk waits for the prompt    print(f"{step} calls: {fmt_int(len(calls))}")    print(f"{step}, prefill share of prefill plus generation: {fmt_share(prefill, prefill + generation)}")    print(f"{step}, prefill share of time to first chunk: {fmt_share(prefill, first_chunk)}")    print(f"{step}, prompt tokens evaluated per second of prefill, computed: {evaluated * 1e9 / prefill:.1f}")    print(f"{step}, tokens written per second of generation, computed: {written * 1e9 / generation:.1f}")
出力python prefill-generation-split.py
route calls: 200
route, prefill share of prefill plus generation: 32.8%
route, prefill share of time to first chunk: 72.7%
route, prompt tokens evaluated per second of prefill, computed: 47.6
route, tokens written per second of generation, computed: 7.3
answer calls: 121
answer, prefill share of prefill plus generation: 54.1%
answer, prefill share of time to first chunk: 91.2%
answer, prompt tokens evaluated per second of prefill, computed: 62.3
answer, tokens written per second of generation, computed: 7.0

出力は各ステップの計算を2種類の作業に分けており、先頭にルート呼び出しがある。ルート呼び出しは固定の指示とメッセージを読み、回答呼び出しはメッセージとルートが取得した内容を読む。ルート呼び出しの最初のチャンクはプロンプトを待つ。その待ち時間のうちプレフィルは72.7%を占めるが、呼び出しの計算全体に占める割合は32.8%にすぎない。回答呼び出しは、同じものをさらに大きな割合で待つ。最初のチャンクまでの待ち時間のうちプレフィルは91.2%であり、返答の最初の一語は、おもにプロンプトが読まれている時間である。

回答呼び出しの生成は毎秒7.0トークンで進み、プレフィルは毎秒62.3トークンを評価して読む。これらの速度は件数から計算したものであり、このマシンでのみ成り立つ。その理由は Small Open Models が述べるとおりで、小型モデルの速度は、名前を挙げた1台のマシンでの記録として測るものであり、決まりごととして引用しない。プレフィルは入力トークンではなく評価されたトークンで数える。この選択がなぜ重要かは次の節で示す。

実践ルール: モデル呼び出しの時間は、プロンプトや返答の長さを変える前に、プレフィルと生成に分ける。区分はカウンタから、同じマシンで同じ呼び出しについて取り、合計と並べて読む。最初のチャンクまでの時間の大半がプレフィルであれば、待ちの原因はプロンプトにある。呼び出しの大半が生成であれば、原因は返答の長さにある。

この部分はまだ翻訳されていないため、英語で表示している。

Retrieved context against prefill

Retrieval puts articles into the answer call's prompt, so a release that retrieves more should make prefill longer. The question for that release is how much longer, and whether the model reads all of the added input. The top-8 release gives the answer call up to eight articles, where the baseline gives up to three, on the routes that retrieve. Route calls come before retrieval, so their prompts hold no articles in either release.

The comparison uses the same messages under both releases, the paired 60: the messages of baseline day 1 that the top-8 release was also recorded on. The output's r0 is the baseline and r3 is the top-8 release. It sums each release's answer calls over those messages, and that is a sum, not a comparison with an interval. Chapter 10 pairs the same messages and gives the interval on the difference.

context-against-prefill.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 合格
"""Compare the same 60 messages under r0 (the baseline, on baseline day 1) and r3 (the top-8 release): the answer calls'prefill, tokens and cache, and the route calls' cache. More articles make the prompt longer, and prefill follows the tokens themodel had to evaluate, since a cached prefix is not read again while the cache holds it. The correlations are over all ofbaseline day 1's answer calls, computed; the paired interval belongs to chapter 10, so none is printed here."""from lib.case import load_messagesfrom lib.dayrun import DATAfrom lib.report import fmt_int, fmt_msimport jsonfrom collections import Counterfrom statistics import correlationdef load(folder):    return [json.loads(line) for line in (DATA / folder / "traces.jsonl").read_text(encoding="utf-8").splitlines()]def total(rows, step, field):    return sum(row[field] for row in rows if row["step"] == step)paired = {message.message_id for message in load_messages("2026-12-08-paired")}   # the 60 messages, same arrivalsbase = load("baseline-day-1")releases = {"r0": [row for row in base if row["message_id"] in paired], "r3": load("release-top-8")}assert {row["message_id"] for row in releases["r3"]} == paired     # r3 was recorded for exactly these messagesfor name, rows in releases.items():    print(f"{name}, prefill summed over the answer calls:", fmt_ms(total(rows, "answer", "prefill_ns")))    print(f"{name}, prompt tokens summed over the answer calls:", fmt_int(total(rows, "answer", "prompt_tokens")))    print(f"{name}, prompt tokens evaluated summed over the answer calls:", fmt_int(total(rows, "answer", "tokens_evaluated")))    print(f"{name}, cached prompt tokens summed over the answer calls:", fmt_int(total(rows, "answer", "cached_tokens_derived")))    print(f"{name}, prompt tokens evaluated summed over the route calls:", fmt_int(total(rows, "route", "tokens_evaluated")))print("prefill, r3 over r0, computed:", f"{total(releases['r3'], 'answer', 'prefill_ns') / total(releases['r0'], 'answer', 'prefill_ns'):.2f}")# The same answer calls under both releases: sorted by message, then by call, so each pair is one message's n-th answer.before = sorted((row for row in releases["r0"] if row["step"] == "answer"), key=lambda row: (row["message_id"], row["seq"]))after = sorted((row for row in releases["r3"] if row["step"] == "answer"), key=lambda row: (row["message_id"], row["seq"]))assert all(b["message_id"] == a["message_id"] and b["prompt_tokens"] <= a["prompt_tokens"] for b, a in zip(before, after))gained = sum(a["prompt_tokens"] > b["prompt_tokens"] for b, a in zip(before, after))   # the assert: none loses anyprint("paired answer calls, r3 with more prompt tokens than r0:", f"{gained} of {len(before)}")route = {name: {row["message_id"]: row for row in rows if row["step"] == "route"} for name, rows in releases.items()}assert all(route["r0"][m]["input_key"] == route["r3"][m]["input_key"]           and route["r0"][m]["prompt_tokens"] == route["r3"][m]["prompt_tokens"] for m in paired)   # identical route promptscached = {name: [row["cached_tokens_derived"] for row in rows if row["step"] == "route"] for name, rows in releases.items()}instruction = Counter(cached["r0"]).most_common(1)[0][0]        # the cached count most route calls get: the instructionprint("route instruction, cached tokens in most route calls:", fmt_int(instruction))for name in releases:    print(f"{name}, route calls that re-read most of the instruction:", sum(c < instruction for c in cached[name]))answer_calls = [row for row in base if row["step"] == "answer"]by_prompt = correlation([row["prompt_tokens"] for row in answer_calls], [row["prefill_ns"] for row in answer_calls])by_evaluated = correlation([row["tokens_evaluated"] for row in answer_calls], [row["prefill_ns"] for row in answer_calls])print("prefill against prompt tokens, correlation, computed:", f"{by_prompt:.2f}")print("prefill against tokens evaluated, correlation, computed:", f"{by_evaluated:.2f}")assert by_evaluated > 0.9 and by_evaluated > by_prompt   # the cached prefix adds to the prompt, not to the prefill
出力python context-against-prefill.py
r0, prefill summed over the answer calls: 172,043.5 ms
r0, prompt tokens summed over the answer calls: 20,420
r0, prompt tokens evaluated summed over the answer calls: 10,855
r0, cached prompt tokens summed over the answer calls: 9,565
r0, prompt tokens evaluated summed over the route calls: 827
r3, prefill summed over the answer calls: 289,244.2 ms
r3, prompt tokens summed over the answer calls: 27,326
r3, prompt tokens evaluated summed over the answer calls: 17,813
r3, cached prompt tokens summed over the answer calls: 9,513
r3, prompt tokens evaluated summed over the route calls: 1,209
prefill, r3 over r0, computed: 1.68
paired answer calls, r3 with more prompt tokens than r0: 15 of 33
route instruction, cached tokens in most route calls: 133
r0, route calls that re-read most of the instruction: 1
r3, route calls that re-read most of the instruction: 4
prefill against prompt tokens, correlation, computed: 0.29
prefill against tokens evaluated, correlation, computed: 0.99

On the paired messages, the answer calls take 289,244.2 ms of prefill under the top-8 release, against 172,043.5 ms under the baseline: 1.68 times as much. The output also gives two correlations over every answer call of baseline day 1.

The input grows with the articles. Input tokens rise from 20,420 to 27,326, and tokens evaluated, the input the model read, rise from 10,855 to 17,813.

Both releases skip about the same cached prefix, 9,565 tokens under the baseline and 9,513 under the top-8 release, so the model reads the added input. Under the top-8 release, 15 of 33 paired answer calls gained prompt tokens, and none lost any.

The route calls show a gap without any article in their prompts. Under the top-8 release they evaluate 1,209 tokens, against 827 under the baseline, on prompts the example asserts are identical under both releases.

The cause is the recorder's cache. The cache is bounded at 1 GiB and drops its oldest state first, so a route call that runs after enough others finds its instruction gone and reads it again. The recording logs no cache hits, so this follows from the cache's rule and not from a log. The cache holds the instruction, 133 tokens, for most route calls. Under the top-8 release, 4 route calls re-read most of it, against 1 under the baseline.

Prefill follows tokens evaluated rather than input. Across baseline day 1's answer calls, prefill correlates 0.99 with tokens evaluated and 0.29 with input. A prefix the model has read before is not read again while the cache holds it, so input can grow while the work does not, and the tokens a call evaluates depend on the calls before it.

Working rule: Measure a prompt's extra prefill on the same messages as the release it changes, and read tokens evaluated beside input tokens. Input tokens say how large the prompt is. Tokens evaluated say how much work the model did, and when a prefix is cached the two counts part company. Act on the work.

この部分はまだ翻訳されていないため、英語で表示している。

Tail percentiles with intervals

The medians so far leave out the messages that wait longest, and those are the ones a tail percentile is for. This book uses the nearest rank. The p-th percentile is the value at sorted position ceil(p/100 × n); the tail is the slowest few percent of messages. Sort the n values, count to position ceil(p/100 × n), and take the value there. It always returns a message that occurred.

Chapter 1 said that twenty messages cannot support a tail percentile. Two hundred can, with an interval beside it, and every percentile in this chapter states its count, n. A percentile of seven messages is a different kind of number from one of 200, and the output shows which.

The rule has a consequence at the top of the list. On 200 values the 99th percentile is the value at position 198, which is the third largest, not the second. The output prints the rule on the values 1 to 200 so that the position is visible.

Predict before you run it. How many messages does a route need before its 95th percentile is anything but its slowest message? Work it from ceil(0.95 × n), then check the output.

percentiles-by-route.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 合格
"""Print each route's median, p95 and p99 of message time on baseline day 1, every one with its message count n, and a 95%interval on each p95. Percentiles are nearest rank: the value at position ceil(p/100 x n). The interval is a bootstrap overmessages, 2,000 resamples, seed 20261207. A route with fewer than 20 messages has its p95 at its largest message, which theexample prints and asserts."""from lib.dayrun import run_dayfrom lib.report import fmt_int, fmt_msfrom lib.stats import bootstrap_interval, nearest_rankfrom collections import defaultdictruns = run_day("2026-12-08")by_route = defaultdict(list)for run in runs:    by_route[run.outcome.route].append(run.replied_ns - run.arrived_ns)   # the message's time on the virtual clocktimes = [run.replied_ns - run.arrived_ns for run in runs]groups = {"all routes": times, **by_route}intervals = {}print("interval method: bootstrap over messages, 2,000 resamples, seed 20261207, 95%")print("p99 of the values 1 to 200 (n = 200), nearest rank:", nearest_rank(list(range(1, 201)), 99))assert nearest_rank(list(range(1, 201)), 99) == 198   # the 198th value, the third largest of 200print("fewest values before the p95 is not the largest, nearest rank:",      next(n for n in range(1, 201) if nearest_rank(list(range(1, n + 1)), 95) != n))for name in ["all routes"] + sorted(by_route):    values = groups[name]    low, high = bootstrap_interval(values, lambda units: nearest_rank(units, 95))    intervals[name] = (low, high)    print(f"{name}, messages (n): {fmt_int(len(values))}")    print(f"{name}, median: {fmt_ms(nearest_rank(values, 50))}")    print(f"{name}, p95: {fmt_ms(nearest_rank(values, 95))}")    print(f"{name}, p95, 95% interval: {fmt_ms(low)} to {fmt_ms(high)}")    print(f"{name}, p99: {fmt_ms(nearest_rank(values, 99))}")small = [name for name in sorted(by_route) if len(by_route[name]) < 20]print("routes under 20 messages, count:", len(small))print("routes under 20 messages, p95 is their largest message:", ", ".join(small))for name in small:    assert nearest_rank(by_route[name], 95) == max(by_route[name])   # ceil(0.95 n) = n for every n up to 19assert len(times) == len(runs) == 200# Two routes' p95 intervals overlap, so the largest p95 cannot be told apart from the next one with this many messages.low_m, high_m = intervals["messages"]low_c, high_c = intervals["calendar"]assert low_m <= high_c and low_c <= high_m
出力python percentiles-by-route.py
interval method: bootstrap over messages, 2,000 resamples, seed 20261207, 95%
p99 of the values 1 to 200 (n = 200), nearest rank: 198
fewest values before the p95 is not the largest, nearest rank: 20
all routes, messages (n): 200
all routes, median: 8,099.3 ms
all routes, p95: 18,351.2 ms
all routes, p95, 95% interval: 16,452.7 ms to 20,909.8 ms
all routes, p99: 22,425.7 ms
alarms, messages (n): 16
alarms, median: 12,159.5 ms
alarms, p95: 22,425.7 ms
alarms, p95, 95% interval: 15,757.0 ms to 22,425.7 ms
alarms, p99: 22,425.7 ms
calendar, messages (n): 27
calendar, median: 12,519.8 ms
calendar, p95: 20,909.8 ms
calendar, p95, 95% interval: 14,623.8 ms to 24,305.8 ms
calendar, p99: 24,305.8 ms
devices, messages (n): 17
devices, median: 12,510.2 ms
devices, p95: 17,417.9 ms
devices, p95, 95% interval: 14,532.9 ms to 17,417.9 ms
devices, p99: 17,417.9 ms
fallback, messages (n): 89
fallback, median: 1,392.0 ms
fallback, p95: 1,726.6 ms
fallback, p95, 95% interval: 1,636.7 ms to 3,108.1 ms
fallback, p99: 3,191.4 ms
lists, messages (n): 13
lists, median: 13,786.6 ms
lists, p95: 17,183.7 ms
lists, p95, 95% interval: 14,842.4 ms to 17,183.7 ms
lists, p99: 17,183.7 ms
media, messages (n): 31
media, median: 12,708.9 ms
media, p95: 16,452.7 ms
media, p95, 95% interval: 14,786.5 ms to 18,351.2 ms
media, p99: 18,351.2 ms
messages, messages (n): 7
messages, median: 19,793.3 ms
messages, p95: 24,253.7 ms
messages, p95, 95% interval: 21,244.6 ms to 24,253.7 ms
messages, p99: 24,253.7 ms
routes under 20 messages, count: 4
routes under 20 messages, p95 is their largest message: alarms, devices, lists, messages
演習 7.3

p95 が最大メッセージとなるルートを挙げる

+10 件の検証

例の33行目は空白である。small に、23行目が求める件数よりメッセージ数が少ないルートを、24行目と同じ順序であるソート順で格納するように、この行を書け。

    print(f"{name}, p95: {fmt_ms(nearest_rank(values, 95))}")    print(f"{name}, p95, 95% interval: {fmt_ms(low)} to {fmt_ms(high)}")    print(f"{name}, p99: {fmt_ms(nearest_rank(values, 99))}")print("routes under 20 messages, count:", len(small))print("routes under 20 messages, p95 is their largest message:", ", ".join(small))for name in small:
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 で実行される
演習 7.4

小さなルートの区間の上端がp95で頭打ちになる理由を説明する

+10 件の検証

alarmsルートの95%区間は、95パーセンタイルと同じ値で終わっている。これを説明しているのはどれか。

小さなルートの区間の上端がp95で頭打ちになる理由を説明する:正しい説明を選ぶ
Python 3.13.16 で実行される

The output gives each route's median, 95th and 99th percentile, each with its count, and a 95% interval on each 95th percentile. A route needs at least 20 messages before its 95th percentile is anything but its largest. 4 routes have fewer than 20 messages, alarms, devices, lists, messages, and for each one the 95th percentile is its slowest message.

The messages route's 95th percentile is 24,253.7 ms from 7 messages, with a 95% interval of 21,244.6 ms to 24,253.7 ms whose top is the same value. Its last answer calls are the longest of the answering routes at the median, at 13,865.7 ms. The output does not say why its tail is long.

The all-routes median, 8,099.3 ms, is lower than the median of every route that answered. The reason is the fallback route. 89 of the 200 messages took the fallback reply, which makes one route call and no answer call, and their median is 1,392.0 ms. The all-routes median is the middle value of all the messages, so those messages pull it down.

figure-latency-tail-by-route.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 route's median and p95 of message time on baseline day 1, with a 95% interval on the p95, so the tail's placein each route shows at a glance. Every value the figure draws is printed first, with its message count n. The intervalis a bootstrap over messages (2,000 resamples, seed 20261207); the route is the one the assistant chose."""from lib.dayrun import run_dayfrom lib.figures import ACCENT, INK, MUTED, new_figure, savefrom lib.report import fmt_int, fmt_msfrom lib.stats import bootstrap_interval, nearest_rankfrom collections import defaultdictruns = run_day("2026-12-08")times = {"all routes": [run.replied_ns - run.arrived_ns for run in runs]}for run in runs:    times.setdefault(run.outcome.route, []).append(run.replied_ns - run.arrived_ns)names = ["all routes"] + sorted(name for name in times if name != "all routes")summary = []for name in names:    values = times[name]    low, high = bootstrap_interval(values, lambda units: nearest_rank(units, 95))    summary.append((name, len(values), nearest_rank(values, 50), nearest_rank(values, 95), low, high))    print(f"{name}, messages (n): {fmt_int(len(values))}")    print(f"{name}, median: {fmt_ms(summary[-1][2])}")    print(f"{name}, p95: {fmt_ms(summary[-1][3])}, interval: {fmt_ms(low)} to {fmt_ms(high)}")fig, ax = new_figure(height=3.8)rows = list(range(len(summary)))[::-1]                 # the first row, all routes, at the topfor row, (name, count, median, p95, low, high) in zip(rows, summary):    ax.hlines(row, low / 1e6, high / 1e6, color=MUTED, linewidth=3, label="95% interval of the p95" if row == rows[0] else None)    ax.scatter([median / 1e6], [row], facecolors="none", edgecolors=INK, linewidths=1.4, s=52, zorder=3,               label="median" if row == rows[0] else None)     # a hollow circle, so the two dots differ in shape as well as colour    ax.scatter([p95 / 1e6], [row], color=ACCENT, marker="D", s=44, zorder=3, label="p95" if row == rows[0] else None)ax.set_yticks(rows, [f"{name} (n = {count})" for name, count, *_ in summary])ax.set_xlabel("message time, milliseconds")ax.set_xlim(0, 30000)ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.22), ncol=3)   # below the axis, clear of every rowsave(fig, "latency-tail-by-route")
出力python figure-latency-tail-by-route.py
all routes, messages (n): 200
all routes, median: 8,099.3 ms
all routes, p95: 18,351.2 ms, interval: 16,452.7 ms to 20,909.8 ms
alarms, messages (n): 16
alarms, median: 12,159.5 ms
alarms, p95: 22,425.7 ms, interval: 15,757.0 ms to 22,425.7 ms
calendar, messages (n): 27
calendar, median: 12,519.8 ms
calendar, p95: 20,909.8 ms, interval: 14,623.8 ms to 24,305.8 ms
devices, messages (n): 17
devices, median: 12,510.2 ms
devices, p95: 17,417.9 ms, interval: 14,532.9 ms to 17,417.9 ms
fallback, messages (n): 89
fallback, median: 1,392.0 ms
fallback, p95: 1,726.6 ms, interval: 1,636.7 ms to 3,108.1 ms
lists, messages (n): 13
lists, median: 13,786.6 ms
lists, p95: 17,183.7 ms, interval: 14,842.4 ms to 17,183.7 ms
media, messages (n): 31
media, median: 12,708.9 ms
media, p95: 16,452.7 ms, interval: 14,786.5 ms to 18,351.2 ms
messages, messages (n): 7
messages, median: 19,793.3 ms
messages, p95: 24,253.7 ms, interval: 21,244.6 ms to 24,253.7 ms
figure: figures/latency-tail-by-route.svg
050001000015000200002500030000message time, millisecondsall routes (n = 200)alarms (n = 16)calendar (n = 27)devices (n = 17)fallback (n = 89)lists (n = 13)media (n = 31)messages (n = 7)95% interval of the p95medianp95
図 7.1 Each route's median and 95th percentile of message time on baseline day 1, with a 95% interval on the 95th percentile

図 7.1 draws each route's median and 95th percentile, with the interval on the 95th percentile as a bar. The top row is all routes together. Read the answering routes' bars against one another. Most of their intervals overlap, and the messages interval overlaps calendar's, as the example asserts. The 4 routes under 20 messages have bars that end at their own largest message. The fallback bar is far shorter than the rest. So the tail depends on whether the route answers, and the count decides how sure the reader can be of where a route's tail sits.

The interval is a percentile bootstrap, and this is the one place the chapter builds it. An interval says how far a number would move had the day brought other messages drawn the same way; here, the middle 95% of 2,000 bootstrap resamples of messages. The question behind it is whether another day's 95th percentile would be the same. The interval answers that only for a day drawn the same way. A different day, a release or a load lies outside what it covers.

For each route, the code draws as many messages as the route has, with replacement, takes the 95th percentile of that resample, and repeats the draw 2,000 times with the seed 20261207. The interval is the 50th and the 1,950th of the 2,000 results, which bracket 95% of them. Efron introduced the bootstrap in 1979, and Evaluating LLM Applications uses the same method over items. Here the unit is the message, not the span, because the spans of one message are not independent of one another.

The same bootstrap applies to any statistic taken per message, such as the share of the day's cost that the most expensive messages carry in chapter 6. Under 20 messages, though, the 95th percentile of every resample is one of the route's own messages, and the largest of them is the top of the interval. The interval cannot reach past the messages it came from. So for each of the 4 routes under 20 messages, the upper end is its own largest message, the upper end and the point estimate are one value, and the interval's width measures the resampling, not what those few messages leave out.

Working rule: Print each percentile with its count and its interval, and rank two routes only when their intervals do not overlap. Collect more messages before you name a tail.

ヒストグラムのバケットが隠すもの

ヒストグラムはメッセージそのものを保持せず、件数だけを保持する。バケットは二つの境界の間にある値の件数を数える。したがって、バケットから読み取るパーセンタイルは、そのバケットの範囲内でしか分からない。タグ 0.1.0 の GenAI 規約は、所要時間のヒストグラムの境界を、エージェントの gen_ai.client.invoke_agent.duration を含めて、秒単位で次のようにすることを推奨している(SHOULD)。本書ではこれをメッセージ時間、すなわちこの章が測る所要時間に用いる。境界は 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92 である。サービスは設定で定めた境界をエクスポートするため、それがこの値と異なる場合もある。

bucket-edges-hide-tail.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 合格
"""Count baseline day 1's message times into the buckets the GenAI conventions advise for the agent's duration histogram, thenestimate the p95 from the bucket counts and set it beside the nearest-rank p95 of the raw values. The estimate spreads eachbucket's values evenly across it, and the p95 falls in one bucket, so the buckets can only place the estimate inside it."""from lib import genaifrom lib.dayrun import run_dayfrom lib.report import fmt_int, fmt_ms, fmt_sharefrom lib.stats import bucket_counts, nearest_rankimport mathEDGES_S = genai.BUCKETS["gen_ai.client.invoke_agent.duration"]   # the conventions' advised upper bounds, in secondsprint("GenAI conventions version:", genai.REGISTRY_VERSION)print("bucket boundaries, GenAI conventions, seconds:", ", ".join(str(edge) for edge in EDGES_S))runs = run_day("2026-12-08")times = [run.replied_ns - run.arrived_ns for run in runs]n = len(times)edges = [round(edge * 1_000_000_000) for edge in EDGES_S]      # integer nanoseconds, as every time here iscounts = bucket_counts(times, edges)                           # a value sits in the bucket whose upper edge it does not exceedprint("messages (n):", fmt_int(n))for index, count in enumerate(counts):    low = edges[index - 1] if index else 0                     # a bucket starts at the upper edge of the one before it    if index < len(edges):        print(f"bucket above {fmt_ms(low)} up to {fmt_ms(edges[index])}: {fmt_int(count)} messages, {fmt_share(count, n)}")    else:        print(f"bucket above {fmt_ms(low)}: {fmt_int(count)} messages, {fmt_share(count, n)}")exact = nearest_rank(times, 95)rank = math.ceil(95 * n / 100)                                 # the nearest-rank position of the p95index = next(i for i, edge in enumerate(edges) if exact <= edge)   # the bucket that holds the exact p95low = edges[index - 1] if index else 0                         # its lower edge, as above; the first starts at zerobelow = sum(counts[:index])                                    # messages in the buckets under itestimate = low + round((rank - below) * (edges[index] - low) / counts[index])print("bucket holding the p95, lower edge:", fmt_ms(low))print("bucket holding the p95, upper edge:", fmt_ms(edges[index]))print("messages in that bucket:", fmt_int(counts[index]))print("messages at or below its lower edge:", fmt_int(below))print("p95, nearest rank of the raw values:", fmt_ms(exact))print("p95, estimated from the bucket counts:", fmt_ms(estimate))print("estimate minus the nearest-rank p95:", fmt_ms(estimate - exact))assert low < exact <= edges[index]                             # the exact p95 lies in the bucket that holds itassert abs(estimate - exact) > 500_000_000                     # the bucket estimate is more than half a second off
出力python bucket-edges-hide-tail.py
GenAI conventions version: 0.1.0
bucket boundaries, GenAI conventions, seconds: 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92
messages (n): 200
bucket above 0.0 ms up to 10.0 ms: 0 messages, 0.0%
bucket above 10.0 ms up to 20.0 ms: 0 messages, 0.0%
bucket above 20.0 ms up to 40.0 ms: 0 messages, 0.0%
bucket above 40.0 ms up to 80.0 ms: 0 messages, 0.0%
bucket above 80.0 ms up to 160.0 ms: 0 messages, 0.0%
bucket above 160.0 ms up to 320.0 ms: 0 messages, 0.0%
bucket above 320.0 ms up to 640.0 ms: 0 messages, 0.0%
bucket above 640.0 ms up to 1,280.0 ms: 21 messages, 10.5%
bucket above 1,280.0 ms up to 2,560.0 ms: 65 messages, 32.5%
bucket above 2,560.0 ms up to 5,120.0 ms: 3 messages, 1.5%
bucket above 5,120.0 ms up to 10,240.0 ms: 16 messages, 8.0%
bucket above 10,240.0 ms up to 20,480.0 ms: 89 messages, 44.5%
bucket above 20,480.0 ms up to 40,960.0 ms: 6 messages, 3.0%
bucket above 40,960.0 ms up to 81,920.0 ms: 0 messages, 0.0%
bucket above 81,920.0 ms: 0 messages, 0.0%
bucket holding the p95, lower edge: 10,240.0 ms
bucket holding the p95, upper edge: 20,480.0 ms
messages in that bucket: 89
messages at or below its lower edge: 105
p95, nearest rank of the raw values: 18,351.2 ms
p95, estimated from the bucket counts: 20,019.8 ms
estimate minus the nearest-rank p95: 1,668.6 ms
演習 7.5

パーセンタイルを含むバケットを選ぶ

+10 件の検証

このコピーでは30行目が空白になっている。19行目のコメントが述べる規則を用いて、index が正確な95パーセンタイルを含むバケットになるように30行目を書け。

exact = nearest_rank(times, 95)rank = math.ceil(95 * n / 100)                                 # the nearest-rank position of the p95low = edges[index - 1] if index else 0                         # its lower edge, as above; the first starts at zerobelow = sum(counts[:index])                                    # messages in the buckets under itestimate = low + round((rank - below) * (edges[index] - low) / counts[index])
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日目の同じメッセージをこれらのバケットに数え入れ、件数から95パーセンタイルを推定し、その推定値を生のメッセージの最近順位法(nearest-rank)の値と並べて示す。95パーセンタイルを含むバケットは 10,240.0 ms から 20,480.0 ms までである。このバケットには 89 件のメッセージがあり、その下側の境界以下には 105 件のメッセージがある。

バケットから分かるのは、95パーセンタイルがそれらの境界の間にあることまでであり、それ以上は絞り込めない。推定では、バケット内のメッセージがバケット全体に一様に散らばっているものとみなす。これは Prometheus がバケットからパーセンタイルを推定する方法 の規則であり、バケット内の分布を線形と仮定している。他のバックエンドは異なる補間をする場合があり、境界が変われば推定値も動く。ここでは推定値が 20,019.8 ms、生のメッセージの最近順位法の値が 18,351.2 ms であり、この日の推定値は 1,668.6 ms 高すぎる。

figure-bucket-hides-tail.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 baseline day 1's message times twice, on one millisecond scale: each message as a point in the upper panel, and thebucket counts for the same messages in the lower panel, each bucket drawn across the span it covers. The edges are the onesbucket-edges-hide-tail uses. Every value the figure shows is printed first, and the nearest-rank p95 is drawn as a line."""from lib import genaifrom lib.dayrun import run_dayfrom lib.figures import ACCENT, INK, MUTED, new_figure, savefrom lib.report import fmt_int, fmt_ms, fmt_sharefrom lib.stats import bucket_counts, nearest_rankEDGES_S = genai.BUCKETS["gen_ai.client.invoke_agent.duration"]  # the conventions' advised upper bounds, in seconds, as thereruns = run_day("2026-12-08")times = sorted(run.replied_ns - run.arrived_ns for run in runs)n = len(times)edges = [round(edge * 1_000_000_000) for edge in EDGES_S]      # integer nanoseconds, as every time here iscounts = bucket_counts(times, edges)exact = nearest_rank(times, 95)lows = [0] + edges                                             # each bucket starts at the edge before itprint("messages (n):", fmt_int(n))for number, count in enumerate(counts):    if number < len(edges):        print(f"bucket above {fmt_ms(lows[number])} up to {fmt_ms(edges[number])}: {fmt_int(count)} messages, {fmt_share(count, n)}")    else:        print(f"bucket above {fmt_ms(lows[number])}: {fmt_int(count)} messages, {fmt_share(count, n)}")print("p95, nearest rank of the raw values:", fmt_ms(exact))fig, (top, bottom) = new_figure(rows=2, height=4.6, sharex=True)top.scatter([t / 1e6 for t in times], [(i + 1) / n for i in range(n)], s=10, color=INK, label="each message")for edge in edges:    top.axvline(edge / 1e6, color=MUTED, linestyle=":", linewidth=0.8)top.axvline(exact / 1e6, color=ACCENT, linestyle="--", linewidth=1.2, label="p95, nearest rank")top.set_ylabel("share at or below")top.legend(loc="lower right")highs = edges + [edges[-1] + 10_000_000_000]                   # the last bucket is open; drawn 10 s wide, past the axiscentres = [(lo + hi) / 2 / 1e6 for lo, hi in zip(lows, highs)]widths = [(hi - lo) / 1e6 for lo, hi in zip(lows, highs)]bars = bottom.bar(centres, counts, width=widths, color=MUTED)bottom.bar_label(bars, labels=[fmt_int(c) if c else "" for c in counts], padding=2)   # empty buckets carry no labelbottom.set_xticks([e / 1e6 for e in edges], [f"{e / 1e6:,.0f}" if e >= 10_240_000_000 else "" for e in edges])   # the small edges crowd the leftbottom.set_ylabel("messages")bottom.set_xlim(0, 42000)                                      # set after the ticks, which would widen itbottom.set_ylim(0, max(counts) * 1.15)bottom.set_xlabel("message time, milliseconds; bucket edges as ticks")save(fig, "bucket-hides-tail")
出力python figure-bucket-hides-tail.py
messages (n): 200
bucket above 0.0 ms up to 10.0 ms: 0 messages, 0.0%
bucket above 10.0 ms up to 20.0 ms: 0 messages, 0.0%
bucket above 20.0 ms up to 40.0 ms: 0 messages, 0.0%
bucket above 40.0 ms up to 80.0 ms: 0 messages, 0.0%
bucket above 80.0 ms up to 160.0 ms: 0 messages, 0.0%
bucket above 160.0 ms up to 320.0 ms: 0 messages, 0.0%
bucket above 320.0 ms up to 640.0 ms: 0 messages, 0.0%
bucket above 640.0 ms up to 1,280.0 ms: 21 messages, 10.5%
bucket above 1,280.0 ms up to 2,560.0 ms: 65 messages, 32.5%
bucket above 2,560.0 ms up to 5,120.0 ms: 3 messages, 1.5%
bucket above 5,120.0 ms up to 10,240.0 ms: 16 messages, 8.0%
bucket above 10,240.0 ms up to 20,480.0 ms: 89 messages, 44.5%
bucket above 20,480.0 ms up to 40,960.0 ms: 6 messages, 3.0%
bucket above 40,960.0 ms up to 81,920.0 ms: 0 messages, 0.0%
bucket above 81,920.0 ms: 0 messages, 0.0%
p95, nearest rank of the raw values: 18,351.2 ms
figure: figures/bucket-hides-tail.svg
0.00.20.40.60.81.0share at or beloweach messagep95, nearest rank10,24020,48040,960message time, milliseconds; bucket edges as ticks020406080100messages2165316896
図 7.2 ベースライン1日目のメッセージを点とバケットの件数で表し、95パーセンタイルを破線で示した図

図 7.2 は、同じメッセージをミリ秒の同一目盛りで2回描いている。上のパネルは、各メッセージをそれ以下のメッセージの割合の位置に打つため、点は右上がりになる。点線はバケットの境界で、破線は最近順位法による95パーセンタイルである。下のパネルは各バケットの件数を、そのバケットが覆う範囲にわたって描いている。95パーセンタイルの線は幅の広いバケットの内側に入り、下のパネルにはそのバケットのどこにメッセージがあるかを示すものがない。これがバケットで失われる情報であり、推定値がずれる理由である。

実践ルール: バケットの境界は、これから問う問いに基づいて決め、アラートの閾値ごとにその近くに境界を置く。パーセンタイルが幅の広いバケットの内側に入るときは、ミリ秒単位の推定値ではなく、そのバケットとその件数を報告し、可能な限り生の値を保持する。バケットからの推定値は、ある一組の境界に一つの規則を当てはめたものであり、境界が動けば推定値も動く。

記録されたサービス時間に基づく待ち行列

メッセージの所要時間は、そのメッセージ自身の処理だけで決まるわけではない。モデルが別のメッセージを処理している間にメッセージが到着すると、そのメッセージは待たされ、その待ち時間もユーザーが目にする時間の一部となる。待ち行列を用いると、この待ち時間が負荷とともにどのように増えるかを示せる。到着したメッセージは列に加わり、サーバーは一度に1件のメッセージだけを処理する。負荷とは、到着したメッセージが要求するサーバー時間の割合である。

この節の数値は記録されたものではなく、計算されたものである。コードは1台のサーバーをモデル化している。到着はランダムに起こり、その平均到着率は負荷によって定まる固定値である。これはポアソン過程であり、到着間隔は互いに独立で、指数分布に従ってばらつく。各メッセージのサービス時間には、その日に記録されたメッセージ時間のうちの1つを、復元抽出で選んで用いる。リトルの法則によれば、系内の平均個数は、到着率と各項目が系内で過ごす平均時間との積に等しい。すなわち L = λW である。Little による1961年の証明がこれを確立しており、M/M/1待ち行列に関するMITの講義ノートが、ここで用いる形でこれを述べている。

queue-on-service-times.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 合格
"""Queue baseline day 1's recorded message times behind one first-come, first-served server at three loads, with seeded Poissonarrivals and each message's service drawn from the recorded times. The number in system is walked from the queue's events andchecked against the arrival rate times the time in system, and the last check compares exponential service with the M/M/1 formula."""from lib.dayrun import run_dayfrom lib.report import fmt_int, fmt_msfrom lib.stats import nearest_rankfrom fractions import Fractionimport numpy as npSEED, N, CHECK_N = 20261208, 50_000, 200_000                   # one seed; messages per run; the M/M/1 check's runrecorded = [run.replied_ns - run.arrived_ns for run in run_day("2026-12-08")]   # the day's 200 recorded message timesmean_service = sum(recorded) / len(recorded)recorded_services = lambda rng, n: rng.choice(np.asarray(recorded, dtype=np.int64), n)   # resampled with replacementexponential_services = lambda rng, n: rng.exponential(mean_service, n).round().astype(np.int64)def simulate(rng, rho, n, services):    """Serve n messages arriving at rate rho / mean_service. Returns arrivals, waits, times in system, the last finish    and the total service time, in ns."""    arrivals = np.cumsum(rng.exponential(mean_service / rho, n)).round().astype(np.int64).tolist()    finish, waits, sojourn, busy = 0, [], [], 0    for arrive, serve in zip(arrivals, services(rng, n).tolist()):        start = max(arrive, finish)          # the server finishes the message before it, then starts this one        finish = start + serve        waits.append(start - arrive)        sojourn.append(finish - arrive)        busy += serve    return arrivals, waits, sojourn, finish, busyprint("mean recorded message time:", fmt_ms(round(mean_service)))for rho in (0.5, 0.8, 0.9):    arrivals, waits, sojourn, finish, busy = simulate(np.random.Generator(np.random.PCG64(SEED)), rho, N, recorded_services)    span = finish - arrivals[0]                                # first arrival to last departure    # Each arrival adds one to the count in system and each departure takes one away; the area under the count is L times the span.    area, count, when = 0, 0, arrivals[0]    for moment, step in sorted([(a, 1) for a in arrivals] + [(a + s, -1) for a, s in zip(arrivals, sojourn)]):        area, count, when = area + count * (moment - when), count + step, moment    number, rate_times_time = Fraction(area, span), Fraction(N, span) * Fraction(sum(sojourn), N)   # L, and lambda W    print(f"load {rho}, utilisation, computed: {busy / span:.2f}")    print(f"load {rho}, wait before service, computed, p95 (n = {fmt_int(N)}):", fmt_ms(nearest_rank(waits, 95)))    print(f"load {rho}, number in system, time average, computed: {float(number):.2f}")    print(f"load {rho}, arrival rate times time in system, computed: {float(rate_times_time):.2f}")    assert number == rate_times_time     # exact, with no tolerance: the window starts at the first arrival and ends at the last departure# M/M/1: the mean time in system is 1 / (mu - lambda), which is mean_service / (1 - rho) for exponential service.sojourn = simulate(np.random.Generator(np.random.PCG64(SEED)), 0.8, CHECK_N, exponential_services)[2]simulated, formula = sum(sojourn) / CHECK_N, mean_service / (1 - 0.8)print(f"exponential service, load 0.8, mean time in system, simulated (n = {fmt_int(CHECK_N)}):", fmt_ms(round(simulated)))print("exponential service, load 0.8, mean time in system, formula:", fmt_ms(round(formula)))assert abs(simulated - formula) / formula < 0.02
出力python queue-on-service-times.py
mean recorded message time: 8,019.0 ms
load 0.5, utilisation, computed: 0.50
load 0.5, wait before service, computed, p95 (n = 50,000): 27,983.0 ms
load 0.5, number in system, time average, computed: 0.91
load 0.5, arrival rate times time in system, computed: 0.91
load 0.8, utilisation, computed: 0.80
load 0.8, wait before service, computed, p95 (n = 50,000): 82,817.5 ms
load 0.8, number in system, time average, computed: 3.31
load 0.8, arrival rate times time in system, computed: 3.31
load 0.9, utilisation, computed: 0.90
load 0.9, wait before service, computed, p95 (n = 50,000): 179,463.5 ms
load 0.9, number in system, time average, computed: 7.26
load 0.9, arrival rate times time in system, computed: 7.26
exponential service, load 0.8, mean time in system, simulated (n = 200,000): 40,422.0 ms
exponential service, load 0.8, mean time in system, formula: 40,094.8 ms

出力は負荷0.5、0.8、0.9の場合を、いずれも同じシードで扱い、そのうえで公式が存在する場合について確認をもう1つ行う。記録されたメッセージ時間の平均は 8,019.0 ms であり、これは各メッセージが平均して要するサービス時間である。負荷0.5のときのサーバー利用率は 0.50 である。

サービス開始前の待ち時間の95パーセンタイルは、負荷0.5で 27,983.0 ms、0.8で 82,817.5 ms、0.9で 179,463.5 ms である。待ち時間は負荷よりも急な勾配で増加する。

系内の個数も同じ曲線をたどる。負荷0.8では平均 3.31 であり、到着率と系内時間の積は 3.31 となる。コードは、前者を時間にわたる待ち行列のイベントから求め、後者を到着率と平均系内時間から求める。そして、すべての負荷においてこの両者が等しいことをアサートする。最初の到着から最後の退去までを区間とするサンプルパスでは、リトルの法則は厳密に成り立つので、このアサートは許容誤差を設けていない。

M/M/1の公式、すなわち指数サービスをもつ1台のサーバーにおける平均系内時間は、サービス時間が指数分布に従う場合にのみ厳密であり、記録された時間は指数分布ではない。そこでコードは、まずシミュレーションをそれ自身の条件で検証する。負荷0.8、200,000件のメッセージで指数サービスとしたとき、シミュレーションによる平均系内時間は 40,422.0 ms であり、公式による値は 40,094.8 ms である。コードは、両者が2%以内で一致することをアサートする。任意のサービス分布をもつ1台のサーバーであるM/G/1には、それ独自の平均の公式があるが、この章ではその確認を省く。

これは1台のサーバーのモデルであり、Ambrewickの実運用環境のモデルではない。各メッセージの記録された時間の全体を1回のサービスとして扱うのは、待ち行列がメッセージを扱う方法そのものである。また、到着はその日の実際の到着時刻を無視している。したがって、ここでの待ち時間は、このメッセージの組合せに対して1台のサーバーが示すものであり、その日に実際に起きたものではない。

実践ルール: 裾の値を受け入れる前、あるいは容量を追加する前に、想定する負荷と、それより高い負荷の両方で待ち行列を読むこと。サービス時間の記録があるときはそれを用い、シミュレーションが計算したすべての数値に、計算値であることを明示し、公式の前提が成り立つ場合に限ってシミュレーションを公式と照合すること。

本番環境で何がうまくいかなくなるか

これらの数値がリプレイの外に出ると、三つの点が変わる。第一に、本番のスパンには隙間が生じる。記録された呼び出し間の隙間は、一日を通して合計 651.4 ms になる。この隙間はメッセージの中の実際の時間であるが、どのスパンにも属さない。そのため、スパンから組み立てたクリティカルパスは、メッセージの全時間より短い範囲しか覆わないことがある。パスの占める割合はメッセージの時間と並べて読み、割合が低い場合は答えではなく、トレースに対する問いとして扱うこと。

第二に、サービスが出力するヒストグラムの境界は、その設定が定めたものであり、規約が推奨するものとは限らない。バケットから読み取ったパーセンタイルには、その境界による誤差が加わる。この日のメッセージに対するバケットの推定値がそれを示している。第9章ではこれらのレイテンシに対して目標を設定するので、境界もその判断の対象に含まれる。

第三に、一日あたりのメッセージ数が少ないルートの95パーセンタイルには、広い区間が付く。点の値だけを表示するダッシュボードは、正確であるかのように見える。件数と区間を同じパネルに載せるか、そのパーセンタイルをパネルから外すこと。

実践ルール: 本番のレイテンシの数値を公開する前に、その件数と区間を数値の横に示し、どの種類の時間であるかを明記する。種類とは、スパンの時間、バケットの推定値、リプレイの合計のいずれかである。パスの占める割合やバケットの境界が不明な場合は、数値を単独で載せず、その旨を数値とともに記す。

本章で下した判断

これらはいずれも、誤る可能性のある判断である。それぞれに理由と、その判断を検証する例を示す。

  • クリティカルパスはスパンから読み取る。重なり合う呼び出しを持つ記録済みメッセージは存在しないため、重なりのある場合は構成したツリーで示す。critical-path-one-messageは、パスが再生したメッセージ全体を覆っていることと、構成したツリーのスパン b がパス上にないことを確認する。
  • 最初のチャンクまでの時間は、同じ呼び出しの合計時間と並べて報告し、カウンタで分解する。最初のチャンクだけを単独で読むことがないようにするためである。time-to-first-chunk-by-routeとprefill-generation-splitは、同じ呼び出しについて両方を出力する。
  • パーセンタイルは最近順位法で求め、件数を添えて示す。各95パーセンタイルには、メッセージを単位とする、乱数の種を固定したブートストラップ再標本から得た区間を付す。percentiles-by-routeは、メッセージ数が20に満たず、95パーセンタイルがその最大のメッセージに一致するルートを挙げ、本文が依拠する唯一の重なりを確認する。
  • メッセージ時間の境界値には GenAI 規約が勧めるものを用いる。サービス独自の境界値は異なる場合があるため、その旨を明記する。bucket-edges-hide-tailはこの日の推定誤差を出力し、figure-bucket-hides-tailは生の値を件数と並べて描く。
  • キューのシミュレーションは、記録されたサービス時間に対してのみ行い、計算によって得た待ち行列の数値にはすべてその旨を表示する。queue-on-service-timesは、キューのイベントからシステム内の数を求め、各負荷について到着率とシステム内時間の積と照合する。M/M/1 の式は、サービス時間が指数分布の場合に限って検証する。
  • ルートの裾の順位付けは、区間が重ならない場合に限って行う。1日分のメッセージでは、それらの順序を決められないためである。この日については、応答するルートの大半が順序付けられないままとなる。したがって、確かな差は、ルートが応答するかどうかであり、応答するルートのうちどれが最も裾が悪いかではない。

この版における本章

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

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

Labs を開始

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

料金を見る

この節を引用する

形式

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

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

このページの内容

全12章中の第7章: 遅延の発生源を見つける

  1. クリティカルパスが終了時刻を決める
  2. Time to first chunk
  3. プレフィルと生成
  4. Retrieved context against prefill
  5. Tail percentiles with intervals
  6. ヒストグラムのバケットが隠すもの
  7. 記録されたサービス時間に基づく待ち行列
  8. 本番環境で何がうまくいかなくなるか
  9. 本章で下した判断

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