找出失敗的步驟

閱讀約 45 分鐘,9 節 中共有 7 個範例。

版次 2026.11.2 範例於 2026年11 月 23 通過測試 80 個範例中有 80 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.2。 閱讀原文

Labs

透過實作學習本章

完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。約 30 秒內開啟。

完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。由 Labs 為你執行:每月 40 小時。

在 Lab 中開啟,於新分頁開啟

正在檢查您的時數…

正在尋找您的 Lab…

於您自己的電腦,免費: 下載本書的筆記本,連同其程式碼與資料,皆取自 GitHub。

讀完本章,你將能找出一則訊息是哪一個步驟失敗、失敗的頻率,以及失敗的原因,並印出每個計數與其所依據的資料列。本案例直接提出這個問題:沒有得到有用回答的使用者,無法從日誌看出原因。路由器可能把請求送到錯誤的路由,或送到備援回覆。模型可能寫出解析器無法讀取的工具呼叫,或是回覆在詞元上限處被截斷。聯絡人伺服器可能回傳錯誤,或完全沒有回應。這些情況究竟是哪一種,又各發生多少次?

基準第 1 天可以根據它的真實回覆,回答「頻率多高」這個問題。在它的 200 則訊息中,有 41 則被送到錯誤的路由,而且沒有任何一個 span 以錯誤結束。這些就是當天真實的失敗。事故日需要第二種計數,因為它的故障是我們注入的:其一是聯絡人伺服器回應過晚的時段,其二是模型拒絕每一個請求的時段,其三是聯絡人伺服器回傳錯誤結果的時段。每個注入的故障都有標示,其計數放在各自的資料列中,絕不併入基準第 1 天的比率。每一張印出注入計數的表格都會重複該標示,而事故日中沒有任何一項是真實的服務中斷。

重播在重播與虛擬時鐘所述的虛擬時鐘上執行。本案例的流量是為本書產生的,因此這裡的比率只屬於本書,並不代表任何服務。

本章為每一種失敗模式建立一個查詢,從 span 記錄的狀態一路到錯誤的路由。

span 如何記錄失敗

span 以其狀態(status)記錄結果。慣例要求,當操作以錯誤結束時,instrumentation 應將狀態設為 Error;沒有出錯時,則保持未設定(recording errors,v1.45.0)。同一頁也要求在失敗的操作上設定 error.type。

span 的狀態可以是 unset、ok 或 error。error.type 為錯誤命名:使用套件寫出的類別名稱,若有登錄值(registry value)則使用登錄值,如此便能依種類統計失敗。我們不自創任何登錄值。

我們用同一個詞來指稱這件事。錯誤指的是狀態為 ERROR 的 span。只要訊息的任一 span 為 ERROR,該訊息就有錯誤。這正是第 10 章〈the CI gate〉所統計的錯誤。另有兩種不良結果並不算錯誤:回覆在 token 上限處被截斷,屬於品質發現;路由回覆未指出任何路由,也是如此。兩者都會在下文統計,而且都不會設定 span 的狀態。

登錄可供選擇的值很少。其後備值為 _OTHER,對於逾時或 HTTP 429 這兩種本章最常遇到的失敗,它都沒有對應的值。登錄要求值必須可預測且基數低,並將 timeout 與 500 列為範例,而非已定義的值(error.md,v1.45.0)。因此我們寫入套件所拋出的類別名稱:讀取逾時用 MCPError,模型請求遭拒用 RateLimitError,助理自行放棄則用 ModelUnavailable。登錄的範例是完整限定名稱,我們寫的則是簡短類別名稱。其他 instrumentation 會寫完整限定名稱,例如 openai instrumentation 的 openai.RateLimitError,而助理在同一個 span 上自己的 exception.type 也是完整限定的。注入的 429 會拋出本書的 RateLimitError,用來代替客戶端同名的例外。因此這個值屬於本書自訂;若部署使用客戶端自己的例外,在同一位置讀到的會是不同的類別名稱。

