失敗したステップを見つける

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

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

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

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

Labs

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

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

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

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

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

Lab を確認しています…

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

この章を終えると、メッセージのどのステップが失敗したのか、その頻度、そして理由を突き止め、各件数をその元になった行とともに出力できるようになる。このケースは問いを率直に立てる。有用な回答を得られなかったユーザーは、ログからその理由を知ることができない。ルーターがリクエストを誤ったルートやフォールバック応答へ送ったのかもしれない。モデルがパーサーの読めないツール呼び出しを書いたのかもしれず、トークン上限で途切れた応答を返したのかもしれない。連絡先サーバーがエラーを返したのかもしれず、まったく応答を返さなかったのかもしれない。これらのうちどれが起きたのか、そしてその頻度はどれほどか。

基準日1は、実際の応答からこの頻度の問いに答える。そのメッセージ 200 件のうち、誤ったルートへ送られたのは 41 件であり、エラーで終わったスパンは1つもない。これらがその日の実際の失敗である。障害日にはもう1種類の集計が必要になる。障害日の故障は人為的に注入したものだからである。注入したのは、連絡先サーバーの応答が遅すぎる時間帯、モデルがすべてのリクエストを拒否する時間帯、連絡先サーバーがエラー結果を返す時間帯の3つである。注入した故障にはそれぞれラベルを付け、その件数は専用の行に置き、基準日1の比率に混ぜることはない。注入した件数を出力する表はすべてそのラベルを繰り返して示す。障害日の出来事は、どれも実際の障害ではない。

リプレイは リプレイと仮想クロック の仮想クロック上で実行する。このケースのトラフィックは本書のために生成したものであり、ここでの比率は本書独自のもので、いかなるサービスも表さない。

この章では、スパンが記録するステータスから誤ったルートまで、失敗モードごとに1つのクエリを組み立てる。

スパンが失敗を記録する方法

スパンは、その結果をステータスに記録する。規約は、操作がエラーで終わったときにインストゥルメンテーションがステータスを Error に設定し、問題がなかったときは未設定のままにすることを求めている(recording errors、v1.45.0)。同じページは、失敗した操作に error.type を付けることも求めている。

スパンのステータスは、unset、ok、error のいずれかである。error.type はエラーに名前を付ける。値は、パッケージが書き出すクラス名か、レジストリに値があればその値である。これにより、失敗を種類別に数えられる。本書はレジストリにない値を新しく作らない。

同じ事柄を指す語をもう一つ使う。エラーとは、ステータスが ERROR であるスパンのことである。メッセージは、そのスパンのいずれかが ERROR であれば、エラーを持つ。これが、第10章のCI ゲートが数えるエラーである。ほかの二つの悪い結果はエラーではない。トークン上限で打ち切られた返信は品質上の所見であり、経路を示さない経路返信も同様である。どちらも以下で数えるが、どちらもスパンのステータスを設定しない。

レジストリが選択肢として挙げる値は少ない。フォールバックは _OTHER であり、タイムアウトや HTTP 429 に当たる値はない。この二つは、本章で最も多く出会う失敗である。レジストリは、予測可能でカーディナリティの低い値を求めており、timeout と 500 を、定義された値ではなく例として挙げている(error.md、v1.45.0)。そこで本書では、パッケージが送出するクラス名を書く。読み取りタイムアウトには MCPError、拒否されたモデルへのリクエストには RateLimitError、アシスタント自身の断念には ModelUnavailable を使う。レジストリの例は完全修飾名であるが、本書は短いクラス名を書く。ほかのインストゥルメンテーションは、openai インストゥルメンテーションの openai.RateLimitError のように修飾名を書く。同じスパン上のアシスタント自身の exception.type も修飾名である。注入した 429 は、本書の RateLimitError を送出する。これは、同名のクライアント例外の代役である。したがってこの値は本書のものであり、クライアント自身の例外を使うデプロイでは、同じ場所に別のクラス名が現れる。

例外はステータスとは別に記録される。OpenTelemetry Python SDK(本書では 1.45.2)が例外を記録すると、スパンに exception イベントを追加し、ステータスは未設定のままにする。スパンを包む二つのヘルパー、start_as_current_span と use_span は、この点の例外である。例外がこれらから外へ抜けると、既定でステータスも ERROR に設定する。recording-errors のページは別の記録先を求めており、操作を失敗させた例外はログレコードとして記録すべきだとしている。本書は、レシーバーがスパンを保持している間は、SDK のイベントを使い続けることを勧める。本章のクエリはすべてスパンを読み、件数はステータスに依存するからである。ログパイプラインを持つデプロイは、ステータスと error.type が引き続きスパンに届くかぎり、もう一方の方法を取ってもよい。

error-status-by-step.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 合格
"""Which spans end with ERROR, and what error.type each carries, on the incident day (injected, labelled) and on baselineday 1 (real). The point rests on the baseline's zero ERROR spans: a wrong route is not a span error, so the status cannotfind it, and the incident's faults look alike from outside."""from collections import Counterfrom lib.dayrun import run_day_tracedfrom lib.report import fmt_intreal = run_day_traced("2026-12-08", live=False)  # baseline day 1, replayed: no fault is injected into itreal_errors = [row for row in real.spans if row["status"] == "ERROR"]print("real ERROR spans, baseline day 1 (4B):", fmt_int(len(real_errors)))assert not real_errors  # the baseline's failures are wrong routes and fallback replies, which set no span statuslive = run_day_traced("2026-12-09")  # live: the contacts server runs the injected faults over stdiorows = live.spans + live.servererrors = [row for row in rows if row["status"] == "ERROR"]print("ERROR spans, incident day (injected):", fmt_int(len(errors)))# Each injected fault labels every span it touches, so the label itself tells an injected error from a real one.assert all(row["attributes"].get("ambrewick.incident.injected") for row in errors)  # every ERROR span is injectedcounts = Counter((row["name"], row["attributes"].get("error.type", "none")) for row in errors)for (name, error_type), count in sorted(counts.items()):    print(f"{name}, error.type {error_type}, injected: {count}")
出力python error-status-by-step.py
real ERROR spans, baseline day 1 (4B): 0
ERROR spans, incident day (injected): 75
MCP send tools/call find_contact, error.type none, injected: 4
chat qwen3-4b-instruct-2507, error.type RateLimitError, injected: 47
contacts.lookup, error.type none, injected: 3
execute_tool find_contact, error.type MCPError, injected: 4
execute_tool find_contact, error.type tool_error, injected: 3
invoke_agent ambrewick-assistant, error.type ModelUnavailable, injected: 11
tools/call find_contact, error.type tool_error, injected: 3
演習 8.1

失敗したスパンをステータスで数える

+10 件の検証

16行目は、error.type を持つかどうかで ERROR のスパンを選んでいるため、error.type を持たない ERROR のスパンはすべて除外されてしまう。16行目を変更して、ステータスが ERROR であるスパンをすべて選ぶようにせよ。

