失敗したステップを見つける
読了まで約48 分。9 節に7 例を収録。
Labs
この章を実際に手を動かして学ぶ
すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。約 30 秒で開く。
すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。Labs が実行環境を用意する: 月40 時間。
自分のマシンで、無料: 書籍のノートブックをダウンロード、そのコードとデータを 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 が引き続きスパンに届くかぎり、もう一方の方法を取ってもよい。
1"""Which spans end with ERROR, and what error.type each carries, on the incident day (injected, labelled) and on baseline2day 1 (real). The point rests on the baseline's zero ERROR spans: a wrong route is not a span error, so the status cannot3find it, and the incident's faults look alike from outside."""4from collections import Counter56from lib.dayrun import run_day_traced7from lib.report import fmt_int89real = run_day_traced("2026-12-08", live=False) # baseline day 1, replayed: no fault is injected into it10real_errors = [row for row in real.spans if row["status"] == "ERROR"]11print("real ERROR spans, baseline day 1 (4B):", fmt_int(len(real_errors)))12assert not real_errors # the baseline's failures are wrong routes and fallback replies, which set no span status1314live = run_day_traced("2026-12-09") # live: the contacts server runs the injected faults over stdio15rows = live.spans + live.server16errors = [row for row in rows if row["status"] == "ERROR"]17print("ERROR spans, incident day (injected):", fmt_int(len(errors)))18# Each injected fault labels every span it touches, so the label itself tells an injected error from a real one.19assert all(row["attributes"].get("ambrewick.incident.injected") for row in errors) # every ERROR span is injected20counts = Counter((row["name"], row["attributes"].get("error.type", "none")) for row in errors)21for (name, error_type), count in sorted(counts.items()):22 print(f"{name}, error.type {error_type}, injected: {count}")
python error-status-by-step.pyreal 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
失敗したスパンをステータスで数える
+10 件の検証スパンが失敗を記録する方法、8章よりもう一度読む
attributeを基にする。1章「スパンを手作業で作る」より
spanを基にする。1章「1メッセージにつき1トレース」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
16行目は、error.type を持つかどうかで ERROR のスパンを選んでいるため、error.type を持たない ERROR のスパンはすべて除外されてしまう。16行目を変更して、ステータスが ERROR であるスパンをすべて選ぶようにせよ。
仕組み
エラーの種類ごとに数える(エラーのないスパンも含める)
+10 件の検証スパンが失敗を記録する方法、8章よりもう一度読む
attributeを基にする。1章「スパンを手作業で作る」より
spanを基にする。1章「1メッセージにつき1トレース」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
20行目は空白のままになっている。各 ERROR スパンをスパン名とその error.type の組で数え、error.type を持たないスパンは値 none の下で数えるように、この行を書け。
仕組み
再生したベースライン 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 トークンの上限がある。この上限はすべてのリリースと記録で同じである。上限は、本書が読むどの記録よりも前に一度だけ設定されたものであり、切れを作り出すために編集された記録はない。
1"""Which model replies the runtime cut at its token cap, read from the finish reason the runtime recorded for each2request: baseline day 1 (the 4B, release r0) and the model swap (the 0.6B, release r2). A cut reply has finish reason3length. The runtime never reports tool_calls, so a reply with a tool call is not found this way (malformed-tool-calls)."""4import json5from collections import Counter67from lib.dayrun import DATA, run_day_traced8from lib.report import fmt_int91011def finish_reasons(recording):12 """The finish reason of every model request in one recording, counted by step and reason."""13 rows = [json.loads(line) for line in (DATA / recording / "traces.jsonl").read_text(encoding="utf-8").splitlines()]14 return [row for row in rows if row["kind"] == "model"], Counter(15 (row["step"], row["finish_reason"]) for row in rows if row["kind"] == "model")1617base_rows, base = finish_reasons("baseline-day-1")18for step in ("route", "answer"):19 print(f"baseline day 1, {step} requests, finish reason stop: {fmt_int(base[(step, 'stop')])}")20 print(f"baseline day 1, {step} requests, finish reason length: {fmt_int(base[(step, 'length')])}")21# The replay answers from the same recording, and its chat spans carry the finish reason in an array.22replayed = run_day_traced("2026-12-08", live=False).spans23chat = [row for row in replayed if row["name"].startswith("chat")]24reasons = Counter(reason for row in chat for reason in row["attributes"]["gen_ai.response.finish_reasons"])25print(f"baseline day 1, chat spans replayed with finish reason stop: {fmt_int(reasons['stop'])}")26assert reasons["length"] == 0 and reasons["stop"] == len(base_rows) # the replay's spans match the recording2728swap_rows, swap = finish_reasons("release-model-swap")29manifest = json.loads((DATA / "release-model-swap" / "manifest.json").read_text(encoding="utf-8"))30for step in ("route", "answer"):31 print(f"model swap (0.6B, release r2), {step} requests, finish reason length: {fmt_int(swap[(step, 'length')])}")32cut = [row for row in swap_rows if row["finish_reason"] == "length"]33print(f"model swap, answer cap in tokens: {manifest['answer_max_tokens']}")34print(f"model swap, cut answer, completion tokens: {cut[0]['completion_tokens']}")35assert len(cut) == 1 and cut[0]["step"] == "answer" # one cut reply, and it is an answer36assert cut[0]["completion_tokens"] == manifest["answer_max_tokens"] # cut at the cap, not at a stop token
python truncated-replies.pybaseline 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が設定される。クエリの節は、これらをツールの試行に含めて数える。
1"""Which answer replies carry a tool call the parser cannot read, on baseline day 1 (the 4B) and the model swap (the 0.6B).2A malformed call is found by parsing the reply, because its finish reason is stop either way. The constructed replies3at the end are not recorded and never become spans: they show that the parser rejects what it should."""4import glob5import json6from pathlib import Path78from lib.assistant import MalformedToolCall, parse_tool_call9from lib.dayrun import DATA, run_day_traced10from lib.report import fmt_int111213def check_answers(recording):14 """Parse every answer reply in one recording. Returns the reply count, the replies with a tool call, and the15 message IDs whose reply the parser rejects."""16 paths = sorted(glob.glob(str(DATA / recording / "calls" / "*.json")))17 calls = [json.loads(Path(path).read_text(encoding="utf-8")) for path in paths]18 answers = sorted((call for call in calls if call["kind"] == "model" and call["step"] == "answer"),19 key=lambda call: call["seq"]) # the recorder's sequence number, unique per request20 tool_calls, rejected = 0, []21 for call in answers:22 try:23 tool_calls += parse_tool_call(call["text"]) is not None24 except MalformedToolCall:25 rejected.append(call["message_id"])26 return len(answers), tool_calls, rejected272829answers, tool_calls, rejected = check_answers("baseline-day-1")30print(f"baseline day 1 (4B), answer replies: {fmt_int(answers)}")31print(f"baseline day 1 (4B), replies with a tool call: {fmt_int(tool_calls)}")32print(f"baseline day 1 (4B), malformed tool calls: {fmt_int(len(rejected))}")33# The replay parses the same recorded texts with the same parser, so its count should agree with the parse above.34replayed = sum(run.outcome.malformed_tool_calls for run in run_day_traced("2026-12-08", live=False).runs)35print(f"baseline day 1 (4B), malformed tool calls in the replay: {fmt_int(replayed)}")36assert not rejected and replayed == 03738answers, tool_calls, rejected = check_answers("release-model-swap")39print(f"model swap (0.6B, release r2), answer replies: {fmt_int(answers)}")40print(f"model swap (0.6B, release r2), replies with a tool call: {fmt_int(tool_calls)}") # one call tests nothing41print(f"model swap (0.6B, release r2), malformed tool calls: {fmt_int(len(rejected))}")42assert not rejected4344# Constructed, not recorded: two replies a model could write, passed straight to the parser.45for label, text in {"unclosed block": '<tool_call>{"name": "find_contact", "arguments": {}',46 "body is not JSON": "<tool_call>find the contact</tool_call>"}.items():47 try:48 parse_tool_call(text)49 raise AssertionError(f"{label} was not rejected")50 except MalformedToolCall:51 print(f"constructed reply, {label}, rejected by the parser: yes")
python malformed-tool-calls.pybaseline 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.
1"""What each injected window does to the calls it covers, on the incident day, run live so the contacts server applies its2faults. A timed-out find_contact is two attempts that end ERROR with MCP code -32001, the retry starting after the read3timeout and the retry delay; a refused model request is retried on the assistant's backoff. Every line here is labelled4with its window: injected, not a natural rate."""5import tomllib67from lib import inject8from lib.case import CASE_DIR9from lib.dayrun import run_day_traced10from lib.report import fmt_int, fmt_ms11from lib.tools import REQUEST_TIMEOUT_NS, RETRY_DELAY_NS1213live = run_day_traced("2026-12-09")14# Spans carry no message ID, so each message is found by its trace: the root spans come in arrival order, as the runs do.15roots = sorted((row for row in live.spans if row["name"].startswith("invoke_agent")), key=lambda row: row["trace_seq"])16message_of = {root["trace_id"]: run.message.message_id for root, run in zip(roots, live.runs, strict=True)}17windows = {incident.incident_id: incident for incident in inject.load_incidents()}18schedule = {row["id"]: row for row in tomllib.loads((CASE_DIR / "incidents.toml").read_text(encoding="utf-8"))["incident"]}19finds = [row for row in live.spans if row["name"] == "execute_tool find_contact"]20refused = [row for row in live.spans if row["attributes"].get("error.type") == "RateLimitError"]212223def inside(name, row):24 """Whether a span starts inside the named window (the window's virtual start, inclusive, to its end)."""25 return windows[name].start_ns <= row["start_ns"] < windows[name].end_ns262728def say(name, label, value):29 """Print one labelled value for a window."""30 print(f"{name} (injected), {label}: {value}")313233TIMEOUT = "inc-contacts-timeout"34# The schedule's stamps read 2026-12-09T13:00:00.000000Z, so characters 11 to 16 hold the UTC clock time.35say(TIMEOUT, "window start (UTC)", schedule[TIMEOUT]["start"][11:16])36say(TIMEOUT, "window end (UTC)", schedule[TIMEOUT]["end"][11:16])37timeouts = sorted((row for row in finds if inside(TIMEOUT, row)38 and row["attributes"].get("error.type") == "MCPError"), key=lambda row: row["start_ns"])39assert all(row["status"] == "ERROR" and row["attributes"]["ambrewick.mcp.error_code"] == -32001 for row in timeouts)40assert all(row["end_ns"] - row["start_ns"] == REQUEST_TIMEOUT_NS for row in timeouts) # each attempt waits the read timeout41say(TIMEOUT, "attempts that time out", fmt_int(len(timeouts)))42say(TIMEOUT, "MCP error code", timeouts[0]["attributes"]["ambrewick.mcp.error_code"])43say(TIMEOUT, "read timeout", fmt_ms(REQUEST_TIMEOUT_NS))44pairs = [(a, b) for a, b in zip(timeouts, timeouts[1:]) if a["trace_id"] == b["trace_id"]]45assert all(b["start_ns"] - a["start_ns"] == REQUEST_TIMEOUT_NS + RETRY_DELAY_NS for a, b in pairs)46say(TIMEOUT, "retries", fmt_int(len(pairs)))47say(TIMEOUT, "retry wait", fmt_ms(RETRY_DELAY_NS))48say(TIMEOUT, "retry starts after the first attempt", fmt_ms(pairs[0][1]["start_ns"] - pairs[0][0]["start_ns"]))4950errors = [row for row in finds if inside("inc-mcp-error", row)]51say("inc-mcp-error", "retries", fmt_int(sum(row["attributes"]["ambrewick.attempt"] > 1 for row in errors)))5253replied = [run for run in live.runs if run.outcome.source == "model" and run.message.message_id in schedule["inc-rate-limit"]["message_ids"]]54retried = [run for run in replied if any(message_of[row["trace_id"]] == run.message.message_id for row in refused)]55say("inc-rate-limit", "messages that got a reply after a refused attempt", fmt_int(len(retried)))56assert len(retried) == len(replied) # every reply in the window came after a refusal
python retries-under-incident.pyinc-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
試行ではなくリトライを数える
+10 件の検証Retries under a timeout、8章よりもう一度読む
spanを基にする。1章「1メッセージにつき1トレース」より
trace IDを基にする。1章「スパンを手作業で作る」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
46行目は、リトライではなく、タイムアウトした試行をすべて数えている。この行がタイムアウトの時間枠内のリトライ数を出力するように修正せよ。
仕組み
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.
1"""How often the router chose a route other than the scenario table's, on baseline day 1 (the 4B), the same messages under2the 0.6B (the model swap, from its recorded route replies) and the dev day. Each message's check event on its route span3holds the table's answer; the 0.6B's replies are read with the same parser. The interval is a bootstrap over messages."""4import json5from fractions import Fraction67from lib.assistant import parse_route8from lib.case import load_messages, scenario_to_route9from lib.dayrun import DATA, run_day, run_day_traced10from lib.report import fmt_int, fmt_share11from lib.stats import bootstrap_interval121314def recorded_routes(recording, day):15 """(expected, chosen) for each route reply in one recording, in order. A reply that names no route is the fallback."""16 messages = {message.message_id: message for message in load_messages(day)}17 paths = sorted((DATA / recording / "calls").glob("*.json"))18 calls = sorted((json.loads(path.read_text(encoding="utf-8")) for path in paths), key=lambda call: call["seq"])19 return [(scenario_to_route(messages[c["message_id"]].scenario), parse_route(c["text"]) or "fallback")20 for c in calls if c["kind"] == "model" and c["step"] == "route"]212223traced = run_day_traced("2026-12-08", live=False)24runs = traced.runs25# The check event is on each route span: the trace itself says whether the route was correct.26checks = [event["attributes"] for row in traced.spans for event in row["events"] if event["name"] == "ambrewick.check"]27wrong = [run.outcome.route != run.outcome.expected_route for run in runs]28assert len(checks) == len(runs) and sum(not check["ambrewick.route.correct"] for check in checks) == sum(wrong)29print(f"baseline day 1 (4B), messages: {fmt_int(len(runs))}")30RESAMPLES = 200031low, high = bootstrap_interval(wrong, lambda units: Fraction(sum(units), len(units)), n=RESAMPLES)32print(f"bootstrap resamples of messages, baseline day 1: {fmt_int(RESAMPLES)}")33print(f"wrong routes, baseline day 1, 95% interval: {fmt_share(low.numerator, low.denominator)} to {fmt_share(high.numerator, high.denominator)}")34for route in sorted({run.outcome.expected_route for run in runs}):35 print(f"{route}, wrong routes of {fmt_int(sum(run.outcome.expected_route == route for run in runs))} messages: "36 f"{fmt_int(sum(run.outcome.route != route for run in runs if run.outcome.expected_route == route))}")37print("fallback replies to a scenario that is not fallback, baseline day 1: "38 f"{fmt_int(sum(run.outcome.route == 'fallback' and run.outcome.expected_route != 'fallback' for run in runs))}")3940# The same messages under the 0.6B, from its recorded replies; the 4B's recorded replies must give the replay's count.41base = recorded_routes("baseline-day-1", "2026-12-08")42assert sum(expected != chosen for expected, chosen in base) == sum(wrong)43swap = recorded_routes("release-model-swap", "2026-12-08")44print(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")45print("fallback replies to a scenario that is not fallback, model swap: "46 f"{fmt_int(sum(c == 'fallback' and e != 'fallback' for e, c in swap))}")4748# The dev day's 20 messages, for chapter 1's fallback replies, checked against the same table.49dev = run_day("2026-12-07")50print(f"dev day, messages: {fmt_int(len(dev))}")51print(f"wrong routes, dev day (20 messages): {fmt_int(sum(run.outcome.route != run.outcome.expected_route for run in dev))}")52print(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.pybaseline 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
各メッセージをテーブルに照らして誤りと判定する
+10 件の検証Wrong routes against the labels、8章よりもう一度読む
fallback replyを基にする。1章「20件のメッセージで時間はどこに使われたか」より
spanを基にする。1章「1メッセージにつき1トレース」より
traceを基にする。1章「1メッセージにつき1トレース」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
27行目は空白である。各実行の結果が持つルートと期待ルートを用いて、ルーティングされた選択がシナリオテーブルの答えと異なる場合に、そのメッセージを誤りと判定するように書け。
仕組み
Count the wrong routes that went to a tool
+10 件の検証この部分はまだ翻訳されていないため、英語で表示している。
Wrong routes against the labels、8章よりもう一度読む
attributeを基にする。1章「スパンを手作業で作る」より
spanを基にする。1章「1メッセージにつき1トレース」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
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.
仕組み
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.
1"""Draw, for each scenario route on baseline day 1, how many of its messages the router sent right, to another tool route,2or to the fallback reply. The failing modes are coloured; the modes with no count on this day (truncated replies,3malformed tool calls) are printed as zero and named in the caption. Every value the figure draws is printed first."""4from lib.dayrun import run_day_traced5from lib.figures import ACCENT, INK, MUTED, new_figure, save6from lib.report import fmt_int78traced = run_day_traced("2026-12-08", live=False) # the 4B's real replies, replayed from the recording9runs = traced.runs10malformed = sum(run.outcome.malformed_tool_calls for run in runs) # calls the parser rejected11truncated = sum("length" in row["attributes"]["gen_ai.response.finish_reasons"] # replies cut at the cap12 for row in traced.spans if row["name"].startswith("chat"))13assert malformed == 0 and truncated == 014rows = []15for route in sorted({run.outcome.expected_route for run in runs}):16 group = [run for run in runs if run.outcome.expected_route == route]17 right = sum(run.outcome.route == route for run in group)18 fallback = sum(run.outcome.route == "fallback" and route != "fallback" for run in group)19 other = len(group) - right - fallback20 assert right + fallback + other == len(group)21 rows.append((route, len(group), right, other, fallback))22 print(f"route {route}, messages (n): {fmt_int(len(group))}")23 print(f"route {route}, routed right: {fmt_int(right)}")24 print(f"route {route}, wrong, to another tool route: {fmt_int(other)}")25 print(f"route {route}, wrong, to the fallback reply: {fmt_int(fallback)}")26print(f"truncated replies, baseline day 1: {fmt_int(truncated)}")27print(f"malformed tool calls, baseline day 1: {fmt_int(malformed)}")2829fig, ax = new_figure(height=3.4)30ys = list(range(len(rows)))[::-1] # the first route at the top31for y, (route, n, right, other, fallback) in zip(ys, rows):32 ax.barh(y, right, color=MUTED, alpha=0.35, label="routed right" if y == ys[0] else None)33 ax.barh(y, other, left=right, color=INK, label="wrong, to another tool route" if y == ys[0] else None)34 ax.barh(y, fallback, left=right + other, color=ACCENT, label="wrong, to the fallback reply" if y == ys[0] else None)35ax.set_xlim(0, 1.12 * max(right + other + fallback for _, _, right, other, fallback in rows)) # headroom so the longest bar is not clipped36ax.set_yticks(ys, [f"{route} (n = {n})" for route, n, *_ in rows])37ax.set_xlabel("messages on baseline day 1")38ax.legend(loc="lower right", frameon=False)39save(fig, "failure-modes-by-route")
python figure-failure-modes-by-route.pyroute 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.
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章で示したとおり、アシスタントのエクスポートが書き出すものと同じ行を保持している。
1"""One query per failure mode over the stored rows: baseline day 1 (real) and the incident day (injected, labelled), each2kept in its own receiver file. The baseline's real failures are wrong routes and fallback replies; its span errors and3truncated replies print zero. A receiver holds spans only, so no query here counts a parse failure."""4import tempfile56from lib import query7from lib.dayrun import run_day_traced8from lib.export import write_jsonl9from lib.report import fmt_int1011folder = tempfile.mkdtemp()12baseline = run_day_traced("2026-12-08", live=False)13write_jsonl(f"{folder}/baseline.jsonl", baseline.spans)14incident = run_day_traced("2026-12-09") # live: the contacts server's rows go to the incident day's receiver15write_jsonl(f"{folder}/incident.jsonl", incident.spans + incident.server)16base, inc = query.connect(f"{folder}/baseline.jsonl"), query.connect(f"{folder}/incident.jsonl")1718# A check event sits in the event list of its route span; the route the span chose is in the span's own attributes.19WRONG = """SELECT count(*) FROM spans, UNNEST(from_json(events, '["json"]')) AS t(e)20 WHERE json_extract_string(e, '$.name') = 'ambrewick.check'21 AND json_extract_string(e, '$.attributes."ambrewick.route.correct"') = 'false'"""22FALLBACK = """SELECT count(*) FROM spans, UNNEST(from_json(events, '["json"]')) AS t(e)23 WHERE json_extract_string(e, '$.name') = 'ambrewick.check'24 AND json_extract_string(e, '$.attributes."ambrewick.route.correct"') = 'false'25 AND json_extract_string(attributes, '$."ambrewick.route"') = 'fallback'26 AND json_extract_string(e, '$.attributes."ambrewick.route.expected"') != 'fallback'"""27TRUNCATED = """SELECT count(*) FROM spans WHERE name LIKE 'chat %'28 AND json_extract_string(attributes, '$."gen_ai.response.finish_reasons"') LIKE '%length%'"""29# Each error-result attempt joined to the contacts server's tools/call span in the same trace: one pair per injected error.30PAIRED = """SELECT count(*) FROM spans AS a JOIN spans AS s ON s.trace_id = a.trace_id31 WHERE a.name LIKE 'execute_tool %' AND s.name LIKE 'tools/call %'32 AND a.status = 'ERROR' AND json_extract_string(a.attributes, '$."error.type"') = 'tool_error'33 AND s.status = 'ERROR' AND json_extract_string(s.attributes, '$."error.type"') = 'tool_error'"""34# Errors on tool attempts and on the contacts server's spans, one row per span name and error.type, with a tie-break.35ERRORS = """SELECT name, json_extract_string(attributes, '$."error.type"') AS error_type, count(*) AS n FROM spans36 WHERE status = 'ERROR' AND (name LIKE 'execute_tool %' OR name LIKE 'tools/call %')37 GROUP BY name, error_type ORDER BY n DESC, name, error_type"""38REFUSED = """SELECT count(*) FROM spans WHERE json_extract_string(attributes, '$."error.type"') = 'RateLimitError'"""3940def one(connection, sql):41 return connection.execute(sql).fetchone()[0]424344print("wrong routes, baseline day 1 (real):", fmt_int(one(base, WRONG)))45print("wrong routes, incident day (real):", fmt_int(one(inc, WRONG)))46print("fallback replies to a scenario that is not fallback, baseline day 1 (real):", fmt_int(one(base, FALLBACK)))47print("truncated replies, baseline day 1 (real):", fmt_int(one(base, TRUNCATED)))48print("ERROR tool-attempt and server spans, baseline day 1 (real):", fmt_int(sum(n for *_, n in base.execute(ERRORS).fetchall())))49for name, error_type, n in inc.execute(ERRORS).fetchall():50 print(f"{name}, error.type {error_type}, incident day (injected): {fmt_int(n)}")51print("error-result attempts paired with their server span, incident day (injected):", fmt_int(one(inc, PAIRED)))52print("model requests refused, incident day (injected):", fmt_int(one(inc, REFUSED)))
python failure-modes-query.pywrong 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 と表示され、いずれもインシデント日のファイルに含まれる。
実践ルール: 障害モードごとにクエリを一つ書き、そのクエリが読む属性またはイベントを明示し、ゼロという結果を信頼する前に、そのモードが発生した日で実行すること。どのスパンも持たない属性に対するクエリは、どの日でもゼロを返す。そのゼロは率ではなく、クエリのバグである。
本番環境での障害
本番環境は、インシデント当日と同じ姿をしているわけではない。ここで扱う障害は、ケースの側で配置したものであるため、それぞれを後から時間枠に対応づけることができる。実際の障害にはラベルがない。したがって、時間枠ごとの件数は、事後に誰かが選んだ時間枠で数えた件数であり、その精度はインシデントの開始と終了の記録の精度を超えない。ケースのインシデントファイルのように、その記録を件数の隣に残し、どの件数がそれに由来するかを明記すること。
ほかのライブラリは、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-stepprints the counts that rule gives, andretries-under-incidentshows 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 astool_errorfor anisErrorresult. The registry has no value for a timeout or a 429.error-status-by-stepshows the names, andretries-under-incidentshows 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-incidentprints 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-repliesandwrong-routes-by-labelprint 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-callsprints the parser's counts. - We keep real and injected failures in separate rows and files, and we label every injected count.
failure-modes-queryreads two receivers, anderror-status-by-stepasserts that every ERROR span on the incident day carries the injected label.
この版における本章
第2026.11.2版2026年11月23日時点で例が通過この章の7 例件のうち7件が合格
英語版の書籍(版2026.11.2)から翻訳した。