找出延迟从何而来

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

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

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

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

实验室

通过动手实践学习本章

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

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

正在查找您的 Lab…

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

读完本章,你将能够说明:在中位数和尾部,是哪一步决定了一条消息的耗时,并且能打印每个数字及其样本数和周围的区间。Ambrewick 的助手用最多五个步骤回答每条消息,它的追踪记录显示了一条消息的每一步,却没有显示是哪一步决定了这条消息的结束。在基线第 1 天,本章读取的 200 条消息中,中位数消息耗时 8,099.3 ms,第 95 百分位耗时 18,351.2 ms。这些时间是花在读取文章、撰写回复,还是等待某个工具上?

这里的每个时间都来自同一台记录机器,即一台 2.10 GHz 的 4 vCPU Intel Xeon,它运行的是 Qwen3-4B-Instruct-2507(下称 4B)。每个时间要么是某次调用的记录时间,要么是这些时间在虚拟时钟上的总和,虚拟时钟见重放与虚拟时钟。这里一条消息的耗时,是它所做的每次调用的记录时间,加上进程内工具的建模时间和 contacts 调用的记录时间,在该时钟上累加而成。记录器还保存了调用之间的时间,而重放没有计入这部分。整天下来,这部分时间合计 651.4 ms,各节会说明其中的数字属于这两者中的哪一种。

本章先构建决定一条消息结束的调用链,再把每次模型调用拆分为读取和撰写两部分,最后讨论尾部,给出每条路由的百分位及其区间。

关键路径决定结束时间

一条消息的追踪是一棵带计时的跨度树,根跨度在回复发出时结束。多数跨度位于根跨度之内,但其中多数并不决定结束时间。要找出真正起决定作用的跨度,可以从根的结束时刻向前回溯:先取最后结束的子跨度,再取在该子跨度开始之前最后结束的子跨度,如此继续,直到回溯到达根的起点。关键路径就是决定一条消息结束时间的跨度链;缩短任何其他跨度,都不会让消息更早结束。缩短链上的某个跨度,消息就会变短,直到另一条链成为更长的那一条。

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

让链中不包含消息自身的 span

+10 项证明

第 20 行用整条路径构建链,因此消息自身的根 span 被算作了一个环节。请修改第 20 行,使链中只包含遍历在根之下到达的那些调用。

path = critical_path(traced.spans)                                       # root first, then the chain in time ordermessage = by_id[path[0]]message_time = message["end_ns"] - message["start_ns"]covered = sum(row["end_ns"] - row["start_ns"] for row in chain)print("message:", slowest.message.message_id)
运行于 Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3

这次运行重放消息 7055,即当天最长的消息,走的是 calendar 路由,其跨度均予保留。回溯得到四个环节:路由调用、一次回答调用、add_event 工具,以及第二次回答调用。输出给出了每个环节的耗时,四者之和等于该消息的 24,305.8 ms。路径上的时间占比为 100.0%,运行中断言这条链覆盖了整条消息。

重放之所以能给出这个占比,是因为其中的调用依次执行,彼此之间没有任何间隔。记录器的间隙本身没有跨度,因此由跨度构建的路径会把它们漏掉,而这条消息的重放中并没有当天出现过的那些间隙。路径涵盖模型调用、进程内工具的建模耗时以及 contacts 调用的记录耗时,除此之外别无其他。检索步骤同样不占时间,因为它的跨度在同一时刻开始并结束。

重叠是重放无法呈现的情形。已记录的消息中没有两个调用同时运行的情况,所以这次运行手工构建了一棵小树。跨度 a 是根,在 10 时结束。跨度 b 从 0 运行到 6,跨度 c 从 2 运行到 9。从结束处回溯,先到达 c,且不会再回到 b,因此路径为 a, c。跨度 b 不在路径上,缩短 b 不会改变结束时间。这一结论只适用于这棵树。路径覆盖了根耗时的 70.0%,所以路径上的跨度只解释了这么多的时间。这正是工作准则所警示的低占比。

工作准则: 调优追踪之前先回溯关键路径,并且只修改路径上的跨度。先看路径占消息时间的比例。比例偏低,说明现有跨度无法解释这段时间,其余部分不属于任何跨度。重放的路径总是覆盖整条消息,因此重放无法告诉你两个重叠的调用中哪一个更重要。