live = run_day_traced("2026-12-09")  # live: the contacts server runs the injected faults over stdiorows = live.spans + live.serverprint("ERROR spans, incident day (injected):", fmt_int(len(errors)))# Each injected fault labels every span it touches, so the label itself tells an injected error from a real one.assert all(row["attributes"].get("ambrewick.incident.injected") for row in errors)  # every ERROR span is injected
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 で実行される
演習 8.2

エラーの種類ごとに数える(エラーのないスパンも含める)

+10 件の検証

20行目は空白のままになっている。各 ERROR スパンをスパン名とその error.type の組で数え、error.type を持たないスパンは値 none の下で数えるように、この行を書け。

print("ERROR spans, incident day (injected):", fmt_int(len(errors)))# Each injected fault labels every span it touches, so the label itself tells an injected error from a real one.assert all(row["attributes"].get("ambrewick.incident.injected") for row in errors)  # every ERROR span is injectedfor (name, error_type), count in sorted(counts.items()):    print(f"{name}, error.type {error_type}, injected: {count}")
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 日目には、ERROR スパンが一つもない。このゼロが要点であり、誤った経路はステータスを設定しない。したがって、その日の実際の失敗はこの表にまったく現れず、本章の残りは別の方法でそれらを数える。インシデント日はライブで実行するので、contacts サーバーは障害を適用する。この日には 75 件の ERROR スパンがあり、例はそのすべてに注入ラベルが付いていることを表明する。

行は、まずステータスで、次に error.type で読む。ERROR スパンの中には、error.type をまったく持たないものがある。一つは、タイムアウトした呼び出しに対する MCP SDK のクライアントスパン MCP send tools/call find_contact であり、これは 4 件ある。もう一つは、注入したクラッシュに対する contacts サーバーの contacts.lookup スパンであり、これは 3 件ある。上述の既定では、クラッシュがスパンの外へ抜けたときに ERROR が設定されるが、error.type を設定するものは何もない。error.type だけで数えると、この二つはどちらも漏れる。そのほかの行は、後の節で説明する種類である。拒否されたモデルへのリクエストは RateLimitError を持ち、47 件ある。返信が得られなかったメッセージは、ModelUnavailable を示すルートスパンで終わり、11 件ある。失敗した contacts 呼び出しは三つの名前で現れる。アシスタントの試行では execute_tool find_contact、クライアントスパンでは MCP send tools/call find_contact、サーバーのスパンでは tools/call find_contact である。タイムアウトとエラー結果の節で、それぞれを読む。

実践ルール: 失敗はスパンのステータスで数え、各 error.type をその件数の横に表示する。error.type のないスパンもエラーであるから、失敗を見つけるためにその属性で絞り込んではならない。実際の件数と注入した件数は別の行にし、注入の行には、現れる箇所ごとにラベルを付ける。

上限で切れた応答

最初の節のステータス規則は、例外を送出する失敗を捉える。しかし、トークン上限で切れた応答は何も送出しない。モデルが応答を完了したからではなく、その上限に達したために止まる応答がある。アシスタントは、ランタイムの終了理由を gen_ai.response.finish_reasons に記録する。これは生成ごとに1要素を持つ配列であり、要素は生成の選択肢の順に並ぶ。終了理由は、モデルがなぜ止まったかを示す。モデル自身が止まった場合(stop)と、トークン上限で止まった場合(length)がある。GenAI規約は、0.1.0 において、推論スパンの値を同じ用語で定義している。中断された生成はプロバイダの理由または interrupted を報告し、理由が期待されたのに得られなかった場合は error が報告される(client inference span、注18)。したがって、length の応答はエラーではなく、エラーとして数えない。エージェントハーネスの終了理由も同じ考え方である。

このランタイムについての2つの事実が、この検査のあり方を決める。第一に、このランタイムは tool_calls を報告しない。モデルのツール呼び出しは応答内のテキストとして返り、終了理由は stop のままである。そのため、終了理由からはツール呼び出しを見分けられない。この場合は次の節で扱う。第二に、回答の段階には 160 トークンの上限がある。この上限はすべてのリリースと記録で同じである。上限は、本書が読むどの記録よりも前に一度だけ設定されたものであり、切れを作り出すために編集された記録はない。

truncated-replies.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 合格
"""Which model replies the runtime cut at its token cap, read from the finish reason the runtime recorded for eachrequest: baseline day 1 (the 4B, release r0) and the model swap (the 0.6B, release r2). A cut reply has finish reasonlength. The runtime never reports tool_calls, so a reply with a tool call is not found this way (malformed-tool-calls)."""import jsonfrom collections import Counterfrom lib.dayrun import DATA, run_day_tracedfrom lib.report import fmt_intdef finish_reasons(recording):    """The finish reason of every model request in one recording, counted by step and reason."""    rows = [json.loads(line) for line in (DATA / recording / "traces.jsonl").read_text(encoding="utf-8").splitlines()]    return [row for row in rows if row["kind"] == "model"], Counter(        (row["step"], row["finish_reason"]) for row in rows if row["kind"] == "model")base_rows, base = finish_reasons("baseline-day-1")for step in ("route", "answer"):    print(f"baseline day 1, {step} requests, finish reason stop: {fmt_int(base[(step, 'stop')])}")    print(f"baseline day 1, {step} requests, finish reason length: {fmt_int(base[(step, 'length')])}")# The replay answers from the same recording, and its chat spans carry the finish reason in an array.replayed = run_day_traced("2026-12-08", live=False).spanschat = [row for row in replayed if row["name"].startswith("chat")]reasons = Counter(reason for row in chat for reason in row["attributes"]["gen_ai.response.finish_reasons"])print(f"baseline day 1, chat spans replayed with finish reason stop: {fmt_int(reasons['stop'])}")assert reasons["length"] == 0 and reasons["stop"] == len(base_rows)  # the replay's spans match the recordingswap_rows, swap = finish_reasons("release-model-swap")manifest = json.loads((DATA / "release-model-swap" / "manifest.json").read_text(encoding="utf-8"))for step in ("route", "answer"):    print(f"model swap (0.6B, release r2), {step} requests, finish reason length: {fmt_int(swap[(step, 'length')])}")cut = [row for row in swap_rows if row["finish_reason"] == "length"]print(f"model swap, answer cap in tokens: {manifest['answer_max_tokens']}")print(f"model swap, cut answer, completion tokens: {cut[0]['completion_tokens']}")assert len(cut) == 1 and cut[0]["step"] == "answer"  # one cut reply, and it is an answerassert cut[0]["completion_tokens"] == manifest["answer_max_tokens"]  # cut at the cap, not at a stop token
出力python truncated-replies.py
baseline day 1, route requests, finish reason stop: 200
baseline day 1, route requests, finish reason length: 0
baseline day 1, answer requests, finish reason stop: 121
baseline day 1, answer requests, finish reason length: 0
baseline day 1, chat spans replayed with finish reason stop: 321
model swap (0.6B, release r2), route requests, finish reason length: 0
model swap (0.6B, release r2), answer requests, finish reason length: 1
model swap, answer cap in tokens: 160
model swap, cut answer, completion tokens: 160

