Set alerts on the assistant's metrics
閱讀約 40 分鐘,8 節 中共有 8 個範例。
Labs
透過實作學習本章
完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。約 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.
助理匯出的指標
追蹤(trace)回答的是一則訊息發生了什麼事。警示需要的則是另一種紀錄:一天中每分鐘都有一個數值,當許多訊息出現變動時,這個數值也隨之變動。第 6 章定義了本章使用的指標(metric)、計數器(counter)與直方圖(histogram),並由它們讀取權杖(token)總數。本節說明助理記錄哪些量測工具,以及每一項計算的是什麼。
助理有一個計量器(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。模型呼叫與工具的直方圖,則定義在同一版本發布的 client inference 與 execute tool 頁面。每個持續時間直方圖的單位皆為秒,且慣例要求失敗的操作須設定 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 則證明第 38 行將訊息直方圖的計數與模型呼叫 span 相比較,因此斷言失敗。請修正第 38 行,使訊息直方圖與正確的 span 進行檢查。
為何有效
需要記住的一點是,匯出內容與追蹤範圍一致。輸入權杖的計數器總計為 104,811 個權杖,而模型呼叫的追蹤範圍加總後同樣是 104,811。訊息直方圖為當天送出的每則訊息保存一個資料點,總共 200 個,範例中的斷言(assertion)會對照追蹤範圍檢查這個數量。在這一天,該直方圖有 1 條序列,即一般訊息的一組屬性。下一節會說明為什麼這個數字值得留意。
實用原則: 警示所用的計數應取自在每項操作結束時就加以記錄的計量器。請在測試中斷言一次,確認計量器的總和等於追蹤範圍的總和,之後每次警示執行時都查詢該指標。
基數
指標是以一條序列為單位來儲存與查詢的。屬性值的每一種相異組合都會開啟一條新的序列,而儀表板為每條序列各畫一條線。只有少數幾個值的屬性,只會增加少數幾條線。若屬性對每位使用者都取一個新值,就會為每位使用者增加一條線,本節其餘部分所檢視的正是這種情況。
指標的基數(cardinality)是記錄該指標時所用的相異屬性組合的數量,每一種組合都是一條需要儲存的序列。
meter 在每個資料點上只保留五個屬性,沒有其他屬性:錯誤類型、代理的名稱、操作的名稱、提示詞版本,以及模型的名稱。慣例的登錄表將這些列為指標屬性,下表則稱之為登錄表屬性。因此,如上一節所印出的結果,在正常的一天裡,實際運作的 meter 只產生一條序列。營運人員最常想要的兩個屬性,也就是路由與使用者,並不在 meter 的資料點上。依據同一批訊息的 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 章「加總 span 會重複計算」
新版次已改變本練習所涵蓋的內容。版次 2026.11.2 的變更內容
第 18 行目前是空白。請將它寫成訊息中所有使用者 ID 的集合,讓下一行可以計算不重複的使用者數量。
為何有效
為什麼使用者 ID 會讓序列倍增
+10 則證明建立於 attribute,出自第 1 章「手動建立 span」
建立於 metric,出自第 6 章「加總 span 會重複計算」
新版次已改變本練習所涵蓋的內容。版次 2026.11.2 的變更內容
輸出顯示,加入使用者 ID 後的序列數量與不重複使用者的數量相符,而不是與訊息數量相符。為什麼加入使用者 ID 會讓序列隨著使用者而增加?
為何有效
同樣的 200 則訊息來自 121 位相異使用者,並分屬 7 條路由。針對各組屬性,訊息直方圖的序列數如下。
| 訊息直方圖上的屬性 | 序列數 |
|---|---|
| 登錄表屬性 | 1 |
| 登錄表屬性與路由 | 7 |
| 登錄表屬性與使用者 ID | 121 |
路由只會增加固定且為數不多的線,本書所用的 7 個值各有一條。使用者則會為每位傳送過訊息的人增加一條線。序列數隨使用者人數而成長,在使用者更多的服務上,就會超過 SDK 的上限,下一段會說明這項上限。
軟體本身也有上限。OpenTelemetry 指標 SDK 預設在一個收集週期內,每個指標串流最多容納 2,000 條序列,超過上限的屬性組合都會落入單一的溢位序列(Metrics SDK, v1.45.0)。溢位序列能保持總數正確,卻隱藏了細節,因此看到溢位序列的營運人員,已經失去了原本可以回答問題的那些線。
基於這個理由,助理的指標不帶使用者 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 秒的目標。慣例建議(SHOULD)invoke_agent 持續時間直方圖的邊界從 0.1 秒到 86,400 秒,這會使 12.8 與 25.6 落在 20 的兩側,而 20 上沒有邊界。助理的計量器自行保有邊界,範圍為 0.5 到 60 秒,由 view 設定,因此 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 小時時間窗與 5 分鐘時間窗,在一天中每個 5 分鐘的刻度上各讀取一次,每個時間窗的計數是同一個直方圖兩次累計讀值之間的差。直方圖只會增加,所以時間窗內的訊息數,就是直方圖在兩次讀取之間新增的部分。範例在每則訊息之後讀取計量器,並將各次讀值依刻度加總。儀表板就是這樣從一個在程序執行期間只增不減的計數器讀出速率。
下面的範例針對事件當天注入的三個時間窗執行,並將每個時間窗視為一種故障:聯絡人伺服器的逾時、模型的速率限制,以及聯絡人伺服器的錯誤回應。對每個時間窗,它會印出截至該時間窗之後第一個刻度的那 1 小時內的訊息數、其中有多少則沒有得到回覆,以及 1 小時與 5 分鐘的燃燒率。這些燃燒率是從該時間窗開始到其結束後 5 分鐘內的最高值。
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 章「加總 span 會重複計算」
新版次已改變本練習所涵蓋的內容。版次 2026.11.2 的變更內容
第 47 行是空白的。請寫出該行,使 in_hour 包含這樣的訊息 span:其結束時間落在該指標的一小時視窗所涵蓋、直到錯誤時間點為止的那一小時內,並且依照直方圖的各次讀取計數的方式來計算。每個 span 資料列都以 end_ns 為鍵,保存以奈秒表示的結束時間。
為何有效
這些 1 小時內的工具嘗試次數,來自計量器自己的工具直方圖 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
表中的計數取自各時間窗之後的第一個刻度,而燃燒率則是從該時間窗開始到其結束後 5 分鐘內的最高值。計數與燃燒率來自不同的刻度,所以將某一列除以另一列,並不會得到燃燒率。
| 指標 | 聯絡人逾時 | 模型速率限制 | 聯絡人錯誤回應 |
|---|---|---|---|
| 時間窗,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 |
| 截至之後第一個刻度的 1 小時內訊息數 | 13 | 15 | 16 |
| 其中沒有回覆的訊息數 | 0 | 11 | 0 |
| 該 1 小時內的工具嘗試次數 | 5 | 2 | 3 |
其中帶有 error.type 的嘗試次數 |
4 | 0 | 3 |
| 1 小時內的最高錯誤燃燒率 | 0.0 | 73.3 | 0.0 |
| 5 分鐘內的最高錯誤燃燒率 | 0.0 | 91.7 | 0.0 |
| 該 1 小時內超過 20 s 的訊息數 | 3 | 1 | 3 |
| 1 小時內的最高延遲燃燒率 | 4.6 | 1.3 | 4.6 |
只有速率限制時間窗會快速消耗錯誤預算。它的那 1 小時內有 11 則訊息沒有回覆,錯誤燃燒率在 1 小時內為 73.3,在 5 分鐘內為 91.7。注入的速率限制拒絕了這些請求,而且拒絕持續的時間比重試退避更久,因此這些訊息最後都沒有得到回覆。
另外兩個時間窗完全沒有消耗錯誤預算,因為其中每一則訊息都得到了回覆。它們的延遲燃燒率(見 1 小時內最高延遲燃燒率那一列)遠低於 14.4,也就是下一節發出告警的燃燒率,而且它們衡量的是緩慢的訊息,不是失敗的訊息。
算術可以說明這個尺度。燃燒率 14.4 會在 50 小時內耗盡整個 30 天的預算,因為 720 小時除以 14.4 等於 50。以這個速度,1 小時會消耗當月預算的 2.0%,下一節的告警門檻之所以是 14.4,原因就在這裡。
實用原則: 以各時間窗內部的計數計算該時間窗的燃燒率,並將計數印在每個燃燒率旁邊。看到 0.0 的讀者需要知道,它代表的是在大量訊息中沒有失敗,還是根本沒有訊息。
事故當天發出一次告警,平靜的一天則無
只用單一視窗的燒耗率(burn rate)告警並不理想。長視窗要等花費累積之後才會觸發,而且只要長視窗還含有那些失敗,就會持續觸發。短視窗遇到短暫的尖峰就會觸發,尖峰一結束便隨即解除。Site Reliability Workbook(O'Reilly,2018)在第 5 章「Alerting on SLOs」中把兩者搭配使用,其表 5-8 給出的呼叫值班(page)條件,是一小時視窗內燒耗率達 14.4,並以五分鐘視窗作為短視窗檢查(該工作手冊)。該表只以燒耗所花掉的預算比例和視窗本身來界定每一種燒耗率,因此在一小時內達到 14.4,就會花掉 30 天預算的 2%。這對 99% 的目標與 99.9% 的目標都成立。改變的只有觸發告警的失敗比例,在此為 14.4% 的訊息。該工作手冊的流量與本書的流量不同,所以其中的 14.4 在這裡只是起點,並不是本書已經做過的量測。
該工作手冊的方法也搭配了較慢的視窗:6 小時視窗、30 分鐘短視窗、燒耗率 6 的呼叫值班條件,花掉 5% 的預算;以及 3 天視窗、6 小時短視窗、燒耗率 1 的工單條件,花掉 10% 的預算。這些條件能抓到一小時視窗組合會漏掉的緩慢而持續的燒耗。一天的流量無法測試它們,這也是本章只設定 1 小時這一組視窗的原因。
本書的告警在以下情況呼叫值班:錯誤燒耗率在該小時內至少為 14.4,在最近五分鐘內也至少為 14.4,而且該小時內至少有 10 則訊息。最後一項條件是本書自訂的。一小時內訊息很少時,一次失敗就會讓燒耗率大幅變動,因此低於下限的一小時不能發出呼叫值班。長視窗使呼叫值班必須有持續的花費,短視窗讓花費停止後呼叫值班得以解除,下限則確保這兩個讀數都有意義。該工作手冊有一節談到流量如此稀少的情況,即「Low-Traffic Services and Error Budget Alerting」,其範例是每小時 10 個 requests。它提出三種做法:產生人工流量、合併小型服務一起監控,或是改變產品。本書的下限不屬於這三種之一。在正式環境中,我們會採用第二種:這樣小的服務在有人依賴其呼叫值班之前,先與較大的服務共用目標。
接下來,告警會在事故當天每五分鐘的每個時間點(tick)上執行,同時針對錯誤目標與延遲目標。
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
事故當天告警只發出一次。第一次觸發在 15:35 UTC,呼叫值班在 15:40 解除。第一次觸發時,該小時內有 11 of 15 則訊息沒有得到回覆。整天之中,錯誤告警在 1 of 288 個時間點觸發,而延遲告警從未觸發,如範例所斷言的那樣。
告警只為速率限制(rate-limit)視窗而觸發,其他皆不然。逾時視窗在這個目標上從未發出呼叫值班。這個視窗是該案例在 13:00 UTC 開始的,錯誤告警在它前後的 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 小時錯誤燒耗率高於門檻的時間較長,因為在五分鐘燒耗率回落之後,那些拒絕仍留在它的一小時之內。1 小時延遲燒耗率從未達到呼叫值班門檻,14.4。一小時的曲線出現缺口,是因為其一小時內的訊息少於下限,全天共有 253 個這樣的時間點。五分鐘的曲線出現缺口,是因為其視窗內沒有任何訊息。
實用原則: 只有在長視窗與短視窗都達到門檻時才呼叫值班,以短視窗來解除呼叫值班,並且不讓任何一個視窗在訊息少於下限的一小時內發出呼叫值班。
在平靜的一天測試同一個警示
平靜的一天是測試的另一半。基準日第 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 章的 span 規則把已復原的訊息算作錯誤,而這裡的目標則不然。兩者都要印出,並各自附上產生它的規則。第 10 章的關卡依 span 狀態計算錯誤,因此第 8 章的錯誤率較為嚴格,在關卡看來不佳的版本,在目標看來可能沒有問題。兩個數字都沒有錯,因為它們回答的是不同的問題。若儀表板把其中一個數字掛上另一個的名稱,就會誤導讀者。
指標上每新增一個屬性,其儲存量與查詢時間都會成倍增加。新增之前,請像基數範例那樣,在一天的真實流量上計算它的序列數,並將該計數與變更一併保存。SDK 在超過上限後寫入的溢位序列,並不是能讓指標繼續有用的備援,而是表示這個屬性選錯了。
**實用原則:**在第一次發出警報之前,先以你自己的流量重新計算燃燒率,並依你的服務在一小時內實際擁有的訊息數來設定下限。
本章的決定
本章的教訓是:以使用者得到什麼為目標,只會對使用者感受得到的故障發出警報,卻會漏掉模型繞過去回答的故障,因此針對助理指標所設的警報,需要第二個數字才看得到這類故障。
- 錯誤目標計算沒有得到回覆的訊息,數據取自持續時間直方圖。Span 錯誤仍留在追蹤中,沿用第 8 章的定義,第 10 章的關卡會讀取這些錯誤。
- 延遲目標是 95% 的訊息在 20 秒內完成,依基準第 1 天的尾端數值設定,並在某個 bucket 的邊界上讀取。
- 當一小時與五分鐘的消耗率都達到 14.4,且該小時內至少有 10 則訊息時,就會發出頁面警報。這組時間窗與起始數字來自工作手冊,最低訊息數則是本書自訂的。
- 指標只帶有登錄表中的屬性。路由與使用者是從 span 計算而得,目的是呈現它們會帶來多少成本,並且不放進計量器。
- 本章沒有設定工具層級或每條路由的目標,因此逾時時段在此目標下不會觸發頁面警報。
- 以使用者得到什麼為依據的警報,只會對使用者感受得到的故障發出警報,而會漏掉模型繞過去回答的故障。要抓到這種故障,需要第二個目標,針對嘗試次數或尾端數值。第 10 章的關卡會在相同訊息上,比較各版本的訊息時間、輸入 token、成本、錯誤率與路由準確度,但它既不讀取嘗試次數,也不讀取尾端數值。
本章,於本版次中
版次 2026.11.2範例於 2026年11 月 23 通過測試8 of 8 個範例 in this chapter pass
譯自英文書,版次 2026.11.2。