例外的記錄與狀態是分開的。OpenTelemetry Python SDK(本書為 1.45.2)記錄例外時,會在 span 上加入 exception 事件,並讓狀態保持未設定。包裝 span 的兩個輔助函式 start_as_current_span 與 use_span 是這項規則的例外:當例外從它們之中逸出時,預設還會將狀態設為 ERROR。recording-errors 頁面要求記錄在不同的位置:該頁指出,使操作失敗的例外應記錄為日誌記錄(log record)。我們建議在接收端保存 span 的期間,保留 SDK 的事件。本章的每個查詢都讀取 span,而計數取決於狀態。擁有日誌管線的部署可以採用另一條路,只要狀態與 error.type 仍會到達 span 即可。

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

依狀態計算失敗的 span

+10 則證明

第 16 行依 span 是否帶有 error.type 來挑出 ERROR span,因此會漏掉所有沒有 error.type 的 ERROR span。請修改第 16 行,使它挑出所有狀態為 ERROR 的 span。

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

Count each error kind, including spans with none

+10 則證明

此部分尚未翻譯,因此以英文呈現。

Line 20 is left blank. Write it so each ERROR span is counted under its span name and its error.type, and a span with no error.type is counted under the value 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 span,而這個零正是重點:錯誤的路由不會設定狀態。因此當日真正的失敗完全不在這張表中,本章其餘部分會以另一種方式統計。事故日採即時執行,讓聯絡人伺服器套用其故障。它有 75 個 ERROR span,範例並斷言其中每一個都帶有注入標籤。

閱讀各列時,先看狀態,再看 error.type。有些 ERROR span 完全沒有 error.type。其一是 MCP SDK 為逾時呼叫所建立的客戶端 span MCP send tools/call find_contact,這類有 4 個。另一種是聯絡人伺服器為注入的當機所建立的 contacts.lookup span,這類有 3 個。上述預設會在當機從 span 逸出時設定 ERROR,而沒有任何機制設定 error.type。單靠 error.type 的計數會兩者皆漏。其餘各列是後續各節說明的種類。被拒絕的模型請求帶有 RateLimitError,共 47 個。未得到回覆的訊息,其根 span 讀作 ModelUnavailable,共 11 個。失敗的聯絡人呼叫以三種名稱出現:助理嘗試上的 execute_tool find_contact、客戶端 span 上的 MCP send tools/call find_contact,以及伺服器 span 上的 tools/call find_contact。關於逾時與錯誤結果的各節會逐一解讀。

實用原則: 依 span 狀態統計失敗,並在每個計數旁印出各個 error.type。沒有 error.type 的 span 仍然是錯誤,因此切勿以該屬性過濾來尋找失敗。真實與注入的計數要分列於不同的列,並在每個注入列出現之處加上標示。

在上限處被截斷的回覆

第一節的狀態規則能攔下會拋出例外的失敗,但回覆在符元上限被截斷時,不會拋出任何例外。有些回覆停止,是因為模型達到了上限,而不是因為它完成了回答。助理會把執行環境回報的結束原因記錄在 gen_ai.response.finish_reasons 中,這是一個陣列,每次生成對應一個項目,順序與該次生成的各個選項相同。結束原因說明模型為何停止:是自行結束(stop),或是在符元上限處停止(length)。GenAI 慣例(版本為 0.1.0)以相同的說法定義推論 span 的值:被中斷的生成會回報供應者給出的原因或 interrupted,而在預期有原因卻未收到時,則回報 error(client inference span,註 18)。因此,結束原因為 length 的回覆不是錯誤,我們也不把它算作錯誤。代理程式框架的結束原因也是同樣的概念。

這個執行環境有兩項事實會影響檢查方式。第一,它從不回報 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 個回答都是自行結束,重播的 chat span 也帶有相同的原因:321 個,全部為 stop。