4Bの応答で上限に達したものはなかった。200 件のルート応答と 121 件の回答はすべて自然に止まっており、リプレイのチャットスパンも同じ理由を持つ。その数は 321 件で、すべて stop である。

モデル入れ替えのリリースはQwen3-0.6Bを実行し、プロンプトに /no_think を加える。そのため、基準の1日目との差は、小さいモデルと接尾辞の両方から生じる。ここで切れた応答が現れる。ルート応答に切れたものはなく、回答の段階では 1 件の応答が、160 トークンで切れた。これが上限の値である。

この切れた応答は品質上の所見である。スパンはエラーではなく、ユーザーは途中で止まった応答を受け取る。これを品質に分類し、その意味を判断する前にテキストを読む。

実践ルール: 応答が完全だとみなす前に、すべてのリリースで段階ごとに length の終了理由を数え、その数の横に上限を示す。ある記録でゼロであっても、別の記録については何も言えない。切れた応答は品質上の所見として読み、エラーとして分類してはならない。

解析できないツール呼び出し

モデルがツールを必要とするとき、モデルは返信の中に<tool_call>ブロックを書き、アシスタントがそのブロックを読み戻す。ランタイムの終了理由では、不正なブロックを見つけることはできない。ブロックが壊れた返信であっても、返信は自然に停止するからである。不正な呼び出しは、返信を解析して初めて見つかる。閉じタグのないブロックは不正である。本体が JSON でないもの、名前のない呼び出し、引数がオブジェクトでない呼び出しも同様である。不正な呼び出しは、そのメッセージ上で1回ずつ数えられる。アシスタントはモデルに対して、呼び出しを読み取れなかったことを伝え、ツールを使わずに答えるよう求める。

これとは別の失敗は、ツール自体に達する。呼び出しは解析に成功しても、そのツールの引数モデルに通らないことがある。これは不正な返信ではない。この場合、ツールの試行は ERROR で終わり、error.typeにはクラスValidationErrorが設定される。クエリの節は、これらをツールの試行に含めて数える。

malformed-tool-calls.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 合格
"""Which answer replies carry a tool call the parser cannot read, on baseline day 1 (the 4B) and the model swap (the 0.6B).A malformed call is found by parsing the reply, because its finish reason is stop either way. The constructed repliesat the end are not recorded and never become spans: they show that the parser rejects what it should."""import globimport jsonfrom pathlib import Pathfrom lib.assistant import MalformedToolCall, parse_tool_callfrom lib.dayrun import DATA, run_day_tracedfrom lib.report import fmt_intdef check_answers(recording):    """Parse every answer reply in one recording. Returns the reply count, the replies with a tool call, and the    message IDs whose reply the parser rejects."""    paths = sorted(glob.glob(str(DATA / recording / "calls" / "*.json")))    calls = [json.loads(Path(path).read_text(encoding="utf-8")) for path in paths]    answers = sorted((call for call in calls if call["kind"] == "model" and call["step"] == "answer"),                     key=lambda call: call["seq"])  # the recorder's sequence number, unique per request    tool_calls, rejected = 0, []    for call in answers:        try:            tool_calls += parse_tool_call(call["text"]) is not None        except MalformedToolCall:            rejected.append(call["message_id"])    return len(answers), tool_calls, rejectedanswers, tool_calls, rejected = check_answers("baseline-day-1")print(f"baseline day 1 (4B), answer replies: {fmt_int(answers)}")print(f"baseline day 1 (4B), replies with a tool call: {fmt_int(tool_calls)}")print(f"baseline day 1 (4B), malformed tool calls: {fmt_int(len(rejected))}")# The replay parses the same recorded texts with the same parser, so its count should agree with the parse above.replayed = sum(run.outcome.malformed_tool_calls for run in run_day_traced("2026-12-08", live=False).runs)print(f"baseline day 1 (4B), malformed tool calls in the replay: {fmt_int(replayed)}")assert not rejected and replayed == 0answers, tool_calls, rejected = check_answers("release-model-swap")print(f"model swap (0.6B, release r2), answer replies: {fmt_int(answers)}")print(f"model swap (0.6B, release r2), replies with a tool call: {fmt_int(tool_calls)}")  # one call tests nothingprint(f"model swap (0.6B, release r2), malformed tool calls: {fmt_int(len(rejected))}")assert not rejected# Constructed, not recorded: two replies a model could write, passed straight to the parser.for label, text in {"unclosed block": '<tool_call>{"name": "find_contact", "arguments": {}',                    "body is not JSON": "<tool_call>find the contact</tool_call>"}.items():    try:        parse_tool_call(text)        raise AssertionError(f"{label} was not rejected")    except MalformedToolCall:        print(f"constructed reply, {label}, rejected by the parser: yes")
出力python malformed-tool-calls.py
baseline day 1 (4B), answer replies: 121
baseline day 1 (4B), replies with a tool call: 10
baseline day 1 (4B), malformed tool calls: 0
baseline day 1 (4B), malformed tool calls in the replay: 0
model swap (0.6B, release r2), answer replies: 57
model swap (0.6B, release r2), replies with a tool call: 1
model swap (0.6B, release r2), malformed tool calls: 0
constructed reply, unclosed block, rejected by the parser: yes
constructed reply, body is not JSON, rejected by the parser: yes

基準日1の記録済みの返信には、壊れたブロックを含むものはなかった。4B は121件の回答返信を書き、そのうち10件がツール呼び出しを含んでいた。パーサーが拒否したのは、そのうち0件である。解析の失敗とスキーマによる拒否をまとめて数えるリプレイの結果は0であり、これは一致している。

モデル入れ替えのリリースは、プロンプトに/no_thinkを付けた Qwen3-0.6B であり、57件の回答を書いた。そのうちツール呼び出しを含んでいたのは1件だけである。その呼び出しは解析に成功した。1件の呼び出しからは、小さなモデルのツール利用について何も検証できないため、この節ではそれについて何も主張しない。

どちらの記録にも壊れたブロックはない。パーサーが何を拒否するかを示すために、この章のために書いた2件の返信をパーサーに直接渡すと、どちらも拒否される。これらの返信は記録されたものではなく、スパン、行、記録のいずれにもならないため、記録された日については何も語らない。

ただし、レシーバーは解析の失敗を見つけられない。不正な返信はアシスタントの内部で例外を送出し、メッセージの結果に数えられるが、それをエラーとして記録するスパンはない。そのため、上の件数は返信から得たものである。レシーバーが何を示せて何を示せないかは、クエリの節で述べる。

実践ルール: ツール呼び出しを含みうるすべての返信を解析し、不正な返信は、終了理由ではなく、パーサー自身の件数で数える。呼び出しを含む返信は、その件数と並べて示し、ツール利用の標本がどれほど小さいかを読者が確認できるようにする。

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

Retries under a timeout