首个数据块时间

回答调用占据了路径的大部分,因此下一个问题是:在一次调用内部,时间花在了哪里。首个数据块时间是指从发出模型调用到收到其回复的第一个流式片段所经过的时间。标签 0.1.0 处的约定用指标 gen_ai.client.inference.time_to_first_chunk 来度量这段等待,该指标是以秒为单位的直方图,仅适用于流式调用,并且仅在有数据块到达时才记录。span 属性 gen_ai.response.time_to_first_chunk 则从逻辑操作的起点开始度量,早于认证和第一次尝试,因此托管客户端的重试也计入其中。第 3 章的名称对照表给出了该软件包对这一指标的命名与标准命名之间的对应关系。

本节的数字来自记录器,而不是来自该指标,这些示例并不运行该指标。记录器对每个流式回复的第一个流事件计时,而该运行时会把这个事件与第一段内容一起发送。本地模型没有需要额外计入的认证步骤。

本节中的每个中位数都附有 95% 区间,其定义见带区间的尾部百分位数。

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

每条消息保留最新的应答调用

+10 项证明

第 20 行对每条消息只保留一个应答调用,但本节指出,输出使用的是一条消息的应答调用中的某一个特定调用。请修改第 20 行,使每条消息保留本节所指明的那个调用。

last_answer = {}for row in sorted(rows, key=lambda r: r["seq"]):          # the sequence numbers give the order the calls were made    if row["step"] == "answer":by_route = defaultdict(list)for message_id, row in last_answer.items():    by_route[routes[message_id]].append(row)
运行于 Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3

输出取每条消息的最后一次回答调用,即写出用户所读回复的那一次调用,并按路由把它的首个数据块时间与总时间并列给出。被路由到兜底回复的消息不会发起回答调用,这一点见第 1 章的说明,因此输出把它们单独计数:共 89 条。200 条用于选择路由的路由调用,其首个数据块的到达时间中位数为 530.2 ms。

回答调用产生首个数据块所需的时间更长。除去含有 7 的 messages 路由,lists 的首个数据块中位数最大,为 8,563.7 ms,来自 13 条消息。其 95% 区间 8,397.1 ms to 8,866.0 ms 高于除 messages 之外的所有其他路由。

在 lists 上,首个数据块占调用时间的 69.5%。在其他路由上,这一占比从 47.7% 到 59.4%。

messages 路由最需要谨慎对待。它的首个数据块中位数为 9,289.0 ms,来自 7 条消息,其 95% 区间 485.7 ms to 12,842.8 ms 是输出中最宽的。

工作准则: 把首个数据块时间与同一次调用的总时间并列打印,并将两者结合起来阅读。首个数据块出现得早,意味着用户较早看到输出,并不意味着这次调用开销小。比较各路由时,应依据区间和占比,不要根据寥寥几条消息就断定某个路由的首个数据块时间。

预填充与生成

第一个数据块要等待提示词,因此接下来的问题是:这段等待中有多少是在读取提示词,又有多少花在别处。预填充是模型读取提示词的阶段;生成是模型逐个词元写出回复的阶段。面向 GPU 的服务系统论文也做了同样的划分:预填充会让计算资源保持忙碌,而每一步解码都会让其中大部分处于空闲(Agrawal et al., Sarathi-Serve,OSDI 2024;关于每次迭代输出一个词元,见 Yu et al., Orca,OSDI 2022)。

本节用到的计数无需新的定义。第 6 章说明了输入词元和输出词元的来源,其中关于缓存输入的一节说明了缓存占比是如何得出的。所评估的词元,就是输入在去掉已缓存的前缀之后剩下的部分,也就是模型实际读取的输入。

这些计数器来自 llama-cpp-python,它为每个上下文提供 llama.cpp 的计数器:已评估的提示词词元数及其耗时,以及已生成的词元数及其耗时。计数器只会累加,因此记录器在每次调用前后取差值。它的四次预热调用发生在每个进程记录第一条消息之前,不计入这一划分。