模型替換版本執行的是 Qwen3-0.6B,並在提示中加入 /no_think,所以它與基準第 1 天的差異,來自較小的模型與這個後綴兩者合併的結果。截斷在這裡出現了。它的路由回覆沒有任何一個被截斷,而它的回答步驟有 1 個回覆被截斷,截斷時為 160 個符元,也就是上限。

那個被截斷的回覆是品質上的發現。該 span 不是錯誤,而使用者收到的是提早中止的回覆。我們把它歸入品質類別,並先閱讀文字內容,再判斷它的意義。

實用原則: 在斷定每個版本的回覆完整之前,先針對每個步驟統計 length 的結束原因,並把上限印在計數旁邊。某一份錄製中的零,無法說明另一份錄製的情況。把被截斷的回覆視為品質上的發現,絕不要歸為錯誤。

無法解析的工具呼叫

模型需要工具時,會在回覆中寫入一個 <tool_call> 區塊,助理再把該區塊讀回來。執行環境的結束原因無法顯示有問題的區塊,因為帶有損壞區塊的回覆仍會自行結束。只有解析回覆,才能發現格式錯誤的呼叫。沒有結尾標籤的區塊屬於格式錯誤;本體不是 JSON 的區塊、沒有名稱的呼叫,或引數不是物件的呼叫也一樣。每個格式錯誤的呼叫會在其訊息上計數一次,助理會告知模型該呼叫無法讀取,並請它不使用工具直接回答。

另一種失敗會影響到工具本身。呼叫可以通過解析,卻仍然無法通過該工具的引數模型。這並不是格式錯誤的回覆。該次工具嘗試會以 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,兩者相符。

模型替換版本採用 Qwen3-0.6B,提示中加入 /no_think,它寫出 57 則回答,其中只有 1 則帶有工具呼叫。該呼叫通過了解析。單一一次呼叫無法檢驗小型模型的工具使用能力,因此本節對此不做任何主張。

兩份記錄都沒有損壞的區塊。為了說明解析器會拒絕什麼,我們把為本章撰寫的兩則回覆直接交給它,它兩則都拒絕了。這兩則回覆從未被記錄,也不會成為 span、資料列或記錄,因此它們與所記錄的那一天無關。

不過,接收端無法發現解析失敗。格式錯誤的回覆會在助理內部引發例外,並計入該訊息的結果,沒有任何 span 會將它記錄為錯誤。因此上述計數來自回覆本身。查詢一節說明了接收端能顯示與不能顯示的內容。

**實用原則:**解析每一則可能帶有工具呼叫的回覆,並以解析器自己的計數來統計格式錯誤的回覆,絕不使用結束原因。把帶有呼叫的回覆列印在該計數旁邊,讓讀者看出這是多麼小的工具使用樣本。

逾時情況下的重試

第一節的狀態規則可以捕捉會引發例外的失敗,而第一個注入的故障正是這類失敗:逾時會跨越行程邊界而引發例外。聯絡人伺服器是獨立的行程,find_contact在其中執行,因此它的失敗會以 MCP SDK 引發例外的形式傳到助理。我們把這個故障注入事故當天。在 13:00 到 13:12 UTC 之間,聯絡人伺服器要等到超過用戶端的讀取逾時 2,000.0 ms 才回應find_contact,用戶端因而放棄。工具包裝層先等待,再重試一次。第 4 章說明了 SDK 如何將該逾時以例外而非回覆的方式引發。

重試是對失敗呼叫的另一次嘗試,並記錄為獨立的 span。我們建議每次嘗試各用一個 span,因此工具呼叫的每次嘗試,都記錄為各自的execute_tool span,並附上ambrewick.attempt編號。失敗的嘗試因此是 ERROR span,而呼叫的成功則出現在成功的那次嘗試上。沒有任何 span 描述整個呼叫。原因見第 4 章的選擇;第一次嘗試的逾時是使用者的訊息所遇到的失敗之一,所以要計入。

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 上執行