The status rule in the first section catches a failure that raises, and the first injected fault is one: a timeout raises across the process boundary. The contacts server is a separate process, and find_contact runs there, so its failures reach the assistant as the MCP SDK raises them. We injected this fault into the incident day. Between 13:00 and 13:12 UTC, the contacts server answers find_contact only after the client's read timeout of 2,000.0 ms, and the client gives up. The tool wrapper waits and tries once more. Chapter 4 explains how the SDK raises that timeout as an exception and not as a reply.

A retry is another attempt at a failed call, recorded as its own span. We recommend one span per attempt, and we record each attempt of a tool call as its own execute_tool span, with an ambrewick.attempt number. A failed attempt is therefore an ERROR span, and the call's success appears on the attempt that succeeded. No span describes the whole call. Chapter 4's choice gives the reason, and the first attempt's timeout is one of the failures the user's message met, so it counts.

retries-under-incident.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 合格
"""What each injected window does to the calls it covers, on the incident day, run live so the contacts server applies itsfaults. A timed-out find_contact is two attempts that end ERROR with MCP code -32001, the retry starting after the readtimeout and the retry delay; a refused model request is retried on the assistant's backoff. Every line here is labelledwith its window: injected, not a natural rate."""import tomllibfrom lib import injectfrom lib.case import CASE_DIRfrom lib.dayrun import run_day_tracedfrom lib.report import fmt_int, fmt_msfrom lib.tools import REQUEST_TIMEOUT_NS, RETRY_DELAY_NSlive = run_day_traced("2026-12-09")# Spans carry no message ID, so each message is found by its trace: the root spans come in arrival order, as the runs do.roots = sorted((row for row in live.spans if row["name"].startswith("invoke_agent")), key=lambda row: row["trace_seq"])message_of = {root["trace_id"]: run.message.message_id for root, run in zip(roots, live.runs, strict=True)}windows = {incident.incident_id: incident for incident in inject.load_incidents()}schedule = {row["id"]: row for row in tomllib.loads((CASE_DIR / "incidents.toml").read_text(encoding="utf-8"))["incident"]}finds = [row for row in live.spans if row["name"] == "execute_tool find_contact"]refused = [row for row in live.spans if row["attributes"].get("error.type") == "RateLimitError"]def inside(name, row):    """Whether a span starts inside the named window (the window's virtual start, inclusive, to its end)."""    return windows[name].start_ns <= row["start_ns"] < windows[name].end_nsdef say(name, label, value):    """Print one labelled value for a window."""    print(f"{name} (injected), {label}: {value}")TIMEOUT = "inc-contacts-timeout"# The schedule's stamps read 2026-12-09T13:00:00.000000Z, so characters 11 to 16 hold the UTC clock time.say(TIMEOUT, "window start (UTC)", schedule[TIMEOUT]["start"][11:16])say(TIMEOUT, "window end (UTC)", schedule[TIMEOUT]["end"][11:16])timeouts = sorted((row for row in finds if inside(TIMEOUT, row)                   and row["attributes"].get("error.type") == "MCPError"), key=lambda row: row["start_ns"])assert all(row["status"] == "ERROR" and row["attributes"]["ambrewick.mcp.error_code"] == -32001 for row in timeouts)assert all(row["end_ns"] - row["start_ns"] == REQUEST_TIMEOUT_NS for row in timeouts)  # each attempt waits the read timeoutsay(TIMEOUT, "attempts that time out", fmt_int(len(timeouts)))say(TIMEOUT, "MCP error code", timeouts[0]["attributes"]["ambrewick.mcp.error_code"])say(TIMEOUT, "read timeout", fmt_ms(REQUEST_TIMEOUT_NS))pairs = [(a, b) for a, b in zip(timeouts, timeouts[1:]) if a["trace_id"] == b["trace_id"]]assert all(b["start_ns"] - a["start_ns"] == REQUEST_TIMEOUT_NS + RETRY_DELAY_NS for a, b in pairs)say(TIMEOUT, "retries", fmt_int(len(pairs)))say(TIMEOUT, "retry wait", fmt_ms(RETRY_DELAY_NS))say(TIMEOUT, "retry starts after the first attempt", fmt_ms(pairs[0][1]["start_ns"] - pairs[0][0]["start_ns"]))errors = [row for row in finds if inside("inc-mcp-error", row)]say("inc-mcp-error", "retries", fmt_int(sum(row["attributes"]["ambrewick.attempt"] > 1 for row in errors)))replied = [run for run in live.runs if run.outcome.source == "model" and run.message.message_id in schedule["inc-rate-limit"]["message_ids"]]retried = [run for run in replied if any(message_of[row["trace_id"]] == run.message.message_id for row in refused)]say("inc-rate-limit", "messages that got a reply after a refused attempt", fmt_int(len(retried)))assert len(retried) == len(replied)  # every reply in the window came after a refusal
出力python retries-under-incident.py
inc-contacts-timeout (injected), window start (UTC): 13:00
inc-contacts-timeout (injected), window end (UTC): 13:12
inc-contacts-timeout (injected), attempts that time out: 4
inc-contacts-timeout (injected), MCP error code: -32001
inc-contacts-timeout (injected), read timeout: 2,000.0 ms
inc-contacts-timeout (injected), retries: 2
inc-contacts-timeout (injected), retry wait: 500.0 ms
inc-contacts-timeout (injected), retry starts after the first attempt: 2,500.0 ms
inc-mcp-error (injected), retries: 0
inc-rate-limit (injected), messages that got a reply after a refused attempt: 1
演習 8.3

試行ではなくリトライを数える

+10 件の検証

46行目は、リトライではなく、タイムアウトした試行をすべて数えている。この行がタイムアウトの時間枠内のリトライ数を出力するように修正せよ。

say(TIMEOUT, "read timeout", fmt_ms(REQUEST_TIMEOUT_NS))pairs = [(a, b) for a, b in zip(timeouts, timeouts[1:]) if a["trace_id"] == b["trace_id"]]assert all(b["start_ns"] - a["start_ns"] == REQUEST_TIMEOUT_NS + RETRY_DELAY_NS for a, b in pairs)say(TIMEOUT, "retry wait", fmt_ms(RETRY_DELAY_NS))say(TIMEOUT, "retry starts after the first attempt", fmt_ms(pairs[0][1]["start_ns"] - pairs[0][0]["start_ns"]))
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 で実行される

Here the incident day runs live, so the contacts server applies the fault, and each span is grouped by its window. Every line names its window and says injected. In the timeout window, the timed-out attempts were 4. Each ends ERROR, with error.type MCPError and the MCP code on ambrewick.mcp.error_code. The code is -32001, the SDK's name for a read timeout and not a protocol code, as chapter 4 says. The retries were 2. Both timed-out messages' retries timed out too, so the tool returned its timed-out reply to the model. Each second attempt starts 2,500.0 ms after its first, which is the read timeout plus the wait before the retry.