prefill-generation-split.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通过
"""Split the recorded compute of each model call on baseline day 1 into prefill (the prompt the model read) and generation(the tokens it wrote), from llama.cpp's counters on the recording machine. The split is the method's output: the numbersbelong to that machine, and the method carries to other hardware. The recorder's warm-up call, made before eachprocess's first recorded message, is not recorded, so it is not in the split. Rates are computed from the recorded counts."""from lib.dayrun import DATAfrom lib.report import fmt_int, fmt_shareimport jsonrows = [json.loads(line) for line in (DATA / "baseline-day-1" / "traces.jsonl").read_text(encoding="utf-8").splitlines()]for step in ("route", "answer"):    calls = [row for row in rows if row["step"] == step]    prefill = sum(call["prefill_ns"] for call in calls)    generation = sum(call["gen_ns"] for call in calls)    first_chunk = sum(call["ttfc_ns"] for call in calls)    evaluated = sum(call["tokens_evaluated"] for call in calls)   # the prompt's tokens the model read, minus cached ones    written = sum(call["completion_tokens"] for call in calls)    assert all(call["prefill_ns"] <= call["ttfc_ns"] for call in calls)   # the first chunk waits for the prompt    print(f"{step} calls: {fmt_int(len(calls))}")    print(f"{step}, prefill share of prefill plus generation: {fmt_share(prefill, prefill + generation)}")    print(f"{step}, prefill share of time to first chunk: {fmt_share(prefill, first_chunk)}")    print(f"{step}, prompt tokens evaluated per second of prefill, computed: {evaluated * 1e9 / prefill:.1f}")    print(f"{step}, tokens written per second of generation, computed: {written * 1e9 / generation:.1f}")
输出python prefill-generation-split.py
route calls: 200
route, prefill share of prefill plus generation: 32.8%
route, prefill share of time to first chunk: 72.7%
route, prompt tokens evaluated per second of prefill, computed: 47.6
route, tokens written per second of generation, computed: 7.3
answer calls: 121
answer, prefill share of prefill plus generation: 54.1%
answer, prefill share of time to first chunk: 91.2%
answer, prompt tokens evaluated per second of prefill, computed: 62.3
answer, tokens written per second of generation, computed: 7.0

输出把每一步的计算量划分为两类工作,先列出路由调用。路由调用读取一段固定的指令和消息,回答调用则读取消息以及路由取回的内容。路由调用的第一个数据块要等待它的提示词:预填充占这段等待的 72.7%,但只占该调用计算量的 32.8%。回答调用在同一件事上等待的比重更大。预填充占它们等待第一个数据块时间的 91.2%,所以回复的第一个词主要是在读取提示词。

回答调用的生成速度为每秒 7.0 个词元,预填充每秒评估 62.3 个词元。这些速率由计数算出,只适用于这台机器,原因见小型开源模型:小模型的速度要在某台指定机器上通过记录来测量,不能当作通用规律引用。预填充按已评估的词元计数,而不是按输入词元计数,下一节会说明这一选择为什么重要。

工作准则: 在修改模型调用的提示词或回复长度之前,先把调用的时间划分为预填充和生成。划分要依据计数器,在同一台机器、同样的调用上取得,并与总时间对照着看。当预填充占到第一个数据块时间的大部分时,等待的症结在提示词。当生成占到调用的大部分时间时,症结在回复的长度。

检索上下文与预填充

检索会把文章放进回答调用的提示词,因此检索更多内容的版本,预填充应当更长。对这个版本而言,问题在于长了多少,以及模型是否读取了新增的全部输入。在会进行检索的路由上,top-8 版本最多给回答调用八篇文章,基线版本最多给三篇。路由调用发生在检索之前,所以在两个版本中,它们的提示词都不含文章。

这一比较在两个版本下使用相同的消息,即配对的 60 条:基线第 1 天的消息中,同时也记录了 top-8 版本的那些消息。输出中的 r0 是基线,r3 是 top-8 版本。输出对这些消息上每个版本的回答调用求和,这是求和,不是带区间的比较。第 10 章会对相同的消息配对,并给出差值的区间。

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

在配对的消息上,回答调用在 top-8 版本下的预填充为 289,244.2 ms,基线下为 172,043.5 ms:是后者的 1.68 倍。输出还给出了基线第 1 天所有回答调用上的两个相关系数。

输入随文章增多而增长。输入词元从 20,420 升至 27,326,而已评估词元,即模型读取的输入,从 10,855 升至 17,813。