這裡事故當天以即時方式執行,由聯絡人伺服器套用故障,每個 span 依其時間窗分組。每一行都標明其時間窗,並註明為注入。在逾時時間窗內,逾時的嘗試有 4 次。每次都以 ERROR 結束,error.type為MCPError,MCP 錯誤碼則記在ambrewick.mcp.error_code上。該錯誤碼為 -32001,這是 SDK 對讀取逾時的稱呼,而不是協定錯誤碼,如第 4 章所述。重試有 2 次。兩則逾時訊息的重試也都逾時,所以工具把逾時的回覆交給模型。每次第二次嘗試都在第一次之後 2,500.0 ms 開始,這等於讀取逾時加上重試前的等待時間。

模型的時間窗運作方式相同,但其失敗是拒絕。時間窗內每個模型請求都得到 429 回應,助理以退避方式重試。每次被拒絕的嘗試是長度為零的 chat span,狀態為 ERROR,error.type為RateLimitError,注入的時間窗拒絕了 47 個請求。退避用盡後,訊息就以沒有回覆告終:有 11 則訊息如此。有一則訊息在一次被拒絕的嘗試之後得到回覆,即 1。依 span 規則,該訊息計為錯誤,儘管其使用者得到了回覆。計數依 span 而定。正式環境一節說明這對比率有何影響。

**實用原則:**即使呼叫之後成功,也要把失敗的嘗試計為失敗,並且在將它計為注入之前,先指明其時間窗。

MCP 錯誤

聯絡人伺服器還有第二種失敗方式,而且它不會拋出任何例外。MCP 工具規格指出,工具本身的失敗會以設定了 isError 的結果回傳,而不是以協定錯誤回傳(tools,修訂版 2026-07-28)。本書使用 2.3.0 的 MCP Python SDK 遵循這項規則。被注入的 mcp-error 時間窗會讓窗內每一次 find_contact 呼叫都以錯誤結果回傳,而用戶端會把這個結果當成一般回覆交還給助理。

錯誤結果不是例外,因此沒有可供命名的例外。該次嘗試以 ERROR 結束,error.type 為 tool_error,這是 MCP 慣例為 isError 結果所定義的值(MCP conventions,v0.1.0)。其狀態描述為「find_contact returned an error result」。系統不會寫入例外事件,也不會接著重試。

事故當天的資料列顯示了三筆紀錄。助理把 3 次嘗試記錄為 tool_error,伺服器也把同樣的呼叫記錄為 tool_error,共 3 筆。該時間窗的重試行顯示 0,所以這些嘗試都沒有被重試。對於這些呼叫,聯絡人伺服器的 contacts.lookup span 同樣是 ERROR,而且不帶有 error.type。慣例要求用戶端 span 也記錄 tool_error,並要求任何失敗的用戶端 span 都帶有 error.type,逾時時則為例外的類別名稱。2.3.0 版的 MCP SDK 在這兩點上都與慣例不同:錯誤結果的用戶端 span 維持未設定,逾時的 span 為 ERROR 但沒有 error.type。在第一個表格中,用戶端唯一的 ERROR 資料列是 4 次逾時。

因此,一次被注入的故障會留下三筆 ERROR 紀錄。若按狀態統計 span 數量,這次故障會被算成三次。使用者的訊息所遇到的失敗是該次嘗試,因為那是這則訊息自己的呼叫所執行的操作。伺服器的 span 是原因,它們透過第 4 章傳遞的脈絡加入該訊息的追蹤。查詢一節把每一次錯誤結果的嘗試與其追蹤中的伺服器 span 配對:3 組。

實用原則: 一次失敗的操作只在呼叫者建立的 span 上計算一次,並對照旁邊伺服器的 span 來找出原因。使用此版本的 MCP SDK 時,遇到錯誤結果應預期用戶端的 span 維持未設定,儘管慣例要求 tool_error;無論如何都以呼叫者的嘗試來計數。

對照標籤找出錯誤路由