The model's window works the same way, but its failures are refusals. Every model request in the window is answered with a 429, and the assistant retries with a backoff. Each refused attempt is a zero-length chat span, ERROR, with error.type RateLimitError, and the injected window refused 47 requests. Once the backoff runs out, the message ends with no reply: 11 messages did. One message got a reply after a refused attempt, which is 1. By the span rule, that message counts as an error, although its user got the reply. The count follows the spans. The production section says what that does to a rate.

Working rule: Count a failed attempt as a failure even when the call later succeeds, and name its window before you count it as injected.

MCP のエラー

contacts サーバーには、もう一つの失敗の仕方があり、そこでは何も例外が送出されない。MCP のツール仕様によれば、ツール自身の失敗は、プロトコルエラーとしてではなく、isError を設定した結果として返される(tools、リビジョン 2026-07-28)。本書で 2.3.0 を用いている MCP Python SDK は、この規則に従う。注入した mcp-error のウィンドウでは、その間の find_contact の呼び出しがすべてエラー結果として返り、クライアントはその結果を返信としてアシスタントに渡す。

エラー結果は例外ではないため、名前を付けるべき例外が存在しない。この試行は ERROR で終わり、error.type は tool_error となる。これは isError の結果について MCP の規約が定めている値である(MCP conventions、v0.1.0)。ステータスの説明は "find_contact returned an error result" である。例外イベントは書き込まれず、再試行も行われない。

インシデント当日の行には、三つの記録が現れる。アシスタントは 3 件の試行を tool_error として記録し、サーバーも同じ呼び出しを tool_error として記録した。その件数は 3 である。ウィンドウの再試行の行は 0 であり、これらの試行はどれも再試行されていない。contacts サーバーの contacts.lookup スパンも、これらの呼び出しでは ERROR であり、error.type を持たない。規約は、クライアントのスパンにも tool_error を求めており、また失敗したクライアントスパンには error.type を求めている。タイムアウトの場合、その値は例外のクラス名である。2.3.0 の MCP SDK は、この両方から外れている。エラー結果に対するクライアントスパンは未設定のままであり、タイムアウトに対するスパンは error.type を持たない ERROR となる。最初の表でクライアント側の ERROR 行は、4 のタイムアウトだけである。

このため、注入した一つの障害が、三つの ERROR 記録を残す。ステータス別にスパンを数えると、これは三回数えられる。ユーザーのメッセージが遭遇した失敗は試行である。それは、そのメッセージ自身の呼び出しが実行した操作が試行だからである。サーバーのスパンは原因であり、第 4 章が伝播するコンテキストを通じて、メッセージのトレースに結び付く。クエリの節では、各エラー結果の試行を、そのトレース内のサーバースパンと対にする。対の数は 3 である。

実践ルール: 失敗した操作は、呼び出し側が作ったスパンで一度だけ数え、原因はその隣にあるサーバーのスパンから読み取る。このバージョンの MCP SDK では、規約が tool_error を求めているにもかかわらず、エラー結果に対するクライアントのスパンは未設定のままになると想定する。いずれの場合も、呼び出し側の試行で数える。

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

Wrong routes against the labels

A wrong route is the one failure with no error anywhere in the trace. The call succeeds, its reply stops on its own, and the answer is a fallback reply, or a tool route the message did not need. To find it, the book needs a source of truth, and the case has one. MASSIVE labels each utterance with a scenario. The scenario table maps each scenario to one route, and the routes are calendar, alarms, lists, messages, devices, media and fallback. A scenario goes to the route whose tool or articles resolve it, and to fallback only when no tool and no article do. A wrong route is a routed choice that differs from the table's. The router writes its choice on the route span, and the check event on that span holds the table's answer, so the trace records whether the route was right.

The fallback reply is defined in chapter 1. The table adds the rule for when it is the right answer. It is right for a message that no tool or article resolves, and for no other message. A fallback reply to any other scenario is a wrong route that the user sees as a refusal. The check is code, and it reads the trace, not the reply's text. Judging whether an answer is right is a separate job, and Evaluating LLM Applications covers the checks that read a reply.

The dev day shows the case in small. Of its 20 messages, 5 were routed wrong, and 3 of those got the fallback reply for a scenario that needed a tool or an article.

wrong-routes-by-label.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 合格
"""How often the router chose a route other than the scenario table's, on baseline day 1 (the 4B), the same messages underthe 0.6B (the model swap, from its recorded route replies) and the dev day. Each message's check event on its route spanholds the table's answer; the 0.6B's replies are read with the same parser. The interval is a bootstrap over messages."""import jsonfrom fractions import Fractionfrom lib.assistant import parse_routefrom lib.case import load_messages, scenario_to_routefrom lib.dayrun import DATA, run_day, run_day_tracedfrom lib.report import fmt_int, fmt_sharefrom lib.stats import bootstrap_intervaldef recorded_routes(recording, day):    """(expected, chosen) for each route reply in one recording, in order. A reply that names no route is the fallback."""    messages = {message.message_id: message for message in load_messages(day)}    paths = sorted((DATA / recording / "calls").glob("*.json"))    calls = sorted((json.loads(path.read_text(encoding="utf-8")) for path in paths), key=lambda call: call["seq"])    return [(scenario_to_route(messages[c["message_id"]].scenario), parse_route(c["text"]) or "fallback")            for c in calls if c["kind"] == "model" and c["step"] == "route"]traced = run_day_traced("2026-12-08", live=False)runs = traced.runs# The check event is on each route span: the trace itself says whether the route was correct.checks = [event["attributes"] for row in traced.spans for event in row["events"] if event["name"] == "ambrewick.check"]wrong = [run.outcome.route != run.outcome.expected_route for run in runs]assert len(checks) == len(runs) and sum(not check["ambrewick.route.correct"] for check in checks) == sum(wrong)print(f"baseline day 1 (4B), messages: {fmt_int(len(runs))}")RESAMPLES = 2000low, high = bootstrap_interval(wrong, lambda units: Fraction(sum(units), len(units)), n=RESAMPLES)print(f"bootstrap resamples of messages, baseline day 1: {fmt_int(RESAMPLES)}")print(f"wrong routes, baseline day 1, 95% interval: {fmt_share(low.numerator, low.denominator)} to {fmt_share(high.numerator, high.denominator)}")for route in sorted({run.outcome.expected_route for run in runs}):    print(f"{route}, wrong routes of {fmt_int(sum(run.outcome.expected_route == route for run in runs))} messages: "          f"{fmt_int(sum(run.outcome.route != route for run in runs if run.outcome.expected_route == route))}")print("fallback replies to a scenario that is not fallback, baseline day 1: "      f"{fmt_int(sum(run.outcome.route == 'fallback' and run.outcome.expected_route != 'fallback' for run in runs))}")# The same messages under the 0.6B, from its recorded replies; the 4B's recorded replies must give the replay's count.base = recorded_routes("baseline-day-1", "2026-12-08")assert sum(expected != chosen for expected, chosen in base) == sum(wrong)swap = recorded_routes("release-model-swap", "2026-12-08")print(f"wrong routes, model swap (0.6B, release r2): {fmt_int(sum(e != c for e, c in swap))} of {fmt_int(len(swap))} messages")print("fallback replies to a scenario that is not fallback, model swap: "      f"{fmt_int(sum(c == 'fallback' and e != 'fallback' for e, c in swap))}")# The dev day's 20 messages, for chapter 1's fallback replies, checked against the same table.dev = run_day("2026-12-07")print(f"dev day, messages: {fmt_int(len(dev))}")print(f"wrong routes, dev day (20 messages): {fmt_int(sum(run.outcome.route != run.outcome.expected_route for run in dev))}")print(f"fallback replies to a scenario that is not fallback, dev day: {fmt_int(sum(run.outcome.route == 'fallback' and run.outcome.expected_route != 'fallback' for run in dev))}")
出力python wrong-routes-by-label.py
baseline day 1 (4B), messages: 200
bootstrap resamples of messages, baseline day 1: 2,000
wrong routes, baseline day 1, 95% interval: 15.0% to 26.5%
alarms, wrong routes of 6 messages: 0
calendar, wrong routes of 42 messages: 16
devices, wrong routes of 17 messages: 1
fallback, wrong routes of 82 messages: 11
lists, wrong routes of 7 messages: 0
media, wrong routes of 29 messages: 3
messages, wrong routes of 17 messages: 10
fallback replies to a scenario that is not fallback, baseline day 1: 18
wrong routes, model swap (0.6B, release r2): 83 of 200 messages
fallback replies to a scenario that is not fallback, model swap: 68
dev day, messages: 20
wrong routes, dev day (20 messages): 5
fallback replies to a scenario that is not fallback, dev day: 3
演習 8.4