两个版本跳过的缓存前缀大致相同,基线下为 9,565 个词元,top-8 版本下为 9,513 个,因此模型读取了新增的输入。在 top-8 版本下,有 15 of 33 个配对的回答调用提示词词元增多,没有任何一个减少。

路由调用在提示词中没有任何文章的情况下也出现了差距。在 top-8 版本下,它们评估了 1,209 个词元,基线下为 827 个,而示例断言这些提示词在两个版本下完全相同。

原因在于记录器的缓存。缓存上限为 1 GiB,并优先丢弃最旧的状态,因此在足够多的其他调用之后运行的路由调用,会发现其指令已被丢弃,只能重新读取。记录没有记下缓存命中,所以这一结论来自缓存的规则,而非日志。对大多数路由调用,缓存保存着该指令,共 133 个词元。在 top-8 版本下,有 4 个路由调用重新读取了其中的大部分,基线下为 1 个。

预填充跟随已评估词元,而不是输入。在基线第 1 天的各回答调用中,预填充与已评估词元的相关系数为 0.99,与输入的相关系数为 0.29。模型读过的前缀,只要缓存还保留着,就不会再读一遍,所以输入可以增长而工作量不变,一次调用评估的词元数取决于它之前的那些调用。

**工作准则:**要在与所改版本相同的消息上度量提示词额外带来的预填充,并把已评估词元与输入词元对照着看。输入词元说明提示词有多大。已评估词元说明模型做了多少工作,而在前缀被缓存时,这两个数会分道扬镳。应以工作量为依据采取行动。

这部分尚未翻译,因此以英文显示。

Tail percentiles with intervals

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

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

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

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

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

找出 p95 等于其最大消息的路由

+10 项证明

示例中的第 33 行为空。请把它写出来,使 small 包含消息数少于第 23 行所求计数的路由,并按排序后的顺序排列,与第 24 行使用的顺序相同。

    print(f"{name}, p95: {fmt_ms(nearest_rank(values, 95))}")    print(f"{name}, p95, 95% interval: {fmt_ms(low)} to {fmt_ms(high)}")    print(f"{name}, p99: {fmt_ms(nearest_rank(values, 99))}")print("routes under 20 messages, count:", len(small))print("routes under 20 messages, p95 is their largest message:", ", ".join(small))for name in small:
运行于 Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3
练习 7.4

解释为什么小型路由的区间上限等于其 p95

+10 项证明

alarms 路由的 95% 区间上端与其第 95 百分位数的值相同。下列哪一项能解释这一点?

解释为什么小型路由的区间上限等于其 p95:选出正确的解释
运行于 Python 3.13.16

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

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

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

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

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

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

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

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

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

直方图的桶及其隐藏的信息

直方图不保存消息,只保存计数。一个桶统计落在两个边界之间的值,因此从桶中读出的百分位数,只能精确到所在的桶。标签 0.1.0 下的 GenAI 约定规定,其时长直方图(包括智能体的 gen_ai.client.invoke_agent.duration)的边界应当采用下列数值,单位为秒。本书把它们用于消息时间,也就是本章测量的时长:0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92。服务导出的是其配置所设定的边界,这些边界未必与此相同。

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

选出包含百分位数的桶

+10 项证明

在这份副本中,第 30 行是空白的。请按第 19 行的注释所述的规则编写这一行,使 index 成为包含精确的第 95 百分位数的桶。

exact = nearest_rank(times, 95)rank = math.ceil(95 * n / 100)                                 # the nearest-rank position of the p95low = edges[index - 1] if index else 0                         # its lower edge, as above; the first starts at zerobelow = sum(counts[:index])                                    # messages in the buckets under itestimate = low + round((rank - below) * (edges[index] - low) / counts[index])
运行于 Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3

输出把基线第 1 天的同一批消息计入这些桶,根据计数估算第 95 百分位数,并把估算值与原始消息的最近秩值并列。包含第 95 百分位数的桶,范围从 10,240.0 ms 到 20,480.0 ms。该桶中有 89 条消息,另有 105 条消息位于其下边界或以下。