錯誤路由是唯一一種在追蹤紀錄(trace)中看不到任何錯誤的失敗。呼叫成功,回覆自行結束,但答案是備援回覆,或是訊息並不需要的工具路由。要找出這類失敗,本書需要一個可信的比對基準,而本案例有這樣的基準。MASSIVE 為每則語句標註一個情境(scenario)。情境表將每個情境對應到一條路由,這些路由是 calendar、alarms、lists、messages、devices、media 與 fallback。情境會被送往能以其工具或文章解決它的路由,只有在沒有任何工具與文章能解決時,才送往 fallback。錯誤路由是指所選的路由與情境表的結果不同。路由器會把它的選擇寫在路由 span 上,該 span 上的檢查事件則記錄情境表的答案,因此追蹤紀錄會記下這次路由是否正確。

備援回覆的定義見第 1 章。情境表補上了它何時才是正確答案的規則:對於沒有任何工具或文章能解決的訊息,它才是正確的,對其他訊息則不是。對任何其他情境給出備援回覆,都屬於錯誤路由,使用者看到的是拒絕回應。這項檢查是程式碼,它讀取的是追蹤紀錄,而不是回覆的文字。判斷答案是否正確是另一項工作,Evaluating LLM Applications說明了讀取回覆內容的檢查方式。

開發日以小規模呈現了這個案例。在 20 則訊息中,有 5 則被路由錯誤,其中 3 則是需要工具或文章的情境卻得到備援回覆。

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

計算被送往工具的錯誤路由

+10 則證明

第 37 行和第 38 行會把退回預設回覆的情況計入其他情境。請修改這兩行,讓範例印出「送往工具路由的錯誤路由,基準日 1:23」這一行,用來取代原本的退回預設回覆那一行,其餘各行維持不變。

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 上執行

在基準線第 1 天,4B 模型有 41 的訊息被路由錯誤。95% 區間為 15.0% to 26.5%,由 2,000 次訊息重抽樣得出。

對於一天 200 則訊息而言,這個區間很寬,解讀比率時應一併參考它。在錯誤路由中,有 18 是對需要工具或文章的情境給出備援回覆,其餘則被送往某條工具路由。

各條路由的差異很大。在情境屬於 messages 路由的訊息中,10,共 17 則,其中每一則都是備援回覆。行事曆是另一個較大的案例:16,共 42 則。

備援情境則呈現相反的錯誤。它們被送往工具路由 11 次,總數為 82。鬧鐘與清單路由完全沒有錯誤路由,但由於分別只有 6 與 7 則訊息,這些零所能說明的很有限。

模型替換版本有 83 of 200 messages 被路由錯誤,其中 68 是對需要工具或文章的情境給出備援回覆。兩個版本回答的是同樣的 200 則訊息。它的提示詞還帶有 /no_think,因此與 4B 的差異來自較小的模型與這個後綴兩者合併的效果。

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 依路由繪出同樣的訊息。每根長條代表情景表中的一條預期路由,內含該路由的訊息,並分成路由正確的、錯誤送往另一條工具路由的,以及錯誤送往備援回覆的。多數錯誤路由集中在行事曆、備援與訊息這幾根長條。這一天有兩種模式的計數為零,即被截斷的回覆與格式錯誤的工具呼叫,圖中並未繪出。第 7 章是依助理所選擇的路由,而不是預期路由,來計算同一天的訊息,所以數字不同:該章為 7 則 messages 與 31 則 media,而此處為 17 與 29。

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 基準線第 1 天各路由的訊息:路由正確、錯誤送往工具路由,或錯誤送往備援回覆

實用原則: 依追蹤紀錄中的情境表檢查每一次路由,將對其他情境的備援回覆與其他錯誤路由分開計算,並且每個比率都附上區間一併列出。只在相同的訊息上比較兩個版本,並在比較旁註明任何後綴或提示詞的變更。

逐一查詢各種失敗模式