各メッセージをテーブルに照らして誤りと判定する

+10 件の検証

27行目は空白である。各実行の結果が持つルートと期待ルートを用いて、ルーティングされた選択がシナリオテーブルの答えと異なる場合に、そのメッセージを誤りと判定するように書け。

runs = traced.runs# The check event is on each route span: the trace itself says whether the route was correct.checks = [event["attributes"] for row in traced.spans for event in row["events"] if event["name"] == "ambrewick.check"]assert len(checks) == len(runs) and sum(not check["ambrewick.route.correct"] for check in checks) == sum(wrong)print(f"baseline day 1 (4B), messages: {fmt_int(len(runs))}")RESAMPLES = 2000
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 で実行される
演習 8.5

Count the wrong routes that went to a tool

+10 件の検証

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

Lines 37 and 38 count fallback replies to other scenarios. Change them so the example prints the line 'wrong routes to a tool route, baseline day 1: 23' in place of the fallback line, and every other line stays as it is.

for route in sorted({run.outcome.expected_route for run in runs}):    print(f"{route}, wrong routes of {fmt_int(sum(run.outcome.expected_route == route for run in runs))} messages: "          f"{fmt_int(sum(run.outcome.route != route for run in runs if run.outcome.expected_route == route))}")# The same messages under the 0.6B, from its recorded replies; the 4B's recorded replies must give the replay's count.base = recorded_routes("baseline-day-1", "2026-12-08")

得られるべき出力

baseline day 1 (4B), messages: 200
bootstrap resamples of messages, baseline day 1: 2,000
wrong routes, baseline day 1, 95% interval: 15.0% to 26.5%
alarms, wrong routes of 6 messages: 0
calendar, wrong routes of 42 messages: 16
devices, wrong routes of 17 messages: 1
fallback, wrong routes of 82 messages: 11
lists, wrong routes of 7 messages: 0
media, wrong routes of 29 messages: 3
messages, wrong routes of 17 messages: 10
wrong routes to a tool route, baseline day 1: 23
wrong routes, model swap (0.6B, release r2): 83 of 200 messages
fallback replies to a scenario that is not fallback, model swap: 68
dev day, messages: 20
wrong routes, dev day (20 messages): 5
fallback replies to a scenario that is not fallback, dev day: 3
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 で実行される

On baseline day 1 the 4B routed 41 of its messages wrong. The 95% interval runs from 15.0% to 26.5%, from 2,000 resamples of messages.

For one day of 200 messages that interval is wide, and the rate should be read with it. Of the wrong routes, 18 were fallback replies to scenarios that needed a tool or an article. The rest went to a tool route.

The routes differ a great deal. Of the messages whose scenario belongs to the messages route, 10 of 17 were wrong, and every one of them was a fallback reply. Calendar was the other large case: 16 of 42 were wrong.

The fallback scenarios show the opposite error. They went to a tool route 11 times, out of 82. The alarms and lists routes had no wrong routes at all, but with 6 and 7 messages, those zeros say little.

The model-swap release routed 83 of 200 messages wrong, and 68 of those were fallback replies to scenarios that needed a tool or an article. The two releases answer the same 200 messages. Its prompt also carries /no_think, so the difference from the 4B is the smaller model and the suffix together.