桶只能把第 95 百分位数定位在这两个边界之间,无法更精确。估算时,桶内的消息被视为均匀分布在整个桶上。这就是 Prometheus 根据桶估算百分位数的规则,它假定桶内为线性分布。其他后端的插值方式可能不同,所以边界一变,估算值也随之变化。此处估算值为 20,019.8 ms,原始消息的最近秩值为 18,351.2 ms,因此这一天的估算值偏高 1,668.6 ms。

figure-bucket-hides-tail.py Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 通过
"""Draw baseline day 1's message times twice, on one millisecond scale: each message as a point in the upper panel, and thebucket counts for the same messages in the lower panel, each bucket drawn across the span it covers. The edges are the onesbucket-edges-hide-tail uses. Every value the figure shows is printed first, and the nearest-rank p95 is drawn as a line."""from lib import genaifrom lib.dayrun import run_dayfrom lib.figures import ACCENT, INK, MUTED, new_figure, savefrom lib.report import fmt_int, fmt_ms, fmt_sharefrom lib.stats import bucket_counts, nearest_rankEDGES_S = genai.BUCKETS["gen_ai.client.invoke_agent.duration"]  # the conventions' advised upper bounds, in seconds, as thereruns = run_day("2026-12-08")times = sorted(run.replied_ns - run.arrived_ns for run in runs)n = len(times)edges = [round(edge * 1_000_000_000) for edge in EDGES_S]      # integer nanoseconds, as every time here iscounts = bucket_counts(times, edges)exact = nearest_rank(times, 95)lows = [0] + edges                                             # each bucket starts at the edge before itprint("messages (n):", fmt_int(n))for number, count in enumerate(counts):    if number < len(edges):        print(f"bucket above {fmt_ms(lows[number])} up to {fmt_ms(edges[number])}: {fmt_int(count)} messages, {fmt_share(count, n)}")    else:        print(f"bucket above {fmt_ms(lows[number])}: {fmt_int(count)} messages, {fmt_share(count, n)}")print("p95, nearest rank of the raw values:", fmt_ms(exact))fig, (top, bottom) = new_figure(rows=2, height=4.6, sharex=True)top.scatter([t / 1e6 for t in times], [(i + 1) / n for i in range(n)], s=10, color=INK, label="each message")for edge in edges:    top.axvline(edge / 1e6, color=MUTED, linestyle=":", linewidth=0.8)top.axvline(exact / 1e6, color=ACCENT, linestyle="--", linewidth=1.2, label="p95, nearest rank")top.set_ylabel("share at or below")top.legend(loc="lower right")highs = edges + [edges[-1] + 10_000_000_000]                   # the last bucket is open; drawn 10 s wide, past the axiscentres = [(lo + hi) / 2 / 1e6 for lo, hi in zip(lows, highs)]widths = [(hi - lo) / 1e6 for lo, hi in zip(lows, highs)]bars = bottom.bar(centres, counts, width=widths, color=MUTED)bottom.bar_label(bars, labels=[fmt_int(c) if c else "" for c in counts], padding=2)   # empty buckets carry no labelbottom.set_xticks([e / 1e6 for e in edges], [f"{e / 1e6:,.0f}" if e >= 10_240_000_000 else "" for e in edges])   # the small edges crowd the leftbottom.set_ylabel("messages")bottom.set_xlim(0, 42000)                                      # set after the ticks, which would widen itbottom.set_ylim(0, max(counts) * 1.15)bottom.set_xlabel("message time, milliseconds; bucket edges as ticks")save(fig, "bucket-hides-tail")
输出python figure-bucket-hides-tail.py
messages (n): 200
bucket above 0.0 ms up to 10.0 ms: 0 messages, 0.0%
bucket above 10.0 ms up to 20.0 ms: 0 messages, 0.0%
bucket above 20.0 ms up to 40.0 ms: 0 messages, 0.0%
bucket above 40.0 ms up to 80.0 ms: 0 messages, 0.0%
bucket above 80.0 ms up to 160.0 ms: 0 messages, 0.0%
bucket above 160.0 ms up to 320.0 ms: 0 messages, 0.0%
bucket above 320.0 ms up to 640.0 ms: 0 messages, 0.0%
bucket above 640.0 ms up to 1,280.0 ms: 21 messages, 10.5%
bucket above 1,280.0 ms up to 2,560.0 ms: 65 messages, 32.5%
bucket above 2,560.0 ms up to 5,120.0 ms: 3 messages, 1.5%
bucket above 5,120.0 ms up to 10,240.0 ms: 16 messages, 8.0%
bucket above 10,240.0 ms up to 20,480.0 ms: 89 messages, 44.5%
bucket above 20,480.0 ms up to 40,960.0 ms: 6 messages, 3.0%
bucket above 40,960.0 ms up to 81,920.0 ms: 0 messages, 0.0%
bucket above 81,920.0 ms: 0 messages, 0.0%
p95, nearest rank of the raw values: 18,351.2 ms
figure: figures/bucket-hides-tail.svg
0.00.20.40.60.81.0share at or beloweach messagep95, nearest rank10,24020,48040,960message time, milliseconds; bucket edges as ticks020406080100messages2165316896
图 7.2 基线第 1 天的消息,分别以点和桶计数表示,第 95 百分位数以虚线表示

