找出失败的步骤

阅读约 45分钟,9节中含7个示例。

版次 2026.11.2 示例于 2026年11月23日 通过 80个示例中有80个通过 变化内容

AI 翻译。由人工以英文核验。 我们如何制作图书

译自英文版图书,版次 2026.11.2。 阅读原文

实验室

通过动手实践学习本章

完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。约 30 秒后打开。

完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。Labs 为你运行:每月 40小时。

正在查找您的 Lab…

在你自己的机器上,免费: 下载本书的笔记本,附其代码和数据,来源为 GitHub。

读完本章,你将能够找出一条消息的哪个步骤失败了、失败的频率有多高、原因是什么,并在打印每个计数时附上它所来自的行。本案例把问题提得很直接:用户没有得到有用的回答,却无法从日志中看出原因。路由器可能把请求发到了错误的路由,或发到了兜底回复。模型可能写出了解析器无法读取的工具调用,或者回复在词元上限处被截断。联系人服务器可能返回了错误,或者根本没有返回。这些情况究竟发生了哪一种,又发生了多少次?

基线第 1 天根据其真实回复回答了"频率有多高"这个问题。在它的 200 条消息中,41 条被发到了错误的路由,没有一个跨度以错误结束。这些就是当天真实的失败。事故日需要第二种计数,因为其中的故障是我们注入的:一个时间窗内联系人服务器响应过晚,一个时间窗内模型拒绝每一个请求,还有一个时间窗内联系人服务器返回错误结果。每个注入的故障都带有标签,其计数单独成行,绝不并入基线第 1 天的比率。每张打印注入计数的表都会重复该标签,事故日的任何情况都不是真实的故障。

回放运行在回放与虚拟时钟所述的虚拟时钟上。本案例的流量是为本书生成的,因此这里的比率只属于本书,并不描述任何真实服务。

本章为每种失败模式构建一个查询,从跨度记录的状态一直到错误的路由。

span 如何记录失败

span 在其状态中记录操作的结果。规范要求,当操作以错误结束时,插桩应将状态设为 Error;没有出错时则保持未设置(记录错误,v1.45.0)。同一页面还要求在失败的操作上设置 error.type。

span 的状态为 unset、ok 或 error。error.type 为错误命名:取包所写出的类名;若存在注册表值,则取该值,这样就能按种类统计失败。我们不自创注册表值。

我们对同一件事还使用另一个说法。错误是状态为 ERROR 的 span。一条消息的任一 span 为 ERROR 时,这条消息就有错误。第 10 章CI 关卡统计的正是这种错误。另有两种不良结果不算错误。回复在词元上限处被截断属于质量问题,路由回复未指明任何路由也是如此。两者都在下文统计,且都不会设置 span 的状态。

注册表可供选择的值很少。它的兜底值是 _OTHER,而且没有针对超时或 HTTP 429 的值,这两种失败正是本章遇到最多的。注册表要求取值可预测且基数低,并把 timeout 和 500 列为示例,而不是已定义的值(error.md,v1.45.0)。因此我们写入包所抛出的类名:读取超时用 MCPError,模型请求被拒用 RateLimitError,助手自身的放弃用 ModelUnavailable。我们写的是简短类名,而注册表中的示例是完全限定名。其他插桩写的是限定名,例如 openai 插桩的 openai.RateLimitError,同一 span 上助手自己的 exception.type 也是限定名。注入的 429 抛出本书自带的 RateLimitError,它代替客户端中同名的异常。因此该值属于本书,而使用客户端自身异常的部署,会在同一位置读到不同的类名。

异常的记录与状态是分开的。OpenTelemetry Python SDK(本书中为 1.45.2)记录异常时,会向 span 添加一个 exception 事件,并保持状态未设置。包装 span 的两个辅助函数 start_as_current_span 和 use_span 是这一规则的例外:异常从中逃逸时,它们默认还会把状态设为 ERROR。记录错误的那一页则要求另一种做法:它指出,使操作失败的异常应记录为日志记录。在接收端保存 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

按状态统计失败的跨度