figure-failure-modes-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, for each scenario route on baseline day 1, how many of its messages the router sent right, to another tool route,or to the fallback reply. The failing modes are coloured; the modes with no count on this day (truncated replies,malformed tool calls) are printed as zero and named in the caption. Every value the figure draws is printed first."""from lib.dayrun import run_day_tracedfrom lib.figures import ACCENT, INK, MUTED, new_figure, savefrom lib.report import fmt_inttraced = run_day_traced("2026-12-08", live=False)  # the 4B's real replies, replayed from the recordingruns = traced.runsmalformed = sum(run.outcome.malformed_tool_calls for run in runs)  # calls the parser rejectedtruncated = sum("length" in row["attributes"]["gen_ai.response.finish_reasons"]  # replies cut at the cap                for row in traced.spans if row["name"].startswith("chat"))assert malformed == 0 and truncated == 0rows = []for route in sorted({run.outcome.expected_route for run in runs}):    group = [run for run in runs if run.outcome.expected_route == route]    right = sum(run.outcome.route == route for run in group)    fallback = sum(run.outcome.route == "fallback" and route != "fallback" for run in group)    other = len(group) - right - fallback    assert right + fallback + other == len(group)    rows.append((route, len(group), right, other, fallback))    print(f"route {route}, messages (n): {fmt_int(len(group))}")    print(f"route {route}, routed right: {fmt_int(right)}")    print(f"route {route}, wrong, to another tool route: {fmt_int(other)}")    print(f"route {route}, wrong, to the fallback reply: {fmt_int(fallback)}")print(f"truncated replies, baseline day 1: {fmt_int(truncated)}")print(f"malformed tool calls, baseline day 1: {fmt_int(malformed)}")fig, ax = new_figure(height=3.4)ys = list(range(len(rows)))[::-1]  # the first route at the topfor y, (route, n, right, other, fallback) in zip(ys, rows):    ax.barh(y, right, color=MUTED, alpha=0.35, label="routed right" if y == ys[0] else None)    ax.barh(y, other, left=right, color=INK, label="wrong, to another tool route" if y == ys[0] else None)    ax.barh(y, fallback, left=right + other, color=ACCENT, label="wrong, to the fallback reply" if y == ys[0] else None)ax.set_xlim(0, 1.12 * max(right + other + fallback for _, _, right, other, fallback in rows))   # headroom so the longest bar is not clippedax.set_yticks(ys, [f"{route} (n = {n})" for route, n, *_ in rows])ax.set_xlabel("messages on baseline day 1")ax.legend(loc="lower right", frameon=False)save(fig, "failure-modes-by-route")
出力python figure-failure-modes-by-route.py
route alarms, messages (n): 6
route alarms, routed right: 6
route alarms, wrong, to another tool route: 0
route alarms, wrong, to the fallback reply: 0
route calendar, messages (n): 42
route calendar, routed right: 26
route calendar, wrong, to another tool route: 12
route calendar, wrong, to the fallback reply: 4
route devices, messages (n): 17
route devices, routed right: 16
route devices, wrong, to another tool route: 0
route devices, wrong, to the fallback reply: 1
route fallback, messages (n): 82
route fallback, routed right: 71
route fallback, wrong, to another tool route: 11
route fallback, wrong, to the fallback reply: 0
route lists, messages (n): 7
route lists, routed right: 7
route lists, wrong, to another tool route: 0
route lists, wrong, to the fallback reply: 0
route media, messages (n): 29
route media, routed right: 26
route media, wrong, to another tool route: 0
route media, wrong, to the fallback reply: 3
route messages, messages (n): 17
route messages, routed right: 7
route messages, wrong, to another tool route: 0
route messages, wrong, to the fallback reply: 10
truncated replies, baseline day 1: 0
malformed tool calls, baseline day 1: 0
figure: figures/failure-modes-by-route.svg

図 8.1 draws the same messages by route. Each bar is an expected route from the scenario table, and it holds that route's messages, split into the ones routed right, the ones wrong to another tool route, and the ones wrong to the fallback reply. Most wrong routes sit in the calendar, fallback and messages bars. Two modes count zero on this day, truncated replies and malformed tool calls, and the figure does not draw them. Chapter 7 counts the same day's messages by the route the assistant chose, not the expected one, so its counts differ: 7 messages and 31 media there, against 17 and 29 here.

020406080messages on baseline day 1alarms (n = 6)calendar (n = 42)devices (n = 17)fallback (n = 82)lists (n = 7)media (n = 29)messages (n = 17)routed rightwrong, to another tool routewrong, to the fallback reply
図 8.1 Each route's messages on baseline day 1: routed right, wrong to a tool route, or wrong to the fallback reply

Working rule: Check each route against the scenario table on the trace, count fallback replies to other scenarios apart from the other wrong routes, and print every rate with its interval. Compare two releases only on the same messages, and name any suffix or prompt change beside the comparison.

各障害モードのクエリ

各障害モードには、レシーバーの行に対するクエリを一つずつ用意する。レシーバーは日ごとに別のファイルを保持する。ベースラインとインシデント日は分けて保管されるため、注入した行が実際の件数に混ざることはない。レシーバーは、第5章で示したとおり、アシスタントのエクスポートが書き出すものと同じ行を保持している。

failure-modes-query.py Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 合格
"""One query per failure mode over the stored rows: baseline day 1 (real) and the incident day (injected, labelled), eachkept in its own receiver file. The baseline's real failures are wrong routes and fallback replies; its span errors andtruncated replies print zero. A receiver holds spans only, so no query here counts a parse failure."""import tempfilefrom lib import queryfrom lib.dayrun import run_day_tracedfrom lib.export import write_jsonlfrom lib.report import fmt_intfolder = tempfile.mkdtemp()baseline = run_day_traced("2026-12-08", live=False)write_jsonl(f"{folder}/baseline.jsonl", baseline.spans)incident = run_day_traced("2026-12-09")  # live: the contacts server's rows go to the incident day's receiverwrite_jsonl(f"{folder}/incident.jsonl", incident.spans + incident.server)base, inc = query.connect(f"{folder}/baseline.jsonl"), query.connect(f"{folder}/incident.jsonl")# A check event sits in the event list of its route span; the route the span chose is in the span's own attributes.WRONG = """SELECT count(*) FROM spans, UNNEST(from_json(events, '["json"]')) AS t(e)  WHERE json_extract_string(e, '$.name') = 'ambrewick.check'  AND json_extract_string(e, '$.attributes."ambrewick.route.correct"') = 'false'"""FALLBACK = """SELECT count(*) FROM spans, UNNEST(from_json(events, '["json"]')) AS t(e)  WHERE json_extract_string(e, '$.name') = 'ambrewick.check'  AND json_extract_string(e, '$.attributes."ambrewick.route.correct"') = 'false'  AND json_extract_string(attributes, '$."ambrewick.route"') = 'fallback'  AND json_extract_string(e, '$.attributes."ambrewick.route.expected"') != 'fallback'"""TRUNCATED = """SELECT count(*) FROM spans WHERE name LIKE 'chat %'  AND json_extract_string(attributes, '$."gen_ai.response.finish_reasons"') LIKE '%length%'"""# Each error-result attempt joined to the contacts server's tools/call span in the same trace: one pair per injected error.PAIRED = """SELECT count(*) FROM spans AS a JOIN spans AS s ON s.trace_id = a.trace_id  WHERE a.name LIKE 'execute_tool %' AND s.name LIKE 'tools/call %'  AND a.status = 'ERROR' AND json_extract_string(a.attributes, '$."error.type"') = 'tool_error'  AND s.status = 'ERROR' AND json_extract_string(s.attributes, '$."error.type"') = 'tool_error'"""# Errors on tool attempts and on the contacts server's spans, one row per span name and error.type, with a tie-break.ERRORS = """SELECT name, json_extract_string(attributes, '$."error.type"') AS error_type, count(*) AS n FROM spans  WHERE status = 'ERROR' AND (name LIKE 'execute_tool %' OR name LIKE 'tools/call %')  GROUP BY name, error_type ORDER BY n DESC, name, error_type"""REFUSED = """SELECT count(*) FROM spans WHERE json_extract_string(attributes, '$."error.type"') = 'RateLimitError'"""def one(connection, sql):    return connection.execute(sql).fetchone()[0]print("wrong routes, baseline day 1 (real):", fmt_int(one(base, WRONG)))print("wrong routes, incident day (real):", fmt_int(one(inc, WRONG)))print("fallback replies to a scenario that is not fallback, baseline day 1 (real):", fmt_int(one(base, FALLBACK)))print("truncated replies, baseline day 1 (real):", fmt_int(one(base, TRUNCATED)))print("ERROR tool-attempt and server spans, baseline day 1 (real):", fmt_int(sum(n for *_, n in base.execute(ERRORS).fetchall())))for name, error_type, n in inc.execute(ERRORS).fetchall():    print(f"{name}, error.type {error_type}, incident day (injected): {fmt_int(n)}")print("error-result attempts paired with their server span, incident day (injected):", fmt_int(one(inc, PAIRED)))print("model requests refused, incident day (injected):", fmt_int(one(inc, REFUSED)))
出力python failure-modes-query.py
wrong routes, baseline day 1 (real): 41
wrong routes, incident day (real): 13
fallback replies to a scenario that is not fallback, baseline day 1 (real): 18
truncated replies, baseline day 1 (real): 0
ERROR tool-attempt and server spans, baseline day 1 (real): 0
execute_tool find_contact, error.type MCPError, incident day (injected): 4
execute_tool find_contact, error.type tool_error, incident day (injected): 3
tools/call find_contact, error.type tool_error, incident day (injected): 3
error-result attempts paired with their server span, incident day (injected): 3
model requests refused, incident day (injected): 47