图 7.2在同一个毫秒刻度上把这些消息画了两次。上图把每条消息绘制在位于其自身及以下的消息所占的比例处,所以各点逐步上升。点线是桶的边界,虚线是最近秩法得到的第 95 百分位数。下图显示每个桶的计数,按该桶所覆盖的范围绘制。第 95 百分位数的线落在一个较宽的桶内,而下图没有任何信息说明消息位于该桶的哪个位置。这正是桶所丢失的信息,也是估算值出现偏差的原因。

工作准则: 根据你将要提出的问题设定桶边界,并在每个告警阈值附近设置一个边界。当百分位数落在较宽的桶内时,报告该桶及其计数,而不要给出精确到毫秒的估算值,并且尽可能保留原始值。根据桶得到的估算值,只是把一条规则应用于一组边界的结果,边界一变,它也随之变化。

基于记录的服务时间进行排队分析

一条消息的耗时并不只是它自身的处理工作。当一条消息到达时,如果模型正忙于处理另一条消息,它就要等待,而这段等待是用户所见时间的一部分。排队模型可以说明这种等待如何随负载增长。每个到达的消息加入一条队列,服务器每次处理一条消息,负载则是到达的消息所要求占用的服务器时间的比例。

本节中的数字是计算得出的,不是记录下来的。代码对单个服务器建模。消息按随机方式到达,平均到达率由负载决定,这是一个泊松过程:相邻到达之间的间隔相互独立,服从指数分布。每条消息的服务时间取自当天记录的消息时间之一,采用有放回抽样。利特尔定律指出,系统中的平均数量等于其到达率乘以每个项目在系统中平均停留的时间,即 L = λW。利特尔 1961 年的证明确立了这一定律,MIT 关于 M/M/1 队列的课程笔记给出了本节所用的形式。

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

输出涵盖 0.5、0.8 和 0.9 三种负载,每种使用相同的随机种子,随后在存在公式的情形下再做一项检验。记录的消息平均时间为 8,019.0 ms,即每条消息平均占用的服务时间;在负载为 0.5 时,服务器的利用率为 0.50。

服务开始前等待时间的第 95 百分位数,在负载 0.5 时为 27,983.0 ms,在 0.8 时为 82,817.5 ms,在 0.9 时为 179,463.5 ms。等待时间的上升比负载的上升更为陡峭。

系统中的消息数量遵循同样的曲线。在负载为 0.8 时,其平均值为 3.31,而到达率乘以系统内时间得到 3.31。代码根据队列随时间变化的事件求得前者,根据到达率和系统内平均时间求得后者,并断言二者在每种负载下都相等。在从第一次到达持续到最后一次离开的样本路径上,利特尔定律严格成立,因此该断言不允许任何容差。

M/M/1 公式给出单个服务器在指数服务下的系统内平均时间,它仅对指数服务时间精确成立,而记录的时间并不服从指数分布。因此代码先按模拟自身的条件对其进行检验。在负载为 0.8、指数服务、共 200,000 条消息的情形下,模拟得到的系统内平均时间为 40,422.0 ms,公式给出 40,094.8 ms。代码断言二者的差异在 2% 以内。M/G/1 是服务分布任意的单服务器队列,它有自己的平均值公式,本章不做这项检验。