+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 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)用同样的方式定义了推理跨度的取值:被中断的生成会报告提供方给出的原因或 interrupted,而当预期会有原因却没有收到时,则报告 error(见客户端推理跨度,注 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 条回答都是自行结束的,回放中的对话跨度给出的原因也相同:321 个,全部为 stop。

模型替换版本运行 Qwen3-0.6B,并在提示词中加入了 /no_think,因此它与第 1 天基线的差异来自较小的模型和这一后缀两者共同作用。截断出现在这里。它的路由回复没有被截断,而回答步骤有 1 条回复被截断,截断时的词元数为 160,正是上限。

这条被截断的回复是一项质量发现。该跨度不是错误,而用户收到的是一条中途停止的回复。我们把它归入质量问题,先阅读文本,再判断它意味着什么。

工作准则: 在认定某个版本的回复完整之前,先统计它每个步骤的 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 条带有工具调用。该调用解析成功。一次调用无法检验小模型的工具使用能力,因此本节对此不作任何论断。

两份记录都没有损坏的块。为了展示解析器会拒绝什么,我们把为本章编写的两条回复直接交给它,它把两条都拒绝了。这两条回复从未被记录,也不会成为跨度、行或记录,因此它们对已记录的那一天没有任何说明作用。

不过,接收器无法发现解析失败。格式错误的回复在助手内部抛出异常,并计入消息的结果,没有任何跨度把它记录为错误。因此上面的计数来自回复本身。查询一节说明了接收器能显示什么、不能显示什么。

工作准则: 解析每一条可能带有工具调用的回复,并使用解析器自身的计数来统计格式错误的回复,绝不使用结束原因。把带有调用的回复数打印在该计数旁边,让读者看出这份工具使用样本有多小。

超时下的重试

第一节中的状态规则可以捕获抛出异常的失败,而第一个注入的故障就属于这一类:超时会跨进程边界抛出。联系人服务器是一个独立的进程,find_contact在其中运行,因此它的失败会以 MCP SDK 抛出异常的形式传到助手这里。我们把这个故障注入到了事故当天。在 UTC 13:00 到 13:12 之间,联系人服务器对find_contact的应答要等到客户端的读取超时 2,000.0 ms 之后才会到达,客户端于是放弃。工具封装层等待一段时间后再试一次。第 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的结果返回,而不是作为协议错误返回(工具,修订版 2026-07-28)。本书使用的 MCP Python SDK 为 2.3.0,它遵循这一规则。注入的mcp-error时间窗会使窗口内每一次find_contact调用都以错误结果返回,客户端再把该结果作为回复交还给助手。

错误结果不是异常,因此没有可供命名的异常。该次尝试以 ERROR 状态结束,error.type为tool_error,这是 MCP 约定为isError结果定义的取值(MCP 约定,v0.1.0)。其状态描述为"find_contact returned an error result"。系统不会写入异常事件,也不会随后重试。

事故当天的各行显示了三条记录。助手把3次尝试记为tool_error,服务器也把同样的调用记为tool_error,共3次。该窗口的重试行显示为0,因此这些尝试都没有被重试。对于这些调用,联系人服务器的contacts.lookup跨度同样为 ERROR,并且不带error.type。约定要求客户端跨度同样带有tool_error,并要求任何失败的客户端跨度都带有error.type,超时则取异常的类名。2.3.0版本的 MCP SDK 在这两点上都与约定不符:错误结果对应的客户端跨度保持未设置,超时对应的跨度为 ERROR 但没有error.type。在第一张表中,客户端一侧仅有的 ERROR 行是4次超时。

因此,一次注入的故障会留下三条 ERROR 记录。若按状态统计跨度,这一次故障会被计为三次。用户的消息所遇到的失败是那次尝试,因为那是该消息自身的调用所执行的操作。服务器的跨度是原因,它们通过第 4 章传播的上下文加入该消息的追踪。查询一节把每个错误结果尝试与其追踪中的服务器跨度配对:3对。

工作准则: 一次失败的操作只在调用方产生的跨度上计一次,并参照旁边服务器的跨度来查明原因。在此版本的 MCP SDK 下,对于错误结果,客户端的跨度预计保持未设置,尽管约定要求tool_error;无论哪种情况,都以调用方的尝试为准来计数。

对照标签的错误路由

错误路由是唯一一种在追踪记录中不留任何错误的故障。调用成功,回复自行结束,而给出的答案却是兜底回复,或是消息并不需要的工具路由。要找出它,本书需要一个事实依据,本案例有这样一个依据。MASSIVE 为每条话语标注了一个场景。场景表把每个场景映射到一条路由,这些路由是 calendar、alarms、lists、messages、devices、media 和 fallback。场景交给其工具或文章能够解决它的那条路由,只有在没有工具也没有文章能解决时,才交给 fallback。错误路由是指所选路由与表中的路由不一致。路由器把它的选择写在路由跨度上,该跨度上的检查事件则保存表中的答案,因此追踪记录会记下这次路由是否正确。

兜底回复的定义见第 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 条,媒体路由为 31 条,而这里分别是 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 天各路由的消息:路由正确、错误地走向工具路由,或错误地得到兜底回复

工作准则: 在追踪记录上对照场景表检查每次路由,把对其他场景的兜底回复与其他错误路由分开计数,并为每个比率都打印出其区间。只在相同的消息上比较两个版本,并在比较旁注明任何后缀或提示词的改动。

逐一查询各类失败模式

每类失败模式对应一条针对接收器所存行数据的查询,而接收器把每一天的数据保存在各自的文件中。基线日与事故日分开存放,因此注入的行不会混入任何真实计数。接收器保存的行与助手的导出所写入的行相同,第 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 版起由 duckdb2.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 span,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。

开始实验室

图书始终免费阅读。

查看价格

引用本节

格式

每种格式均引用英文原书,本译本以其为准。

每种格式都会注明该版次。其链接会打开当前版次,节标题处会说明该节文本最后一次修改的时间。访问日期和检索日期即为您打开此页的当天。

本页内容

第 8 章,共 12 章: 找出失败的步骤

  1. span 如何记录失败
  2. 在上限处被截断的回复
  3. 无法解析的工具调用
  4. 超时下的重试
  5. MCP 错误
  6. 对照标签的错误路由
  7. 逐一查询各类失败模式
  8. 生产环境中的故障
  9. What this chapter decided

返回顶部全部章节