第2026.11.2版でduckdb 2.0.0 から 2.0.1 へから更新された。

ベースラインで実際に見つかった障害は、誤ったルート選択の41件と、ツールや記事を必要とするシナリオに対するフォールバック応答の18件である。インシデント日の誤ったルート選択13件は、モデルが実際に行ったルート選択であり、注入した障害ではない。注入した障害は誤ったルート選択を増やさない。拒否されたルート試行は同じ記録済みの応答で再試行され、断念したメッセージには比較すべきチェックイベントがないため、注入した期間には誤ったルート選択が加わらないからである。本章では、この日の率は示さない。

その他のモードは、ベースラインではゼロとなる。切り詰められた応答は0件である。ベースラインには途中で切れた応答がないため、このゼロはここでは検証されていない。つまり、このモードが発生した日にはクエリを実行していない。ERRORとなったツール試行とサーバースパンは0件である。ベースライン1日目の不正な形式のツール呼び出しの真の件数はゼロである。これは解析できないツール呼び出しの節の応答から数えた値であり、レシーバーにはクエリの対象となるものが何もない。

インシデント日には、同じツールのクエリが注入した試行を検出する。試行でのタイムアウトは4件、試行でのエラー結果は3件、同じ呼び出しに対する連絡先サーバーのスパンでは3件である。拒否されたモデルリクエストは47件である。これらはいずれも出力で injected と表示され、いずれもインシデント日のファイルに含まれる。

実践ルール: 障害モードごとにクエリを一つ書き、そのクエリが読む属性またはイベントを明示し、ゼロという結果を信頼する前に、そのモードが発生した日で実行すること。どのスパンも持たない属性に対するクエリは、どの日でもゼロを返す。そのゼロは率ではなく、クエリのバグである。

本番環境での障害

最終変更:版2026.11.2

本番環境は、インシデント当日と同じ姿をしているわけではない。ここで扱う障害は、ケースの側で配置したものであるため、それぞれを後から時間枠に対応づけることができる。実際の障害にはラベルがない。したがって、時間枠ごとの件数は、事後に誰かが選んだ時間枠で数えた件数であり、その精度はインシデントの開始と終了の記録の精度を超えない。ケースのインシデントファイルのように、その記録を件数の隣に残し、どの件数がそれに由来するかを明記すること。

ほかのライブラリは、status を独自の方法で設定する。クライアントのスパンは、error.typeがないまま ERROR と表示されることがある。最初の表にある、タイムアウトに対する MCP SDK のスパンがその例である。障害はまず status で数え、error.typeは各件数に付けるラベルとして扱う。障害と見なすための条件としては扱わない。クライアントライブラリ内部のリトライにも注意が必要である。3.57.0の openai クライアントは、既定で 1 回の呼び出しの内部でリトライを行う(max_retries)。そのため、この呼び出しの周囲に計装を施しても書き出されるスパンは 1 つであり、リトライされた拒否はスパンにならず、スパン規則では数えられない。それらを確認するには、max_retries=0を設定し、本書のように自分のコードでリトライする。

自分のコードで行うリトライには、専用の属性が必要である。HTTP の規約は、再送された HTTP リクエストのためにhttp.request.resend_countを定めている(HTTP スパン、v1.45.0)。この属性は MCP の呼び出しを表すものではないため、本書のリトライではambrewick.attemptを付ける。呼び出しが使うプロトコルが何であっても、試行を表す属性を選ぶこと。

最後に、スパン規則は回復したメッセージも数える。最初のモデルリクエストが拒否され、その後のリクエストで応答を得たメッセージは、リトライの節が示すとおり、エラーとして数えられる。第 10 章のゲートは、回復したメッセージをエラーとして数える。第 9 章の目標は、ユーザーが目にしたものを数えるため、リトライの後に応答を得たメッセージは、そこでは障害ではない(サービスレベル目標)。最初のツール試行がタイムアウトし、リトライが成功したメッセージも、同じく数えられる。インシデント当日には、タイムアウトした 2 件のメッセージがどちらもリトライでタイムアウトしたため、このケースは起きなかった。2 つの数値が自分のシステムで異なる状況を示すなら、両方を測定し、それぞれを生んだ規則とともに示すこと。

実践ルール: 本番環境の障害率を公表する前に、その件数、対象とする時間枠、および障害のうち回復したものの数を示すこと。障害の種類ごとにエラータイプを明記し、タイプをまったく持たない種類があればそれも述べること。数値がユーザーの目にしたものを表すときは、第 9 章の目標と同じく、メッセージの結果で数えること。

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

What this chapter decided

A failure is found at the span that records it, so each decision below names the span it reads.

  • We define an error as a span with status ERROR, and we count a message by any of its spans. error-status-by-step prints the counts that rule gives, and retries-under-incident shows the message that recovered and still counts.
  • We write the class name the package raises into error.type, or the conventions' value where one is defined, such as tool_error for an isError result. The registry has no value for a timeout or a 429. error-status-by-step shows the names, and retries-under-incident shows the timeouts.
  • We keep the SDK's exception event rather than a log record, because the receiver holds spans and every query here reads them. Chapter 4's timeout example shows the event.
  • We count each failed attempt as its own error, so the first timeout counts. retries-under-incident prints the timed-out attempts and the retries they led to.
  • We read a cut reply and a wrong route as quality findings, not errors. truncated-replies and wrong-routes-by-label print both, with the cap and the scenario table beside them.
  • We parse each reply for a tool call, because the finish reason cannot show one. malformed-tool-calls prints the parser's counts.
  • We keep real and injected failures in separate rows and files, and we label every injected count. failure-modes-query reads two receivers, and error-status-by-step asserts that every ERROR span on the incident day carries the injected label.

この版における本章

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

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

Labs を開始

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

料金を見る

この節を引用する

形式

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

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

このページの内容

全12章中の第8章: 失敗したステップを見つける

  1. スパンが失敗を記録する方法
  2. 上限で切れた応答
  3. 解析できないツール呼び出し
  4. Retries under a timeout
  5. MCP のエラー
  6. Wrong routes against the labels
  7. 各障害モードのクエリ
  8. 本番環境での障害
  9. What this chapter decided

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