这是对单个服务器的模型,而不是对 Ambrewick 部署的模型。每条消息的全部记录时间被视为一次服务,这正是该队列处理消息的方式,而且其到达时刻忽略了当天实际的到达时间。因此,这些等待时间是具有这种消息组合的单个服务器所会产生的,并不是当天实际发生的情况。

工作准则: 在接受某个尾部数值或增加容量之前,既要在预期的负载下,也要在更高的负载下查看队列。有记录的服务时间时就使用它们,标明模拟计算出的每一个数字,并且只在公式的假设成立时,才用公式来检验模拟。

生产环境中会出什么问题

这些数字离开回放环境后,有三件事会发生变化。第一,生产环境中的 span 会留下空隙。记录器记录的调用间空隙在这一天内合计为 651.4 ms。这些空隙是消息中真实存在的时间,但不属于任何 span,因此由 span 构建的关键路径,覆盖的时间可能少于消息的全部时间。请把关键路径所占的份额与消息时间对照着读,并把偏低的份额当作需要去追查的问题,而不是当作答案。

第二,服务导出的直方图所用的边界由其配置决定,未必是各项约定所建议的边界。按桶读取的百分位数会带上其边界的误差,这一天的消息上的桶估计值就说明了这一点。第 9 章会以这些延迟为依据设定目标,因此在那项决策中也要考虑边界。

第三,每天消息很少的路由,其第 95 百分位数的区间很宽,而只显示点估计值的仪表盘看起来却很精确。请把计数和区间放在同一个面板上,否则就不要在面板上放这个百分位数。

工作准则: 在发布生产环境的延迟数字之前,请在数字旁边打印其计数和区间,并说明它属于哪一种时间:span 的时间、桶的估计值,还是回放的总和。当关键路径的份额或桶的边界未知时,请随数字一并说明,而不要让数字单独出现。

本章做出的决定

下面每一项都是我们可能判断错误的地方。每一项都给出理由,以及检验它的示例。

  • 我们根据各个 span 读出关键路径,并在一棵构造出来的树上展示重叠的情形,因为没有任何一条已记录的消息含有相互重叠的调用。critical-path-one-message 检查该路径是否覆盖整条回放的消息,并检查构造的树中的 span b 不在路径上。
  • 我们把首个数据块的时间与同一次调用的总时间并列报告,并用计数器对它做拆分,这样首个数据块就不会被孤立地解读。time-to-first-chunk-by-route 和 prefill-generation-split 在相同的调用上打印这两者。
  • 我们打印最近秩百分位数及其计数,并对每个第 95 百分位数给出区间,该区间来自对消息做的带种子的自助法重采样。percentiles-by-route 指出消息数不足 20 条的路由,其第 95 百分位数就是它最大的那条消息,并检查正文所依赖的那一处重叠。
  • 我们采用 GenAI 约定建议的消息时间分桶边界,并明确说明这一点,因为某项服务自己的边界可能不同。bucket-edges-hide-tail 打印这一天该估计的误差,figure-bucket-hides-tail 把原始值与计数画在一起。
  • 我们只在已记录的服务时间上模拟队列,并为计算得出的每个队列数字加上标注。queue-on-service-times 根据队列的事件求出系统中的数量,并在每种负载下,用到达率乘以系统内时间来核对它;仅在服务时间服从指数分布时,才检验 M/M/1 公式。
  • 我们只在各路由的区间互不重叠时才为它们的尾部排序,因为一天的消息无法给它们排出先后。这一天里,这样做会使大多数有回答的路由无法排序,所以确定的差别在于路由是否作答,而不在于哪条作答的路由尾部最差。

本章,在本版次中

版次 2026.11.2示例于 2026年11月23日 通过9 of 9个示例 in this chapter pass

译自英文版图书,版次 2026.11.2。

开始实验室

图书始终免费阅读。

查看价格

引用本节

格式

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

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

本页内容

第 7 章,共 12 章: 找出延迟从何而来

  1. 关键路径决定结束时间
  2. 首个数据块时间
  3. 预填充与生成
  4. 检索上下文与预填充
  5. Tail percentiles with intervals
  6. 直方图的桶及其隐藏的信息
  7. 基于记录的服务时间进行排队分析
  8. 生产环境中会出什么问题
  9. 本章做出的决定

返回顶部全部章节