Set alerts on the assistant's metrics
阅读约 39分钟,8节中含8个示例。
实验室
通过动手实践学习本章
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。约 30 秒后打开。
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。Labs 为你运行:每月 40小时。
在你自己的机器上,免费: 下载本书的笔记本,附其代码和数据,来源为 GitHub。
在本书所用版本上运行你的代码
这部分尚未翻译,因此以英文显示。
By the end of this chapter you can set two alerts on a service's metrics, test each one on a normal day and on an incident day, and say what each one misses. On the incident day, lookups to the contacts team's server start timing out at 13:00 UTC. The 13 messages in the hour to 13:15 all got a reply, although both attempts of each lookup timed out. Beside that, the model's rate limit at 15:30 left 11 of 15 messages in its hour with no reply. Which of those numbers would wake someone, and would the same number wake someone on a normal day? The faults on the incident day were injected, at windows the case sets, so nothing below is a record of an outage or a measure of any real service.
The assistant is Ambrewick's back end, and it records its own metrics as it runs. An alert can read those metrics without reading a single span. A metric is cheap to keep for every minute of a day, because it holds a few numbers for each attribute set (chapter 6 defines the form) and not one record for each message. That trade has a cost, which the chapter measures as it goes: a metric can say how many messages failed, but not which ones, and not why.
助手导出的指标
追踪回答的是一条消息发生了什么。告警需要另一种记录:一天中每一分钟都有一个数字,当许多消息的情况发生变化时,这个数字随之变化。第 6 章定义了本章所用的指标、计数器和直方图,并从中读取词元总量。本节说明助手记录哪些仪器(instrument),以及每一个统计什么。
助手有一个计量器(meter),计量器在每个操作结束时记录该操作。共有三个耗时直方图,每种操作各对应一个。一条消息是一次 invoke_agent 操作,因此 gen_ai.invoke_agent.duration 为每条消息保存一个数据点。一次模型调用是一次 chat 操作,gen_ai.client.inference.duration 为每次调用尝试保存一个数据点。一次工具尝试是一次 execute_tool 操作,gen_ai.execute_tool.duration 为每次尝试保存一个数据点。名称和单位来自 GenAI 约定的指标页面,版本为 0.1.0。模型调用和工具直方图定义在同一版本发布的客户端推理页面和执行工具页面上。每个耗时直方图的单位均为秒,约定要求失败的操作设置 error.type。因此,没有得到回复的消息,其在消息直方图中的数据点带有 error.type,告警正是依据这个属性来计数。
计量器还会记录每次模型调用的词元数,记录在第 6 章读取的计数器和逐次调用直方图中。本章的告警不使用它们,但同一个计量器会写入它们,所以下面的导出结果中包含这些数据。
计量器是实时的。告警在一天运行期间读取它,每个数据点在其操作结束时到达计量器。本章的每个示例都在产生测量数据的同一进程中读取计量器。生产环境中的告警则在指标离开进程之后,通过承载它们的任意管道读取相同的指标,该管道不在本书讨论范围之内。
基线第 1 天是没有注入故障的正常一天,因此适合用来检查计量器与跨度(span)是否一致。回放在挂载计量器的情况下运行这一天,随后读回导出结果,并与跨度自身的计数并列对照。
1"""The metrics the assistant exports, from its live meter (chapter 9, `metrics-the-assistant-exports`).23The assistant records each operation as it ends: a message is one `invoke_agent` operation, a model call one `chat`, a4tool attempt one `execute_tool`, and each model call's tokens go to the token counters and histograms. The names and5units come from the pinned registry (lib.genai.METRICS). The export must not lose what the spans count, so the sums6are checked against the spans' own sums."""7from lib.dayrun import run_day_traced8from lib.genai import METRICS9from lib.metrics import DURATION, USAGE, make_alert_meter_provider, totals10from lib.report import fmt_int11from opentelemetry.sdk.metrics.export import InMemoryMetricReader1213DAY = "2026-12-08"14reader = InMemoryMetricReader()15provider = make_alert_meter_provider(reader, service_instance_id=f"{DAY}-export")16traced = run_day_traced(DAY, live=False, meter_provider=provider) # no faults on this day, so no live contacts server1718reader.collect()19series = {} # metric name: its number of series (one per attribute set)20for resource in reader.get_metrics_data().resource_metrics:21 for scope in resource.scope_metrics:22 for metric in scope.metrics:23 series[metric.name] = len(metric.data.data_points)24for name in sorted(series):25 print(f"series, {name}:", fmt_int(series[name]))26 print(f"unit, {name}:", METRICS[name]["unit"])2728spans = lambda op: [row for row in traced.spans if row["attributes"].get("gen_ai.operation.name") == op]29messages, calls, attempts = spans("invoke_agent"), spans("chat"), spans("execute_tool")30print("messages, invoke_agent operations:", fmt_int(len(messages)))31print("model calls, chat operations:", fmt_int(len(calls)))32print("tool attempts, execute_tool operations:", fmt_int(len(attempts)))33sums = totals(reader)34print("input tokens, counter total:", fmt_int(int(sums[USAGE["input"]]["sum"])))35print("input tokens, summed over chat spans:", fmt_int(sum(c["attributes"]["gen_ai.usage.input_tokens"] for c in calls)))36print("message durations, histogram count:", fmt_int(sums[DURATION["invoke_agent"]]["count"]))3738assert sums[DURATION["invoke_agent"]]["count"] == len(messages) # one point per message, none lost39assert sums[DURATION["chat"]]["count"] == len(calls) # one point per model call attempt40assert sums[DURATION["execute_tool"]]["count"] == len(attempts) # one point per tool attempt41assert sums[USAGE["input"]]["sum"] == sum(c["attributes"]["gen_ai.usage.input_tokens"] for c in calls)
python assistant-metrics-export.pyseries, gen_ai.client.inference.duration: 1
unit, gen_ai.client.inference.duration: s
series, gen_ai.client.inference.operation.input_tokens: 1
unit, gen_ai.client.inference.operation.input_tokens: {token}
series, gen_ai.client.inference.operation.output_tokens: 1
unit, gen_ai.client.inference.operation.output_tokens: {token}
series, gen_ai.client.inference.usage.cache_read.input_tokens: 1
unit, gen_ai.client.inference.usage.cache_read.input_tokens: {token}
series, gen_ai.client.inference.usage.input_tokens: 1
unit, gen_ai.client.inference.usage.input_tokens: {token}
series, gen_ai.client.inference.usage.output_tokens: 1
unit, gen_ai.client.inference.usage.output_tokens: {token}
series, gen_ai.execute_tool.duration: 1
unit, gen_ai.execute_tool.duration: s
series, gen_ai.invoke_agent.duration: 1
unit, gen_ai.invoke_agent.duration: s
messages, invoke_agent operations: 200
model calls, chat operations: 321
tool attempts, execute_tool operations: 10
input tokens, counter total: 104,811
input tokens, summed over chat spans: 104,811
message durations, histogram count: 200
让消息直方图与消息对应
+10 项证明建立在 message 的基础上,参见第1章,“一条消息,一条追踪”
建立在 metric 的基础上,参见第6章,“对跨度求和会重复计数”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 38 行把消息直方图的计数与模型调用 span 进行比较,因此断言失败。请修改第 38 行,使消息直方图与正确的 span 进行比对。
原理何在
需要记住的结论是:导出结果与跨度一致。输入词元的计数器总计 104,811 个词元,模型调用的跨度加总后得到同样的 104,811。消息直方图为当天发送的每条消息保存一个数据点,共 200 个,示例的断言会对照跨度检查这一数量。这一天该直方图有 1 个序列,即正常消息的一组属性。下一节将说明为什么要关注这个数字。
工作准则: 告警所用的计数应取自在每个操作结束时进行记录的计量器。在测试中断言一次计量器的总和等于跨度的总和,此后每次告警运行时都查询该指标。
基数
指标按序列逐条存储和查询。属性值的每一种不同组合都会开启一条新的序列,仪表盘为每条序列绘制一条线。只取少数几个值的属性,只会增加几条线。若某个属性为每位用户都取一个新值,就会为每位用户增加一条线,本节余下的内容讨论的正是这种情形。
指标的基数(cardinality)是记录该指标时所用的不同属性组合的数量,每一种组合都是一条需要存储的序列。
计量器在每个数据点上只保留五个属性,没有其他属性:错误类型、智能体名称、操作名称、提示词版本和模型名称。规范的注册表将这些列为指标属性,下表称之为注册表属性。因此,正常的一天里,在线计量器只产生一条序列,正如上一节所打印的那样。运维人员最常需要的两个属性,即路由和用户,并不在计量器的数据点上。根据同一批消息的 span,把它们分别加到消息直方图上,就能看出各自的代价。
1"""Which attributes may label the assistant's duration metric (chapter 9, `cardinality`).23A metric keeps one series for each distinct set of attribute values, and each series is stored and queried. The4registry's attributes give one series for a message's operation on a normal day. A route gives a few more. A user ID5gives one series per user, so the count grows with the traffic and no dashboard can read it. The assistant's live meter6keeps the registry's attributes only, so its count is the first line. The other two are what the same messages would7give with another attribute added, counted from their spans."""8from lib.dayrun import run_day_traced9from lib.metrics import DURATION, METRIC_ATTRIBUTES, make_alert_meter_provider10from lib.report import fmt_int11from opentelemetry.sdk.metrics.export import InMemoryMetricReader1213DAY = "2026-12-08"14reader = InMemoryMetricReader()15provider = make_alert_meter_provider(reader, service_instance_id=f"{DAY}-cardinality")16traced = run_day_traced(DAY, live=False, meter_provider=provider) # the assistant's live meter, registry attributes only17messages = [row for row in traced.spans if row["attributes"].get("gen_ai.operation.name") == "invoke_agent"]18users = {row["attributes"]["ambrewick.user.id"] for row in messages}19routes = {row["attributes"]["ambrewick.route"] for row in messages if row["attributes"].get("ambrewick.route")}20print("messages:", fmt_int(len(messages)))21print("distinct users:", fmt_int(len(users)))22print("distinct routes:", fmt_int(len(routes)))232425def series(reader, name: str | None = None) -> int:26 """The number of series a reader holds, for one metric when a name is given (one per distinct attribute set)."""27 reader.collect()28 return sum(len(metric.data.data_points) for resource in reader.get_metrics_data().resource_metrics29 for scope in resource.scope_metrics for metric in scope.metrics if name in (None, metric.name))303132def series_with(extra: tuple[str, ...]) -> int:33 """The number of series the duration histogram holds when each message carries the registry's attributes and34 the `extra` ones. Values are the messages' real durations; only the count of attribute sets matters here."""35 own = InMemoryMetricReader()36 histogram = make_alert_meter_provider(own, service_instance_id=f"{DAY}-cardinality").get_meter("cardinality") \37 .create_histogram(DURATION["invoke_agent"], unit="s")38 for row in messages:39 attrs = row["attributes"]40 kept = {key: attrs[key] for key in METRIC_ATTRIBUTES + extra if key in attrs}41 histogram.record((row["end_ns"] - row["start_ns"]) / 1_000_000_000, kept)42 return series(own)434445registry = series(reader, DURATION["invoke_agent"])46with_route = series_with(("ambrewick.route",))47with_user = series_with(("ambrewick.user.id",))48print("series, registry attributes:", fmt_int(registry))49print("series, registry attributes and route:", fmt_int(with_route))50print("series, registry attributes and user ID:", fmt_int(with_user))51assert registry == 1 # on a normal day every message is a success with one attribute set52assert with_user == len(users) # a user ID makes one series per user, and no two users share one53assert with_user > with_route > registry # each attribute that varies multiplies the series
python cardinality-of-attributes.pymessages: 200
distinct users: 121
distinct routes: 7
series, registry attributes: 1
series, registry attributes and route: 7
series, registry attributes and user ID: 121
写出用户集合
+10 项证明建立在 attribute 的基础上,参见第1章,“手工构造 span”
建立在 histogram 的基础上,参见第6章,“对跨度求和会重复计数”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 18 行为空。请把它写成各条消息中用户 ID 的集合,以便下一行统计不同用户的数量。
原理何在
为什么用户 ID 会使序列数成倍增加
+10 项证明建立在 attribute 的基础上,参见第1章,“手工构造 span”
建立在 metric 的基础上,参见第6章,“对跨度求和会重复计数”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
输出显示,带有用户 ID 时的序列数与不同用户的数量一致,而不是与消息数量一致。为什么加入用户 ID 之后,序列数会随用户数而变化?
原理何在
同样的 200 条消息来自 121 位不同的用户,分属 7 条路由。针对每一组属性,消息直方图的序列数如下。
| 消息直方图上的属性 | 序列数 |
|---|---|
| 注册表属性 | 1 |
| 注册表属性和路由 | 7 |
| 注册表属性和用户 ID | 121 |
路由只增加固定的少量线条,本书使用的 7 个取值各对应一条。用户则为每位发送过消息的人增加一条线。线条数随用户数增长,在用户更多的服务上会超出 SDK 的上限,下一段将说明这一上限。
软件本身也有上限。OpenTelemetry 指标 SDK 默认在一个采集周期内,对每个指标流最多保留 2,000 条序列,超出上限的属性集都会落入同一条溢出序列(Metrics SDK, v1.45.0)。溢出序列能保证总量正确,却隐去了细节,因此看到它的运维人员,已经失去了本可回答问题的那些线条。
因此,助手的指标不带用户 ID,本书也从不添加用户 ID。针对用户消息的问题要在追踪中解答:在追踪里,一条消息就是一条记录,其用户只是众多属性之一。关于某位用户延迟的问题,应当去查追踪。告警回答的则是关于整个助手服务的问题。
工作准则: 只用上线前就能列出的取值集合来标记指标。用一天的真实流量统计每个候选属性对应的序列数,凡是序列数随用户数增长的属性,一律舍弃。
服务级别目标
如果一条告警只说失败的消息太多,就还需要一条用来衡量的线,以及一个仍可接受的失败速度。目标本身不会通知任何人,所以告警衡量的是:失败以多快的速度用掉了目标所留下的那部分份额。
目标(objective)是在一个周期内必须成功、或在限定时间内完成的消息所占的比例;错误预算(error budget)是目标允许失败的比例;燃烧率(burn rate)是失败消耗预算的速度,其中燃烧率为 1 表示预算恰好在周期结束时用完。
助手有两个目标。第一个针对失败的消息。在 30 天内,99% 的消息必须得到回复,这留下 1.0% 的错误预算;周期只确定算术,并不预测任何流量。就该目标而言,一条消息失败,是指其用户没有得到回复;重试后恢复的消息不算失败。这比第 8 章的错误更窄。按照 span 规则,一条消息的第一次模型请求被拒绝而第二次请求得到了回复,它有错误;一条消息的查询两次尝试都超时但模型仍然作出了回复,它同样有错误。本目标两者都不计入,因为这两种情况下用户都得到了回复。兜底回复也是一种回复,所以本目标同样不将其计为失败。兜底回复是否送到了正确的场景,则是第 8 章的错误路由检查要回答的问题。
第二个目标针对延迟:在 30 天内,95% 的消息必须在 20 秒内完成,这条线设在正常一天里最慢消息的耗时之上,由此留下 5.0% 的延迟预算。这个数字来自第 7 章在第 1 章介绍的录制数据上测得的尾部,所以这里的每个时间都是该回放虚拟时钟上的录制时间。在基线第 1 天,消息时间的第 95 百分位数(p95,按最近秩法)为 18,351.2 ms,200 messages,低于 20 秒的目标。约定建议 invoke_agent 时长直方图的边界取 0.1 至 86,400 秒,这是一条 SHOULD 级别的建议,这样 12.8 和 25.6 分处 20 的两侧,而 20 处没有边界。助手的计量器保留自己的边界,为 0.5 至 60 秒,由视图设定,因此 20 秒的目标正好落在某个边界上,不超过 20 秒的消息计数是精确的。第 7 章展示了两个边界之间的估算会对尾部造成什么影响。
基线第 1 天展示了这两个目标在正常一天里留下的余量。
1"""The assistant's two objectives, and the error budget each one leaves (chapter 9, `service-level-objectives`).23The error objective: 99% of messages get a reply. A message that ended with no reply has `error.type` on its duration4point, and it spends the budget. The latency objective: 95% of messages finish within 20 seconds, the book's edge5(chapter 7). The edge sits above baseline day 1's p95, so a normal day meets it. Both are read from the metrics that the6alert reads, on the same day. The 30-day period is the arithmetic's period, not a traffic forecast."""7from decimal import Decimal89from lib.dayrun import run_day_traced10from lib.metrics import DayMeter, burn_rate, tallies_by_tick11from lib.report import fmt_burn, fmt_int, fmt_ms, fmt_share12from lib.stats import nearest_rank1314DAY = "2026-12-08"15ERROR_SLO, LATENCY_SLO, PERIOD_HOURS = 0.99, 0.95, 30 * 2416meter = DayMeter(DAY) # the assistant's live meter, read after each message17traced = run_day_traced(DAY, live=False, meter_provider=meter.provider, after_message=meter.after)18day = tallies_by_tick(meter.marks, DAY)[-1][1] # the last tick's cumulative tally is the whole day19durations = sorted(row["end_ns"] - row["start_ns"] for row in traced.spans20 if row["attributes"].get("gen_ai.operation.name") == "invoke_agent")21p95 = nearest_rank(durations, 95)2223print("error objective, share of messages with a reply:", fmt_share(round(ERROR_SLO * 100), 100))24print("error budget, share of messages that may fail:", fmt_share(round((1 - ERROR_SLO) * 100), 100))25print("latency objective, share of messages within 20 s:", fmt_share(round(LATENCY_SLO * 100), 100))26print("latency budget, share of messages that may run over 20 s:", fmt_share(round((1 - LATENCY_SLO) * 100), 100))27print("messages, baseline day 1:", fmt_int(day.requests))28print("messages with no reply:", fmt_int(day.failed), "of", fmt_int(day.requests))29print("messages within 20 s:", fmt_int(day.within), "of", fmt_int(day.requests), "share", fmt_share(day.within, day.requests))30print("messages over 20 s:", fmt_int(day.slow), "of", fmt_int(day.requests))31print("error budget spent over the day, burn:", fmt_burn(burn_rate(day.failed, day.requests, ERROR_SLO)))32print("latency budget spent over the day, burn:", fmt_burn(burn_rate(day.slow, day.requests, LATENCY_SLO)))33print("p95 of message times, nearest rank, n:", fmt_int(len(durations)), "messages")34print("p95 of message times:", fmt_ms(p95))35print("share of the 30-day budget a 1-hour page at burn 14.4 spends:", fmt_share(Decimal("14.4") * 1, PERIOD_HOURS))3637assert day.failed == 0 # a normal day has no message without a reply38assert day.within / day.requests >= LATENCY_SLO # and meets the latency objective39assert p95 <= 20 * 1_000_000_000 # the edge sits above the day's p95 (chapter 7, P-24)
python slo-and-budget.pyerror objective, share of messages with a reply: 99.0%
error budget, share of messages that may fail: 1.0%
latency objective, share of messages within 20 s: 95.0%
latency budget, share of messages that may run over 20 s: 5.0%
messages, baseline day 1: 200
messages with no reply: 0 of 200
messages within 20 s: 194 of 200 share 97.0%
messages over 20 s: 6 of 200
error budget spent over the day, burn: 0.0
latency budget spent over the day, burn: 0.6
p95 of message times, nearest rank, n: 200 messages
p95 of message times: 18,351.2 ms
share of the 30-day budget a 1-hour page at burn 14.4 spends: 2.0%
按自身目标衡量延迟消耗率
+10 项证明第 32 行输出了延迟消耗率,但它是按错误目标来衡量慢消息的,因此输出的消耗率与延迟预算不符。请修改第 32 行,使慢消息按延迟目标来衡量。
原理何在
两个目标在正常一天都成立,代码对此做了断言。在这一天的消息中,0 of 200 条没有得到回复,6 of 200 条超过了 20 秒。
就整天而言,错误燃烧率为 0.0,延迟燃烧率为 0.6。两者都低于 1,也就是目标所允许的速度。这些就是告警在平静的一天里会读到的燃烧率,后续各节使用同样的这两个目标。
工作准则: 依据正常一天的数字设定每个目标,并在任何告警读取它之前,检查正常一天是否满足它。把目标的错误规则与其计数一起打印出来,以便读者将它与第 8 章的 span 规则区分开。
燃烧率
燃烧率是一种速度,而不是一个计数。只有知道这十四次失败来自多少条消息,以及错误预算有多大,这个数字才有意义。对一个窗口而言,燃烧率等于该窗口中失败消息所占的比例除以错误预算。失败占比本身是两个计数之比,因此燃烧率只是多做一次除法,得到的数值可以在大小不同的窗口之间比较。
本节中的窗口都按虚拟时间计算。一小时窗口和五分钟窗口在一天中的每个五分钟刻度上读取,每个窗口的计数是同一个直方图两次累计读数之差。直方图只增不减,所以窗口内的消息数就是直方图在两次读数之间增加的部分。该示例在每条消息之后读取计量器,并按刻度把各次读数相加。仪表盘从一个只在进程运行期间增长的计数器中读取速率,用的也是这种方式。
下面的示例针对事故日中注入的三个窗口运行,把每个窗口当作一个故障:联系人服务器的超时、模型的速率限制,以及联系人服务器的错误回复。对每个窗口,它会打印截至窗口之后第一个刻度的那一小时内的消息数,其中有多少条没有得到回复,以及一小时和五分钟两种窗口的燃烧率。这些燃烧率取从窗口开始到窗口结束后五分钟之间的最高值。
1"""The burn in each window on the incident day (chapter 9, `burn-rate`).23A burn rate is how fast a window spends the error budget. The windows are on virtual time: one hour (the long window)4and five minutes (the short one), each read as the difference between two cumulative reads of the metric at 5-minute5ticks. The live contacts server injects the three incident windows (lib.inject). The counts in each window are checked6against the spans' own counts, so the metric and the spans agree on what happened."""7from lib.clock import VirtualClock8from lib.dayrun import run_day_traced9from lib.inject import load_incidents10from lib.metrics import DayMeter, alert_verdicts, tallies_by_tick11from lib.report import fmt_burn, fmt_int1213DAY, STEP_NS, HOUR_NS = "2026-12-09", 300 * 1_000_000_000, 3600 * 1_000_000_00014MIN_REQUESTS = 10 # a burn counts only over an hour with this many messages (alert)15meter = DayMeter(DAY) # the assistant's live meter, read after each message16traced = run_day_traced(DAY, meter_provider=meter.provider, after_message=meter.after) # live: faults on virtual time17midnight = VirtualClock(DAY).now_ns18tallies = tallies_by_tick(meter.marks, DAY)19errors = alert_verdicts(tallies, slo=0.99, measure="failed") # objective 99%: budget 1%20slow = alert_verdicts(tallies, slo=0.95, measure="slow") # objective 95% within 20 s: budget 5%21messages = [row for row in traced.spans if row["attributes"].get("gen_ai.operation.name") == "invoke_agent"]222324def clock(ns: int) -> str:25 """A virtual time as hours, minutes and seconds UTC, from the day's midnight."""26 offset = (ns - midnight) // 1_000_000_00027 return f"{offset // 3600:02d}:{offset % 3600 // 60:02d}:{offset % 60:02d}"282930for incident in load_incidents():31 first = -(-(incident.end_ns - midnight) // STEP_NS) # the first tick at or after the window's end, 1-based32 error, latency = errors[first - 1], slow[first - 1]33 near = [v for v in errors if incident.start_ns < v.tick_ns <= incident.end_ns + STEP_NS]34 counted = {v.tick_ns for v in near if v.long.requests >= MIN_REQUESTS} # the hours a page could read35 print(f"{incident.incident_id}, window:", f"{clock(incident.start_ns)} to {clock(incident.end_ns)} UTC")36 print(f"{incident.incident_id}, first tick after the window:", clock(error.tick_ns))37 print(f"{incident.incident_id}, messages in the hour to that tick:", fmt_int(error.long.requests))38 print(f"{incident.incident_id}, messages with no reply in that hour:", fmt_int(error.long.bad))39 print(f"{incident.incident_id}, error burn, 1 hour:", fmt_burn(error.long.burn))40 print(f"{incident.incident_id}, error burn, 1 hour, highest from the window to 5 minutes after it:",41 fmt_burn(max(v.long.burn for v in errors if v.tick_ns in counted)))42 print(f"{incident.incident_id}, error burn, 5 minutes, highest from the window to 5 minutes after it:",43 fmt_burn(max(v.short.burn for v in errors if v.tick_ns in counted)))44 print(f"{incident.incident_id}, messages over 20 s in that hour:", fmt_int(latency.long.bad))45 print(f"{incident.incident_id}, latency burn, 1 hour, highest from the window to 5 minutes after it:",46 fmt_burn(max(v.long.burn for v in slow if v.tick_ns in counted)))47 in_hour = [row for row in messages if error.tick_ns - HOUR_NS < row["end_ns"] <= error.tick_ns]48 assert len(in_hour) == error.long.requests # the metric's count49 assert sum("error.type" in row["attributes"] for row in in_hour) == error.long.bad # the spans' failures
python burn-rate-by-window.pyinc-contacts-timeout, window: 13:00:00 to 13:12:00 UTC
inc-contacts-timeout, first tick after the window: 13:15:00
inc-contacts-timeout, messages in the hour to that tick: 13
inc-contacts-timeout, messages with no reply in that hour: 0
inc-contacts-timeout, error burn, 1 hour: 0.0
inc-contacts-timeout, error burn, 1 hour, highest from the window to 5 minutes after it: 0.0
inc-contacts-timeout, error burn, 5 minutes, highest from the window to 5 minutes after it: 0.0
inc-contacts-timeout, messages over 20 s in that hour: 3
inc-contacts-timeout, latency burn, 1 hour, highest from the window to 5 minutes after it: 4.6
inc-rate-limit, window: 15:30:00 to 15:31:30 UTC
inc-rate-limit, first tick after the window: 15:35:00
inc-rate-limit, messages in the hour to that tick: 15
inc-rate-limit, messages with no reply in that hour: 11
inc-rate-limit, error burn, 1 hour: 73.3
inc-rate-limit, error burn, 1 hour, highest from the window to 5 minutes after it: 73.3
inc-rate-limit, error burn, 5 minutes, highest from the window to 5 minutes after it: 91.7
inc-rate-limit, messages over 20 s in that hour: 1
inc-rate-limit, latency burn, 1 hour, highest from the window to 5 minutes after it: 1.3
inc-mcp-error, window: 17:00:00 to 17:10:00 UTC
inc-mcp-error, first tick after the window: 17:10:00
inc-mcp-error, messages in the hour to that tick: 16
inc-mcp-error, messages with no reply in that hour: 0
inc-mcp-error, error burn, 1 hour: 0.0
inc-mcp-error, error burn, 1 hour, highest from the window to 5 minutes after it: 0.0
inc-mcp-error, error burn, 5 minutes, highest from the window to 5 minutes after it: 0.0
inc-mcp-error, messages over 20 s in that hour: 3
inc-mcp-error, latency burn, 1 hour, highest from the window to 5 minutes after it: 4.6
选出一小时内读取新增的消息
+10 项证明建立在 error budget 的基础上,参见第9章,“服务级别目标”
建立在 histogram 的基础上,参见第6章,“对跨度求和会重复计数”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 47 行是空白的。请补全这一行,使 in_hour 保存这样的消息跨度:其结束时间落在该指标的一小时窗口所覆盖的那一小时内,该窗口截至错误时刻,并按直方图读取的计数方式计数。每个跨度行都以键 end_ns 保存以纳秒为单位的结束时间。
原理何在
这些小时内的工具尝试次数来自计量器自带的工具直方图 gen_ai.execute_tool.duration,下一个示例以同样的方式在每条消息之后读取它。
1"""The tool attempts in each incident window, read from the assistant's meter (chapter 9, `burn-rate-by-window`).23The meter records gen_ai.execute_tool.duration once for each tool attempt. The example reads that histogram after each4message, so a message's attempts count at its reply, as the alert's ticks do. For each incident window it prints the5attempts in the hour up to the first tick after the window, and how many carry error.type. The day's totals are checked6against the spans, so the meter and the spans agree on every attempt."""7from functools import reduce89from lib.clock import VirtualClock10from lib.dayrun import run_day_traced11from lib.inject import load_incidents12from lib.metrics import DURATION, DayMeter, Tally, tally13from lib.report import fmt_int1415DAY, STEP_NS, HOUR_NS = "2026-12-09", 300 * 1_000_000_000, 3600 * 1_000_000_00016meter, tools, last = DayMeter(DAY), [], [Tally(0, 0, 0)] # the live meter; attempts by reply time; the last read171819def after_message(run) -> None:20 """Read the tool histogram after one message: the attempts it added, keyed by its reply time."""21 now = tally(meter.reader, DURATION["execute_tool"], 20)22 tools.append((run.replied_ns, now - last[0]))23 last[0] = now242526traced = run_day_traced(DAY, meter_provider=meter.provider, after_message=after_message) # live: faults on virtual time27midnight = VirtualClock(DAY).now_ns28calls = [row for row in traced.spans if row["attributes"].get("gen_ai.operation.name") == "execute_tool"]293031def tools_in_hour(tick_ns: int) -> Tally:32 """The tool attempts of the messages that replied in the hour up to a tick."""33 return reduce(Tally.__add__, [added for replied, added in tools if tick_ns - HOUR_NS < replied <= tick_ns],34 Tally(0, 0, 0))353637for incident in load_incidents():38 tick = midnight + -(-(incident.end_ns - midnight) // STEP_NS) * STEP_NS # the first tick after the window39 attempts = tools_in_hour(tick)40 print(f"{incident.incident_id}, tool attempts in the hour to that tick:", fmt_int(attempts.requests))41 print(f"{incident.incident_id}, tool attempts with error.type in that hour:", fmt_int(attempts.failed))4243assert sum(added.requests for _, added in tools) == len(calls) # every attempt, as spans44assert sum(added.failed for _, added in tools) == sum("error.type" in row["attributes"] for row in calls)
python tool-attempts-by-window.pyinc-contacts-timeout, tool attempts in the hour to that tick: 5
inc-contacts-timeout, tool attempts with error.type in that hour: 4
inc-rate-limit, tool attempts in the hour to that tick: 2
inc-rate-limit, tool attempts with error.type in that hour: 0
inc-mcp-error, tool attempts in the hour to that tick: 3
inc-mcp-error, tool attempts with error.type in that hour: 3
表中的计数取窗口之后第一个刻度处的值,而燃烧率取从窗口开始到窗口结束后五分钟之间的最高值。计数和燃烧率来自不同的刻度,所以用某一行除以另一行得不到燃烧率。
| 指标 | 联系人超时 | 模型速率限制 | 联系人错误回复 |
|---|---|---|---|
| 窗口,UTC | 13:00:00 to 13:12:00 UTC | 15:30:00 to 15:31:30 UTC | 17:00:00 to 17:10:00 UTC |
| 截至窗口之后第一个刻度的一小时内的消息数 | 13 | 15 | 16 |
| 其中没有回复的消息数 | 0 | 11 | 0 |
| 该小时内的工具尝试次数 | 5 | 2 | 3 |
其中带有 error.type 的尝试次数 |
4 | 0 | 3 |
| 1 小时内最高错误燃烧率 | 0.0 | 73.3 | 0.0 |
| 5 分钟内最高错误燃烧率 | 0.0 | 91.7 | 0.0 |
| 该小时内超过 20 s 的消息数 | 3 | 1 | 3 |
| 1 小时内最高延迟燃烧率 | 4.6 | 1.3 | 4.6 |
只有速率限制窗口消耗错误预算很快。它那一小时内有 11 条消息没有得到回复,错误燃烧率在一小时窗口上是 73.3,在五分钟窗口上是 91.7。注入的速率限制拒绝了这些请求,而且拒绝持续的时间超过了重试退避,因此这些消息最终没有得到回复。
另外两个窗口完全没有消耗错误预算,因为其中的每条消息都得到了回复。它们的延迟燃烧率见“1 小时内最高延迟燃烧率”一行,远低于 14.4,也就是下一节触发告警的燃烧率;它们衡量的是慢消息,而不是失败的消息。
算术给出了尺度。燃烧率为 14.4 时,整个 30 天的预算会在 50 小时内耗尽,因为 720 小时除以 14.4 等于 50。按这个速度,一小时会消耗当月预算的 2.0%,下一节中的告警阈值取 14.4 就是这个原因。
工作准则: 用窗口内部的计数计算每个窗口的燃烧率,并把计数打印在燃烧率旁边。读者看到 0.0 时,需要知道它表示大量消息中没有失败,还是根本没有消息。
事故日有一次页面告警,平静的一天则一次也没有
只在一个窗口上设置燃烧率告警,效果不佳。长窗口要等消耗累积起来才会触发,并且只要长窗口里还留有失败,它就会一直触发。短窗口遇到短暂的尖峰就会触发,尖峰一结束又立刻解除。《站点可靠性工作手册》(Site Reliability Workbook,O'Reilly,2018)在第 5 章“基于 SLO 的告警”中把两者配对使用,其表 5-8 给出的页面告警条件是:1 小时窗口的燃烧率为 14.4,并用 5 分钟窗口做短窗口检查(该手册)。该表按燃烧所消耗的预算份额和窗口本身来给出各个燃烧率,因此 1 小时内燃烧率为 14.4,会消耗 30 天预算的 2%。这一点对 99% 的目标和 99.9% 的目标同样成立。变化的只是触发它的失败占比,在这里是 14.4% 的消息。该手册的流量与本书的流量并不相同,所以这里的 14.4 只是一个起点,而不是本书做过的测量。
该手册的方法还配对了更慢的窗口:6 小时窗口、燃烧率 6、30 分钟短窗口的页面告警,它消耗 5% 的预算;以及 3 天窗口、燃烧率 1、6 小时短窗口的工单告警,它消耗 10% 的预算。这两组用来捕捉 1 小时这一对窗口漏掉的缓慢而持续的燃烧。一天的流量无法检验它们,所以本章只设置 1 小时这一对。
本书的告警在以下情况下发出页面:1 小时内的错误燃烧率至少为 14.4,最近 5 分钟内的错误燃烧率也至少为 14.4,并且这 1 小时内至少有 10 条消息。最后一个条件是本书自己加的。消息很少时,一次失败就会让燃烧率大幅变动,所以消息数低于下限的一小时不能发出页面。长窗口使页面需要持续的消耗,短窗口使页面在消耗停止后得以解除,而下限保证这两个读数都有意义。该手册有一节专门讨论这类流量稀少的情形,即“低流量服务与错误预算告警”,其示例是每小时 10 个 requests。它给出三种做法:生成人工流量、合并小服务一起监控,或者改变产品。本书的下限不属于这三种。在生产环境中我们会采用第二种:这样小的服务先与一个较大的服务共用目标,之后才让人依赖它的页面告警。
接下来,告警在事故日的每个 5 分钟采样点上运行,分别针对错误目标和延迟目标。
1"""The two-window burn-rate alert, run on the incident day at each 5-minute tick (chapter 9, `an-alert-that-stays-quiet`).23The page fires when the error budget burns at 14.4 or faster over the hour and over the last five minutes, and the hour4holds at least 10 messages, so one failed message in a quiet hour cannot page. 14.4 spends 2% of a 30-day budget in an5hour (chapter 9, `slo-and-budget`). The short window is what lets the page clear once the burn stops. The alert reads the6metric only. It is run for the error objective and for the latency objective, which has the same windows."""7from lib.clock import VirtualClock8from lib.dayrun import run_day_traced9from lib.inject import load_incidents10from lib.metrics import DayMeter, alert_verdicts, tallies_by_tick11from lib.report import fmt_burn, fmt_int1213DAY, STEP_NS, THRESHOLD, MIN_REQUESTS = "2026-12-09", 300 * 1_000_000_000, 14.4, 1014meter = DayMeter(DAY) # the assistant's live meter, read after each message15run_day_traced(DAY, meter_provider=meter.provider, after_message=meter.after) # live: the contacts server injects faults16midnight = VirtualClock(DAY).now_ns17tallies = tallies_by_tick(meter.marks, DAY)18errors = alert_verdicts(tallies, slo=0.99, measure="failed", threshold=THRESHOLD, min_requests=MIN_REQUESTS)19slow = alert_verdicts(tallies, slo=0.95, measure="slow", threshold=THRESHOLD, min_requests=MIN_REQUESTS)202122def clock(ns: int) -> str:23 """A virtual time as hours and minutes UTC, from the day's midnight."""24 offset = (ns - midnight) // 60_000_000_00025 return f"{offset // 60:02d}:{offset % 60:02d}"262728pages = [v for v in errors if v.page]29cleared = next(v for v in errors if v.tick_ns > pages[0].tick_ns and not v.page)30print("page threshold, burn over 1 hour and over 5 minutes:", fmt_burn(THRESHOLD))31print("minimum messages in the hour:", fmt_int(MIN_REQUESTS))32print("ticks where the error page fires:", fmt_int(len(pages)), "of", fmt_int(len(errors)))33print("first tick the error page fires:", clock(pages[0].tick_ns))34print("messages in that hour, with no reply:", fmt_int(pages[0].long.bad), "of", fmt_int(pages[0].long.requests))35print("error burn at that tick, 1 hour and 5 minutes:", fmt_burn(pages[0].long.burn), fmt_burn(pages[0].short.burn))36print("first tick the error page is clear again:", clock(cleared.tick_ns))37print("ticks where the latency page fires:", fmt_int(sum(v.page for v in slow)))38print("highest latency burn over an hour, with the minimum met:",39 fmt_burn(max(v.long.burn for v in slow if v.long.requests >= MIN_REQUESTS)))4041for incident in load_incidents():42 near = [v for v in errors if incident.start_ns < v.tick_ns <= incident.end_ns + STEP_NS]43 print(f"{incident.incident_id}, ticks in or just after the window:", fmt_int(len(near)))44 print(f"{incident.incident_id}, ticks where the error page fires:", fmt_int(sum(v.page for v in near)))4546rate_limit = next(i for i in load_incidents() if i.kind == "rate-limit")47assert pages and all(rate_limit.start_ns < v.tick_ns <= rate_limit.end_ns + STEP_NS for v in pages)48assert sum(v.page for v in slow) == 0 # the latency objective never pages on this day49for incident in load_incidents():50 if incident.kind != "rate-limit":51 assert not any(v.page for v in errors if incident.start_ns < v.tick_ns <= incident.end_ns + STEP_NS)
python alert-on-incident-day.pypage threshold, burn over 1 hour and over 5 minutes: 14.4
minimum messages in the hour: 10
ticks where the error page fires: 1 of 288
first tick the error page fires: 15:35
messages in that hour, with no reply: 11 of 15
error burn at that tick, 1 hour and 5 minutes: 73.3 91.7
first tick the error page is clear again: 15:40
ticks where the latency page fires: 0
highest latency burn over an hour, with the minimum met: 5.0
inc-contacts-timeout, ticks in or just after the window: 3
inc-contacts-timeout, ticks where the error page fires: 0
inc-rate-limit, ticks in or just after the window: 1
inc-rate-limit, ticks where the error page fires: 1
inc-mcp-error, ticks in or just after the window: 3
inc-mcp-error, ticks where the error page fires: 0
事故日里页面告警只发出一次。首次触发在 UTC 15:35,页面在 15:40 解除。首次触发时,这一小时内有 11 of 15 条消息没有得到回复。全天中,错误页面在 1 of 288 个采样点上触发,而延迟页面从未触发,示例对此做了断言。
页面只因限流窗口而触发,别的窗口都不会。超时窗口在这个目标上从不发出页面。该窗口是案例在 UTC 13:00 开始的那一段,错误页面在它前后的 0 个采样点上触发。该窗口内的每次查找都被重试过(2 次重试),每次尝试都超时了(4 次尝试),没有一次重试成功。随后模型根据工具的超时结果写出了回复。两条查找超时的消息得到的回复把责任归于名字,而实际上查找从未应答。每条消息都得到了回复,所以错误目标一条也不计入。
该窗口内的消息反而变慢了。它的延迟燃烧率达到 4.6,而全天在满足下限的前提下最高的延迟燃烧率是 5.0。要让 14.4 的延迟页面触发,需要一小时内 72% 的消息超过 20 秒,即 5.0% 预算的 14.4 倍,而这一天从未接近这个占比。模型绕过去作答的故障不会进入错误目标,延迟目标则需要大得多的慢消息占比才会发出页面。这个故障体现在工具的 ERROR 尝试中,表中的工具行用 gen_ai.execute_tool.duration 来统计它们。
联系人服务器的错误回复是第三个窗口,它在这个目标上表现相同,因为工具的错误结果被交给了模型,模型作了回答而没有重试(0 次重试)。它的消息得到了回复,错误页面在该窗口前后的 0 个采样点上触发。
1"""Draw the burn rate over the incident day, by window, with the page's threshold (chapter 9, `burn-rate-incident-day`).23A burn rate is a rate of budget use, not a count of errors: 14.4 means the window spends the budget 14.4 times as fast4as the objective allows. The one-hour burn is drawn as a gap wherever the hour holds fewer than the minimum of 105messages, since a burn over two or three messages is noise. The five-minute burn is drawn as a gap wherever its window6holds no message, since a zero there would read as no failures among many. The page fires where the hour and the five7minutes both reach the threshold. The peaks are printed so a reader can find the spike on the figure."""8import math910from lib.clock import VirtualClock11from lib.dayrun import run_day_traced12from lib.figures import ACCENT, INK, MUTED, new_figure, save13from lib.metrics import DayMeter, alert_verdicts, tallies_by_tick14from lib.report import fmt_burn, fmt_int1516DAY, THRESHOLD, MIN_REQUESTS = "2026-12-09", 14.4, 1017meter = DayMeter(DAY) # the assistant's live meter, read after each message18run_day_traced(DAY, meter_provider=meter.provider, after_message=meter.after) # live: faults on virtual time19tallies = tallies_by_tick(meter.marks, DAY)20errors = alert_verdicts(tallies, slo=0.99, measure="failed", threshold=THRESHOLD, min_requests=MIN_REQUESTS)21slow = alert_verdicts(tallies, slo=0.95, measure="slow", threshold=THRESHOLD, min_requests=MIN_REQUESTS)22hours = [(v.tick_ns - VirtualClock(DAY).now_ns) / 3_600_000_000_000 for v in errors] # hours from the day's midnight23error_hour = [v.long.burn if v.long.requests >= MIN_REQUESTS else math.nan for v in errors]24error_five = [v.short.burn if v.short.requests else math.nan for v in errors] # no message in five minutes: no burn25latency_hour = [v.long.burn if v.long.requests >= MIN_REQUESTS else math.nan for v in slow]262728def peak(series):29 """The highest value of a series and the first tick that reaches it, as hours and minutes UTC."""30 known = [(x, i) for i, x in enumerate(series) if not math.isnan(x)]31 value = max(x for x, _ in known)32 index = min(i for x, i in known if x == value) # the first tick at the peak, not the last33 minutes = round(hours[index] * 60)34 return fmt_burn(value), f"{minutes // 60:02d}:{minutes % 60:02d}"353637print("gaps, one-hour burn at ticks under the minimum:", fmt_int(sum(math.isnan(x) for x in error_hour)))38print("peak error burn, 1 hour:", *peak(error_hour))39print("peak error burn, 5 minutes:", *peak(error_five))40print("peak latency burn, 1 hour:", *peak(latency_hour))41print("page threshold:", fmt_burn(THRESHOLD))4243fig, ax = new_figure(height=2.8)44ax.plot(hours, error_hour, color=ACCENT, linewidth=1.8, label="error burn, 1 hour")45ax.plot(hours, error_five, color=INK, linewidth=1.2, marker="o", markersize=2.5, label="error burn, 5 minutes")46ax.plot(hours, latency_hour, color=MUTED, linewidth=1.2, linestyle="--", label="latency burn, 1 hour")47ax.axhline(THRESHOLD, color=INK, linewidth=1, linestyle=":", label="page threshold, 14.4")48ax.set_xlim(0, 24)49ax.set_xticks(range(0, 25, 3), [f"{h:02d}:00" for h in range(0, 25, 3)])50ax.set_ylim(0, 130) # headroom above the 91.7 peak, for the legend51ax.set_yticks(range(0, 101, 20))52ax.set_ylabel("burn rate")53ax.legend(loc="upper left", ncol=2, frameon=False) # in the headroom above the data, left of the 15:35 spike54save(fig, "burn-rate-incident-day")
python figure-burn-rate-incident-day.pygaps, one-hour burn at ticks under the minimum: 253
peak error burn, 1 hour: 84.6 15:55
peak error burn, 5 minutes: 91.7 15:35
peak latency burn, 1 hour: 5.0 13:25
page threshold: 14.4
figure: figures/burn-rate-incident-day.svg
图 9.1按值班仪表盘的样子画出事故日:只有一个尖峰越过页面阈值,出现在限流窗口,其他都远未接近。5 分钟错误燃烧率在该窗口内达到峰值,几分钟内就回落,这正是页面得以解除的原因。1 小时错误燃烧率在阈值之上停留得更久,因为在 5 分钟燃烧率回落之后,那些拒绝仍然留在它的一小时之内。1 小时延迟燃烧率从未达到页面阈值 14.4。1 小时曲线在其窗口内消息数少于下限的地方有断点,全天共 253 个采样点。5 分钟曲线在其窗口内没有消息的地方有断点。
工作准则: 只有当长窗口和短窗口都达到阈值时才发出页面,用短窗口来解除页面,并且不让任何一个窗口在消息数少于下限的一小时上发出页面。
在平静的一天测试同一条告警
平静的一天是测试的另一半。基线第 2 天没有注入故障,同一条告警在任何一个时刻都不应对任何一个目标发出页面告警。
1"""The same alert on baseline day 2, a normal day with no injected incident (chapter 9, `an-alert-that-stays-quiet`).23It is the alert's quiet day: the page must not fire at any tick, for either objective. The page is quiet here because no4message fails, not because of the hour's minimum. The day has 80 messages, so most hours hold fewer than the minimum,5and the printed count of the ticks that hold the minimum shows how little of the day the error page could read."""6from lib.dayrun import run_day_traced7from lib.metrics import DayMeter, alert_verdicts, tallies_by_tick8from lib.report import fmt_burn, fmt_int910DAY, THRESHOLD, MIN_REQUESTS = "2026-12-10", 14.4, 1011meter = DayMeter(DAY) # the assistant's live meter, read after each message12run_day_traced(DAY, live=False, meter_provider=meter.provider, after_message=meter.after) # no fault on this day13tallies = tallies_by_tick(meter.marks, DAY)14errors = alert_verdicts(tallies, slo=0.99, measure="failed", threshold=THRESHOLD, min_requests=MIN_REQUESTS)15slow = alert_verdicts(tallies, slo=0.95, measure="slow", threshold=THRESHOLD, min_requests=MIN_REQUESTS)16total = tallies[-1][1]1718print("messages, baseline day 2:", fmt_int(total.requests))19print("messages with no reply:", fmt_int(total.failed))20print("messages over 20 s:", fmt_int(total.slow))21print("ticks where the hour holds the minimum:", fmt_int(sum(v.long.requests >= MIN_REQUESTS for v in errors)),22 "of", fmt_int(len(errors))) # the only ticks a full hour can page on this day23print("highest error burn over an hour:", fmt_burn(max(v.long.burn for v in errors)))24print("highest error burn over 5 minutes:", fmt_burn(max(v.short.burn for v in errors)))25print("highest latency burn over an hour, with the minimum met:",26 fmt_burn(max(v.long.burn for v in slow if v.long.requests >= MIN_REQUESTS)))27print("ticks where the error page fires:", fmt_int(sum(v.page for v in errors)))28print("ticks where the latency page fires:", fmt_int(sum(v.page for v in slow)))2930assert total.failed == 0 # no message on this day ended without a reply31assert not any(v.page for v in errors) # the error page stays quiet at every tick32assert not any(v.page for v in slow) # and so does the latency page
python alert-quiet-on-baseline-day-two.pymessages, baseline day 2: 80
messages with no reply: 0
messages over 20 s: 4
ticks where the hour holds the minimum: 21 of 288
highest error burn over an hour: 0.0
highest error burn over 5 minutes: 0.0
highest latency burn over an hour, with the minimum met: 4.0
ticks where the error page fires: 0
ticks where the latency page fires: 0
基线第 2 天共有 80 条消息,其中 0 条没有得到回复。它的最高错误燃烧率在一小时窗口内为 0.0,在五分钟窗口内为 0.0。
在满足最低消息数的前提下,它的最高延迟燃烧率为 4.0,远低于 14.4。错误页面告警在 0 个时刻触发,代码断言在每一个时刻页面告警都保持安静。
这份平静来自消息本身,而不是来自最低消息数。按这一天的流量,只有 21 of 288 个时刻的一小时窗口达到了最低消息数,也只有在这些时刻,错误页面告警才算读到了完整的一小时。低于最低消息数的一小时,无论其中是什么情况,都不能触发页面告警:九条消息全部失败,也保持沉默。最低消息数防范的是稀疏的一小时里出现单次失败,而在流量稀少的一天里,它决定了大部分判定结果。这条告警在更繁忙的服务上是否可靠,本书的流量无法回答。
**工作准则:**在两天的数据上测试一条告警,一天必须触发页面告警,另一天必须不触发,并把它无法读取的时刻与它给出的判定并排打印出来。
燃烧率告警在何处失明
只统计用户得到了什么的目标,会漏掉模型绕过去作答的每一种故障。在超时窗口中,模型给出的回复没有附上联系方式,而告警页面没有触发。常见的补救办法是再设一个目标:一个针对工具尝试,或者一个针对各路由上最慢消息的延迟。本章的示例两者都没有提供。在这样的流量上,工具层面的告警在这样的流量上也只能看到很少的调用,因为计量器统计的是每一次工具尝试,而基线第 1 天整天只有 10 次。
告警只有在消息结束时才会看到它。等待重试的消息会较晚计入该小时的计数,如果它失败了,这一失败也会较晚到达告警页面。期望故障一开始告警就触发的运维人员,会对每一条在检查时刻仍在运行的消息感到失望。
真实的故障不带标签。本章中的各个窗口是该案例给定的,因此每个计数事后都可以与某个窗口对应起来。生产环境中的告警没有这样的记录,第 8 章的生产环境一节对失败率也说明了同一点。复盘时,请把事故的起止时间与计数放在一起,不要让事后的对应关系充当对告警的衡量。
本章的失败消息率与第 8 章的错误率有意不一致。第 8 章的跨度规则把已恢复的消息算作错误,而这里的目标不这样算。请把两者都打印出来,并各自附上产生它的规则。第 10 章的闸门按跨度状态统计错误,所以第 8 章的错误率更严格,在闸门看来不佳的发布,在该目标看来可能没有问题。两个数字都没有错,因为它们回答的是不同的问题。把其中一个冠以另一个的名称显示在仪表盘上,会造成误导。
指标上每增加一个属性,其存储量和查询时间都会成倍增加。添加之前,请像基数示例那样,在一天的真实流量上统计它的序列数,并把这个数字与变更一并保存。SDK 在超出上限后写入的溢出序列,并不是让指标继续可用的后备办法,它表明所选的属性不对。
工作准则: 在发出第一次告警之前,先用你自己的流量重新计算燃烧率,并根据你的服务每小时实际容纳的消息数来设定最小值。
本章的决定
本章的结论是:以用户收到的结果为依据的目标,会针对用户能感受到的故障发出告警,却会漏掉模型绕开处理的故障,因此对助手指标的告警还需要第二个数字来发现这类故障。
- 错误目标统计没有收到回复的消息,数据读自时长直方图。span 错误仍保留在追踪中,沿用第 8 章的定义,由第 10 章的关卡读取。
- 延迟目标是 95% 的消息在 20 秒内完成,依据基线第 1 天的尾部数据设定,并在某个桶的边界处读取。
- 当一小时窗口和五分钟窗口内的消耗速率都达到 14.4,且这一小时内至少有 10 条消息时,触发告警。这一组窗口和起始数值来自工作手册,最小消息数则是本书自己设定的。
- 指标只携带注册表中的属性。路由和用户是从 span 中统计的,目的是展示它们会带来多大的开销,它们不会进入指标计量。
- 本章没有设定工具级或按路由的目标,因此在这一目标下,超时时间窗口不会触发告警。
- 以用户收到的结果为依据的告警会针对用户能感受到的故障,却会漏掉模型绕开处理的故障。要发现这类故障,需要第二个目标,针对尝试次数或尾部延迟。第 10 章的关卡在相同的消息上,按消息时间、输入 token、成本、错误率和路由准确率比较各个版本,既不读取尝试次数,也不读取尾部延迟。
本章,在本版次中
版次 2026.11.2示例于 2026年11月23日 通过8 of 8个示例 in this chapter pass
译自英文版图书,版次 2026.11.2。