每一種失敗模式各用一個查詢,針對接收器(receiver)的資料列執行,而接收器把每一天的資料存放在各自的檔案中。基準日與事故日分開保存,因此注入的資料列不會混入真實的計數。接收器所存放的資料列,與助理的匯出所寫出的相同,如第 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 的工具嘗試與伺服器 span:0。基準日第 1 天格式錯誤的工具呼叫,其真實數量為零,這是依據無法解析的工具呼叫一節中的回覆計算而得,而接收器中沒有可供查詢的資料。

在事故日,同一個工具查詢找出了注入的嘗試:嘗試逾時 4 筆,嘗試的錯誤結果 3 筆,而聯絡人伺服器針對相同呼叫的 span 上有 3 筆。被拒絕的模型請求共 47 筆。這些結果在輸出中都標示為注入,並且都存放在事故日的檔案中。

實用原則: 每一種失敗模式各寫一個查詢,指明它所讀取的屬性或事件,並且先在出現該模式的日子執行,再相信它的零。針對沒有任何 span 帶有的屬性所做的查詢,每一天都會回傳零,而這個零是查詢的錯誤,不是比率。

正式環境中的失敗

最近一次變動於第 2026.11.2 版

正式環境不會和事故當天一樣。這裡的錯誤是由案例安排的,因此事後可以把每一個錯誤對應到某個時間窗。真實的錯誤不帶標籤。依時間窗計算的次數,是事後有人選定的次數,其可靠程度取決於事故起訖時間的紀錄。請把這份紀錄與計數放在一起,如同本案例的事故檔案所做的,並說明哪些計數來自這份紀錄。

其他函式庫會以各自的方式設定狀態。用戶端 span 可能顯示 ERROR 而沒有 error.type,MCP SDK 在第一個表格中對逾時所寫的 span 就是如此。請先依狀態計算失敗次數,並把 error.type 視為附加在每個計數上的標籤,而不是判定為失敗的條件。用戶端函式庫內部的重試也需要留意。位於 3.57.0 的 openai 用戶端預設會在一次呼叫內部重試(max_retries),因此包住該呼叫的檢測程式只會寫出一個 span,而被重試的拒絕回應不會成為 span,span 規則也就無法計入這些回應。若要看到它們,請設定 max_retries=0,並像本書一樣在自己的程式碼中重試。

在自己的程式碼中進行的重試,需要有專屬的屬性。HTTP 慣例為重新送出的 HTTP 請求定義了 http.request.resend_count(HTTP spans,v1.45.0)。該屬性並不描述 MCP 呼叫,因此本書的重試帶有 ambrewick.attempt。請選擇一個能在你的呼叫所用協定中標示嘗試次數的屬性。

最後,span 規則會計入已經恢復的訊息。若一則訊息的第一次模型請求被拒絕,而後續請求得到回覆,它仍計為錯誤,如重試一節所示。第 10 章的閘門把這則已恢復的訊息計為錯誤。第 9 章的目標則計算使用者所見的結果,因此經過重試後得到回覆的訊息在該處不算失敗(服務水準目標)。若某則訊息的第一次工具嘗試逾時而重試成功,同樣會被計入。在事故當天並未出現這種情況,因為兩則逾時訊息的重試也都逾時。如果這兩個數字在你的系統中會呈現不同的情形,請兩者都量測,並在每個數字旁印出產生它的規則。

實用原則: 在發布正式環境的失敗率之前,請印出其計數、所涵蓋的時間窗,以及其中有多少失敗已經恢復。為每一種失敗指明錯誤類型,並說明哪些種類完全沒有類型。當這個數字代表使用者所見的結果時,請依訊息結果計算,如第 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 of 7 個範例 in this chapter pass

譯自英文書,版次 2026.11.2。

開始 Labs

本書仍可免費閱讀。

查看價格

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 8 章,共 12 章: 找出失敗的步驟

  1. span 如何記錄失敗
  2. 在上限處被截斷的回覆
  3. 無法解析的工具呼叫
  4. 逾時情況下的重試
  5. MCP 錯誤
  6. 對照標籤找出錯誤路由
  7. 逐一查詢各種失敗模式
  8. 正式環境中的失敗
  9. What this chapter decided

返回頂端所有章節