Set alerts on the assistant's metrics

読了まで約41 分。8 節に8 例を収録。

第2026.11.2版 2026年11月23日時点で例が通過 80 例中 80 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.2)から翻訳した。 原文を読む

Labs

この章を実際に手を動かして学ぶ

すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。約 30 秒で開く。

すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。Labs が実行環境を用意する: 月40 時間。

Labで開く、新しいタブで開く

利用時間を確認しています…

Lab を確認しています…

自分のマシンで、無料: 書籍のノートブックをダウンロード、そのコードとデータを 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.

アシスタントがエクスポートするメトリクス

トレースが答えるのは、1件のメッセージに何が起きたかである。アラートに必要なのは別の種類の記録であり、1日の各分について、多くのメッセージが動いたときに動く数値を持つものである。第6章は、本章で用いるメトリクス、カウンター、ヒストグラムを定義し、それらからトークンの合計を読み取っている。本節では、アシスタントがどのインストルメントを記録し、それぞれが何を数えるかを述べる。

アシスタントはメーターを持ち、メーターは各オペレーションの終了時にそのオペレーションを記録する。所要時間のヒストグラムは3つあり、オペレーションの種類ごとに1つずつである。1件のメッセージは1つのinvoke_agentオペレーションであるため、gen_ai.invoke_agent.durationにはメッセージごとに1つのポイントが入る。1回のモデル呼び出しは1つのchatオペレーションであり、gen_ai.client.inference.durationには呼び出しの試行ごとに1つのポイントが入る。1回のツール試行は1つのexecute_toolオペレーションであり、gen_ai.execute_tool.durationにはその試行ごとに1つのポイントが入る。名前と単位は、バージョン0.1.0のGenAI規約のメトリクスのページに従っている。モデル呼び出しとツールのヒストグラムは、同じバージョンが公開しているクライアント推論とツール実行のページで定義されている。所要時間のヒストグラムはいずれも単位を秒とし、規約は、失敗したオペレーションがerror.typeを設定するよう求めている。したがって、返信が得られなかったメッセージは、メッセージのヒストグラムのポイントにerror.typeを持ち、アラートはこの属性に基づいて数える。

メーターは、各モデル呼び出しのトークンも記録する。これは、第6章が読み取るカウンターと呼び出しごとのヒストグラムに記録される。本章のアラートはこれらを使わないが、同じメーターがそれらを書き込むので、以下のエクスポートには含まれている。

メーターはライブである。アラートは1日が進行している間にメーターを読み取り、各ポイントはそのオペレーションが終了した時点でメーターに届く。本章の各例は、計測を行ったのと同じプロセス内でメーターを読み取る。本番のアラートは、メトリクスがプロセスを離れた後、それを運ぶパイプラインがどのようなものであれ、それを通じて同じメトリクスを読み取る。そのパイプラインは本書の対象外である。

基準日1は、障害を注入していない通常の日であり、メーターがスパンと一致することを確かめるのに適した日である。リプレイはメーターを接続した状態でその日を実行し、その後エクスポートを読み戻して、スパン自身の集計と並べて比較する。

assistant-metrics-export.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 合格
"""The metrics the assistant exports, from its live meter (chapter 9, `metrics-the-assistant-exports`).The assistant records each operation as it ends: a message is one `invoke_agent` operation, a model call one `chat`, atool attempt one `execute_tool`, and each model call's tokens go to the token counters and histograms. The names andunits come from the pinned registry (lib.genai.METRICS). The export must not lose what the spans count, so the sumsare checked against the spans' own sums."""from lib.dayrun import run_day_tracedfrom lib.genai import METRICSfrom lib.metrics import DURATION, USAGE, make_alert_meter_provider, totalsfrom lib.report import fmt_intfrom opentelemetry.sdk.metrics.export import InMemoryMetricReaderDAY = "2026-12-08"reader = InMemoryMetricReader()provider = make_alert_meter_provider(reader, service_instance_id=f"{DAY}-export")traced = run_day_traced(DAY, live=False, meter_provider=provider)   # no faults on this day, so no live contacts serverreader.collect()series = {}                                        # metric name: its number of series (one per attribute set)for resource in reader.get_metrics_data().resource_metrics:    for scope in resource.scope_metrics:        for metric in scope.metrics:            series[metric.name] = len(metric.data.data_points)for name in sorted(series):    print(f"series, {name}:", fmt_int(series[name]))    print(f"unit, {name}:", METRICS[name]["unit"])spans = lambda op: [row for row in traced.spans if row["attributes"].get("gen_ai.operation.name") == op]messages, calls, attempts = spans("invoke_agent"), spans("chat"), spans("execute_tool")print("messages, invoke_agent operations:", fmt_int(len(messages)))print("model calls, chat operations:", fmt_int(len(calls)))print("tool attempts, execute_tool operations:", fmt_int(len(attempts)))sums = totals(reader)print("input tokens, counter total:", fmt_int(int(sums[USAGE["input"]]["sum"])))print("input tokens, summed over chat spans:", fmt_int(sum(c["attributes"]["gen_ai.usage.input_tokens"] for c in calls)))print("message durations, histogram count:", fmt_int(sums[DURATION["invoke_agent"]]["count"]))assert sums[DURATION["invoke_agent"]]["count"] == len(messages)     # one point per message, none lostassert sums[DURATION["chat"]]["count"] == len(calls)                # one point per model call attemptassert sums[DURATION["execute_tool"]]["count"] == len(attempts)     # one point per tool attemptassert sums[USAGE["input"]]["sum"] == sum(c["attributes"]["gen_ai.usage.input_tokens"] for c in calls)
出力python assistant-metrics-export.py
series, 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
演習 9.1

メッセージのヒストグラムをメッセージに対応させる

+10 件の検証

38行目は、メッセージのヒストグラムの件数をモデル呼び出しのスパンと比較しているため、アサーションが失敗する。メッセージのヒストグラムが正しいスパンと照合されるように、38行目を修正せよ。

print("input tokens, summed over chat spans:", fmt_int(sum(c["attributes"]["gen_ai.usage.input_tokens"] for c in calls)))print("message durations, histogram count:", fmt_int(sums[DURATION["invoke_agent"]]["count"]))assert sums[DURATION["chat"]]["count"] == len(calls)                # one point per model call attemptassert sums[DURATION["execute_tool"]]["count"] == len(attempts)     # one point per tool attemptassert sums[USAGE["input"]]["sum"] == sum(c["attributes"]["gen_ai.usage.input_tokens"] for c in calls)
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 で実行される

押さえるべき点は、エクスポートとスパンが一致していることである。入力トークンのカウンターの合計は104,811トークンであり、モデル呼び出しのスパンを合計しても同じ104,811になる。メッセージのヒストグラムには、その日に送られたメッセージごとに1つのポイントが入っており、合計で200である。この件数は、例のアサーションがスパンと照合している。この日、ヒストグラムの系列は1本であり、通常のメッセージ用の属性セットが1つあるだけである。この数がなぜ注視すべき数なのかは、次の節で説明する。

実践ルール: アラートの件数は、各オペレーションを終了時に記録するメーターから取る。メーターの合計がスパンの合計に等しいことは、テストで一度だけアサートし、その後はアラートが動くたびにメトリクスを照会する。

カーディナリティ

メトリクスは、1本の系列(series)ごとに保存され、照会される。属性値の組み合わせが異なるたびに新しい系列が作られ、ダッシュボードは系列ごとに1本の線を描く。取る値が少数の属性が増やす線は数本にとどまる。一方、ユーザーごとに新しい値を取る属性は、ユーザーの数だけ線を増やす。本節の以下の部分で調べるのは、この場合である。

メトリクスのカーディナリティ(cardinality)とは、そのメトリクスが記録される際の属性の組み合わせの異なり数であり、その一つ一つが保存すべき系列となる。

メーターは、各データポイントに5個の属性だけを持たせる。エラーの種類、エージェント名、操作名、プロンプトのバージョン、モデル名である。規約のレジストリはこれらをメトリクスの属性として挙げており、以下の表ではレジストリの属性と呼ぶ。したがって、前の節で出力したとおり、通常の日には実際のメーターが生む系列は1本である。運用者が最も欲しがる2つの属性、すなわちルートとユーザーは、メーターのデータポイントには含まれていない。同じメッセージのスパンから、これらをそれぞれメッセージのヒストグラムに加えてみると、それぞれがどれだけのコストを要するかが分かる。

cardinality-of-attributes.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 合格
"""Which attributes may label the assistant's duration metric (chapter 9, `cardinality`).A metric keeps one series for each distinct set of attribute values, and each series is stored and queried. Theregistry's attributes give one series for a message's operation on a normal day. A route gives a few more. A user IDgives one series per user, so the count grows with the traffic and no dashboard can read it. The assistant's live meterkeeps the registry's attributes only, so its count is the first line. The other two are what the same messages wouldgive with another attribute added, counted from their spans."""from lib.dayrun import run_day_tracedfrom lib.metrics import DURATION, METRIC_ATTRIBUTES, make_alert_meter_providerfrom lib.report import fmt_intfrom opentelemetry.sdk.metrics.export import InMemoryMetricReaderDAY = "2026-12-08"reader = InMemoryMetricReader()provider = make_alert_meter_provider(reader, service_instance_id=f"{DAY}-cardinality")traced = run_day_traced(DAY, live=False, meter_provider=provider)  # the assistant's live meter, registry attributes onlymessages = [row for row in traced.spans if row["attributes"].get("gen_ai.operation.name") == "invoke_agent"]users = {row["attributes"]["ambrewick.user.id"] for row in messages}routes = {row["attributes"]["ambrewick.route"] for row in messages if row["attributes"].get("ambrewick.route")}print("messages:", fmt_int(len(messages)))print("distinct users:", fmt_int(len(users)))print("distinct routes:", fmt_int(len(routes)))def series(reader, name: str | None = None) -> int:    """The number of series a reader holds, for one metric when a name is given (one per distinct attribute set)."""    reader.collect()    return sum(len(metric.data.data_points) for resource in reader.get_metrics_data().resource_metrics               for scope in resource.scope_metrics for metric in scope.metrics if name in (None, metric.name))def series_with(extra: tuple[str, ...]) -> int:    """The number of series the duration histogram holds when each message carries the registry's attributes and    the `extra` ones. Values are the messages' real durations; only the count of attribute sets matters here."""    own = InMemoryMetricReader()    histogram = make_alert_meter_provider(own, service_instance_id=f"{DAY}-cardinality").get_meter("cardinality") \        .create_histogram(DURATION["invoke_agent"], unit="s")    for row in messages:        attrs = row["attributes"]        kept = {key: attrs[key] for key in METRIC_ATTRIBUTES + extra if key in attrs}        histogram.record((row["end_ns"] - row["start_ns"]) / 1_000_000_000, kept)    return series(own)registry = series(reader, DURATION["invoke_agent"])with_route = series_with(("ambrewick.route",))with_user = series_with(("ambrewick.user.id",))print("series, registry attributes:", fmt_int(registry))print("series, registry attributes and route:", fmt_int(with_route))print("series, registry attributes and user ID:", fmt_int(with_user))assert registry == 1                       # on a normal day every message is a success with one attribute setassert with_user == len(users)             # a user ID makes one series per user, and no two users share oneassert with_user > with_route > registry   # each attribute that varies multiplies the series
出力python cardinality-of-attributes.py
messages: 200
distinct users: 121
distinct routes: 7
series, registry attributes: 1
series, registry attributes and route: 7
series, registry attributes and user ID: 121
演習 9.2

ユーザーの集合を書く

+10 件の検証

18行目は空白である。メッセージ全体にわたるユーザーIDの集合としてこの行を書き、次の行で重複を除いたユーザー数を数えられるようにする。

provider = make_alert_meter_provider(reader, service_instance_id=f"{DAY}-cardinality")traced = run_day_traced(DAY, live=False, meter_provider=provider)  # the assistant's live meter, registry attributes onlymessages = [row for row in traced.spans if row["attributes"].get("gen_ai.operation.name") == "invoke_agent"]routes = {row["attributes"]["ambrewick.route"] for row in messages if row["attributes"].get("ambrewick.route")}print("messages:", fmt_int(len(messages)))print("distinct users:", fmt_int(len(users)))
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 で実行される
演習 9.3

ユーザー ID がシリーズを増やす理由

+10 件の検証

出力を見ると、ユーザー ID を付けた場合のシリーズ数は、メッセージ数ではなく、異なるユーザーの数と一致している。ユーザー ID を加えると、なぜシリーズがユーザーに従うようになるのか。

ユーザー ID がシリーズを増やす理由:正しい説明を選ぶ
Python 3.13.16 で実行される

同じ200件のメッセージは121人の異なるユーザーから送られ、7個のルートに分かれる。属性の組ごとのメッセージのヒストグラムの系列は次のとおりである。

メッセージのヒストグラムに付ける属性 系列数
レジストリの属性 1
レジストリの属性とルート 7
レジストリの属性とユーザーID 121

ルートが加える線は固定された少数であり、本書で使う7個の値それぞれに1本である。ユーザーは、メッセージを送った人ごとに1本の線を加える。その数はユーザーとともに増え、ユーザーがさらに多いサービスでは、次の段落で述べるSDKの上限を超える。

ソフトウェアにも上限がある。OpenTelemetryのメトリクスSDKは、1回の収集周期において、メトリクスストリームごとに既定で2,000系列で打ち切る。この上限を超えた属性の組は、単一のオーバーフロー系列にまとめられる(Metrics SDK, v1.45.0)。オーバーフロー系列は合計を正しく保つが、内訳を隠す。そのため、これを目にした運用者は、問いに答えられたはずの線をすでに失っている。

このため、アシスタントのメトリクスにはユーザーIDを付けず、本書でも付けることはない。ユーザーごとのメッセージに関する問いには、トレースで答える。トレースでは1件のメッセージが1件のレコードであり、そのユーザーは多数ある属性の一つにすぎない。特定のユーザーのレイテンシに関する問いは、トレースに向けるべき問いである。アシスタントのサービス全体に関する問いには、アラートが答える。

実践ルール: メトリクスには、公開前に列挙できる集合の値だけをラベルとして付ける。実際のトラフィックがある日に、候補となる各属性を付けた場合の系列数を数え、その数がユーザーとともに増える属性は退ける。

この部分はまだ翻訳されていないため、英語で表示している。

Service-level objectives

An alert that says too many messages failed needs a line to measure them against, and a pace at which failing is still acceptable. An objective alone pages no one, so an alert measures how fast the failures use up the share that the objective leaves.

An objective is the share of messages that must succeed, or finish within a time, over a period; the error budget is the share it lets fail; the burn rate is how fast failures spend it, where 1 spends it exactly by the period's end.

The assistant has two objectives. The first is for failed messages. Over 30 days, 99% of messages must get a reply, which leaves an error budget of 1.0%; the period sets the arithmetic and forecasts no traffic. A message fails, for the objective, when its user got no reply; a retry that recovered is not a failure. That is narrower than chapter 8's error. Under the span rule, a message whose first model request was refused and whose second request got a reply has an error, and so does a message whose lookup timed out on both attempts and whose model replied anyway. This objective counts neither, because the user got a reply in both cases. A fallback reply is a reply too, so the objective does not count it either. Whether a fallback reply went to the right scenario is a question for chapter 8's wrong-route check.

The second objective is for latency: over 30 days, 95% of messages must finish within 20 seconds, a line set above the slowest messages of a normal day, which leaves a latency budget of 5.0%. The number comes from the tail that chapter 7 measured on the recordings that chapter 1 introduces, so every time here is a recorded time on that replay's virtual clock. On baseline day 1 the 95th percentile (p95, by nearest rank) of message times is 18,351.2 ms, over 200 messages, which sits under the 20-second objective. The conventions advise edges for the invoke_agent duration histogram, as a SHOULD, from 0.1 to 86,400 s, which puts 12.8 and 25.6 either side of 20 and no edge at 20. The assistant's meter keeps its own edges, 0.5 to 60 s, set by a view, so the 20-second objective sits on one and the count within it is exact. Chapter 7 shows what an estimate between two edges can do to a tail.

Baseline day 1 shows what the two objectives leave on a normal day.

slo-and-budget.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 合格
"""The assistant's two objectives, and the error budget each one leaves (chapter 9, `service-level-objectives`).The error objective: 99% of messages get a reply. A message that ended with no reply has `error.type` on its durationpoint, and it spends the budget. The latency objective: 95% of messages finish within 20 seconds, the book's edge(chapter 7). The edge sits above baseline day 1's p95, so a normal day meets it. Both are read from the metrics that thealert reads, on the same day. The 30-day period is the arithmetic's period, not a traffic forecast."""from decimal import Decimalfrom lib.dayrun import run_day_tracedfrom lib.metrics import DayMeter, burn_rate, tallies_by_tickfrom lib.report import fmt_burn, fmt_int, fmt_ms, fmt_sharefrom lib.stats import nearest_rankDAY = "2026-12-08"ERROR_SLO, LATENCY_SLO, PERIOD_HOURS = 0.99, 0.95, 30 * 24meter = DayMeter(DAY)                                  # the assistant's live meter, read after each messagetraced = run_day_traced(DAY, live=False, meter_provider=meter.provider, after_message=meter.after)day = tallies_by_tick(meter.marks, DAY)[-1][1]         # the last tick's cumulative tally is the whole daydurations = sorted(row["end_ns"] - row["start_ns"] for row in traced.spans                   if row["attributes"].get("gen_ai.operation.name") == "invoke_agent")p95 = nearest_rank(durations, 95)print("error objective, share of messages with a reply:", fmt_share(round(ERROR_SLO * 100), 100))print("error budget, share of messages that may fail:", fmt_share(round((1 - ERROR_SLO) * 100), 100))print("latency objective, share of messages within 20 s:", fmt_share(round(LATENCY_SLO * 100), 100))print("latency budget, share of messages that may run over 20 s:", fmt_share(round((1 - LATENCY_SLO) * 100), 100))print("messages, baseline day 1:", fmt_int(day.requests))print("messages with no reply:", fmt_int(day.failed), "of", fmt_int(day.requests))print("messages within 20 s:", fmt_int(day.within), "of", fmt_int(day.requests), "share", fmt_share(day.within, day.requests))print("messages over 20 s:", fmt_int(day.slow), "of", fmt_int(day.requests))print("error budget spent over the day, burn:", fmt_burn(burn_rate(day.failed, day.requests, ERROR_SLO)))print("latency budget spent over the day, burn:", fmt_burn(burn_rate(day.slow, day.requests, LATENCY_SLO)))print("p95 of message times, nearest rank, n:", fmt_int(len(durations)), "messages")print("p95 of message times:", fmt_ms(p95))print("share of the 30-day budget a 1-hour page at burn 14.4 spends:", fmt_share(Decimal("14.4") * 1, PERIOD_HOURS))assert day.failed == 0                               # a normal day has no message without a replyassert day.within / day.requests >= LATENCY_SLO      # and meets the latency objectiveassert p95 <= 20 * 1_000_000_000                     # the edge sits above the day's p95 (chapter 7, P-24)
出力python slo-and-budget.py
error 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%
演習 9.4

レイテンシのバーンを固有の目標に対して測定する

+10 件の検証

32行目はレイテンシのバーンを出力するが、遅いメッセージをエラー目標に対して測定している。そのため、出力されるバーンはレイテンシのバジェットと一致しない。遅いメッセージがレイテンシ目標に対して測定されるように、32行目を修正せよ。

print("messages within 20 s:", fmt_int(day.within), "of", fmt_int(day.requests), "share", fmt_share(day.within, day.requests))print("messages over 20 s:", fmt_int(day.slow), "of", fmt_int(day.requests))print("error budget spent over the day, burn:", fmt_burn(burn_rate(day.failed, day.requests, ERROR_SLO)))print("p95 of message times, nearest rank, n:", fmt_int(len(durations)), "messages")print("p95 of message times:", fmt_ms(p95))print("share of the 30-day budget a 1-hour page at burn 14.4 spends:", fmt_share(Decimal("14.4") * 1, PERIOD_HOURS))
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 で実行される

Both objectives hold on the normal day, and the code asserts it. Of the day's messages, 0 of 200 got no reply, and 6 of 200 ran over 20 seconds.

Over the whole day the error burn is 0.0, and the latency burn is 0.6. Both sit below 1, which is the pace the objective allows. Those are the burns an alert would read on a quiet day, and the next sections use the same two objectives.

Working rule: Set each objective from the numbers of a normal day, and check that the normal day meets it before any alert reads it. Print the objective's error rule beside its count, so a reader can tell it from chapter 8's span rule.

バーンレート

バーンレートは件数ではなく速度である。14 件の失敗は、それが何件のメッセージから生じたのか、またエラーバジェットがどれだけの大きさなのかが分からない限り、ほとんど意味を持たない。ある時間窓のバーンレートとは、その窓で失敗したメッセージの割合をエラーバジェットで割った値である。失敗の割合は件数を件数で割ったものであるから、バーンはもう一度割り算をしたものであり、大きさの異なる窓どうしでも比較できる数値になる。

この節の時間窓は仮想時間上にある。1 時間窓と 5 分窓は、1 日の 5 分ごとの各ティックで読み取られ、各窓の件数は同じヒストグラムを累積で 2 回読んだ値の差である。ヒストグラムは増える一方なので、窓のメッセージ数は、2 回の読み取りの間にヒストグラムが加えた分になる。この例では、メッセージごとにメーターを読み取り、その読み取り値をティックごとに足し合わせる。プロセスが動いている間は増える一方のカウンターから、ダッシュボードがレートを読み取る方法と同じである。

以下の例は、インシデントの日に注入された三つの窓に対して実行され、各窓を一つの障害として扱う。障害とは、連絡先サーバーのタイムアウト、モデルのレート制限、連絡先サーバーのエラー応答である。例は窓ごとに、窓の後の最初のティックまでの 1 時間のメッセージ数、そのうち返信がなかった数、1 時間と 5 分のバーンを出力する。バーンは、窓から窓の 5 分後までの最大値である。

burn-rate-by-window.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 合格
"""The burn in each window on the incident day (chapter 9, `burn-rate`).A burn rate is how fast a window spends the error budget. The windows are on virtual time: one hour (the long window)and five minutes (the short one), each read as the difference between two cumulative reads of the metric at 5-minuteticks. The live contacts server injects the three incident windows (lib.inject). The counts in each window are checkedagainst the spans' own counts, so the metric and the spans agree on what happened."""from lib.clock import VirtualClockfrom lib.dayrun import run_day_tracedfrom lib.inject import load_incidentsfrom lib.metrics import DayMeter, alert_verdicts, tallies_by_tickfrom lib.report import fmt_burn, fmt_intDAY, STEP_NS, HOUR_NS = "2026-12-09", 300 * 1_000_000_000, 3600 * 1_000_000_000MIN_REQUESTS = 10                                     # a burn counts only over an hour with this many messages (alert)meter = DayMeter(DAY)                                 # the assistant's live meter, read after each messagetraced = run_day_traced(DAY, meter_provider=meter.provider, after_message=meter.after)  # live: faults on virtual timemidnight = VirtualClock(DAY).now_nstallies = tallies_by_tick(meter.marks, DAY)errors = alert_verdicts(tallies, slo=0.99, measure="failed")   # objective 99%: budget 1%slow = alert_verdicts(tallies, slo=0.95, measure="slow")       # objective 95% within 20 s: budget 5%messages = [row for row in traced.spans if row["attributes"].get("gen_ai.operation.name") == "invoke_agent"]def clock(ns: int) -> str:    """A virtual time as hours, minutes and seconds UTC, from the day's midnight."""    offset = (ns - midnight) // 1_000_000_000    return f"{offset // 3600:02d}:{offset % 3600 // 60:02d}:{offset % 60:02d}"for incident in load_incidents():    first = -(-(incident.end_ns - midnight) // STEP_NS)     # the first tick at or after the window's end, 1-based    error, latency = errors[first - 1], slow[first - 1]    near = [v for v in errors if incident.start_ns < v.tick_ns <= incident.end_ns + STEP_NS]    counted = {v.tick_ns for v in near if v.long.requests >= MIN_REQUESTS}   # the hours a page could read    print(f"{incident.incident_id}, window:", f"{clock(incident.start_ns)} to {clock(incident.end_ns)} UTC")    print(f"{incident.incident_id}, first tick after the window:", clock(error.tick_ns))    print(f"{incident.incident_id}, messages in the hour to that tick:", fmt_int(error.long.requests))    print(f"{incident.incident_id}, messages with no reply in that hour:", fmt_int(error.long.bad))    print(f"{incident.incident_id}, error burn, 1 hour:", fmt_burn(error.long.burn))    print(f"{incident.incident_id}, error burn, 1 hour, highest from the window to 5 minutes after it:",          fmt_burn(max(v.long.burn for v in errors if v.tick_ns in counted)))    print(f"{incident.incident_id}, error burn, 5 minutes, highest from the window to 5 minutes after it:",          fmt_burn(max(v.short.burn for v in errors if v.tick_ns in counted)))    print(f"{incident.incident_id}, messages over 20 s in that hour:", fmt_int(latency.long.bad))    print(f"{incident.incident_id}, latency burn, 1 hour, highest from the window to 5 minutes after it:",          fmt_burn(max(v.long.burn for v in slow if v.tick_ns in counted)))    in_hour = [row for row in messages if error.tick_ns - HOUR_NS < row["end_ns"] <= error.tick_ns]    assert len(in_hour) == error.long.requests                                              # the metric's count    assert sum("error.type" in row["attributes"] for row in in_hour) == error.long.bad      # the spans' failures
出力python burn-rate-by-window.py
inc-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
演習 9.5

1時間の読み取りが加えるメッセージを選ぶ

+10 件の検証

47行目は空白である。この行を書き、in_hour に、エラーのティックまでのメトリクスの1時間ウィンドウが対象とする1時間のうちに終了したメッセージのスパンを格納せよ。数え方は、ヒストグラムの読み取りによる数え方に合わせる。各スパンの行は、終了時刻をナノ秒単位でキー end_ns に保持している。

    print(f"{incident.incident_id}, messages over 20 s in that hour:", fmt_int(latency.long.bad))    print(f"{incident.incident_id}, latency burn, 1 hour, highest from the window to 5 minutes after it:",          fmt_burn(max(v.long.burn for v in slow if v.tick_ns in counted)))    assert len(in_hour) == error.long.requests                                              # the metric's count    assert sum("error.type" in row["attributes"] for row in in_hour) == error.long.bad      # the spans' failures
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 時間に含まれるツール試行は、メーター自身のツールヒストグラム gen_ai.execute_tool.duration から得られる。このヒストグラムは、次の例が同じ方法でメッセージごとに読み取る。

tool-attempts-by-window.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 合格
"""The tool attempts in each incident window, read from the assistant's meter (chapter 9, `burn-rate-by-window`).The meter records gen_ai.execute_tool.duration once for each tool attempt. The example reads that histogram after eachmessage, so a message's attempts count at its reply, as the alert's ticks do. For each incident window it prints theattempts in the hour up to the first tick after the window, and how many carry error.type. The day's totals are checkedagainst the spans, so the meter and the spans agree on every attempt."""from functools import reducefrom lib.clock import VirtualClockfrom lib.dayrun import run_day_tracedfrom lib.inject import load_incidentsfrom lib.metrics import DURATION, DayMeter, Tally, tallyfrom lib.report import fmt_intDAY, STEP_NS, HOUR_NS = "2026-12-09", 300 * 1_000_000_000, 3600 * 1_000_000_000meter, tools, last = DayMeter(DAY), [], [Tally(0, 0, 0)]   # the live meter; attempts by reply time; the last readdef after_message(run) -> None:    """Read the tool histogram after one message: the attempts it added, keyed by its reply time."""    now = tally(meter.reader, DURATION["execute_tool"], 20)    tools.append((run.replied_ns, now - last[0]))    last[0] = nowtraced = run_day_traced(DAY, meter_provider=meter.provider, after_message=after_message)  # live: faults on virtual timemidnight = VirtualClock(DAY).now_nscalls = [row for row in traced.spans if row["attributes"].get("gen_ai.operation.name") == "execute_tool"]def tools_in_hour(tick_ns: int) -> Tally:    """The tool attempts of the messages that replied in the hour up to a tick."""    return reduce(Tally.__add__, [added for replied, added in tools if tick_ns - HOUR_NS < replied <= tick_ns],                  Tally(0, 0, 0))for incident in load_incidents():    tick = midnight + -(-(incident.end_ns - midnight) // STEP_NS) * STEP_NS    # the first tick after the window    attempts = tools_in_hour(tick)    print(f"{incident.incident_id}, tool attempts in the hour to that tick:", fmt_int(attempts.requests))    print(f"{incident.incident_id}, tool attempts with error.type in that hour:", fmt_int(attempts.failed))assert sum(added.requests for _, added in tools) == len(calls)                              # every attempt, as spansassert sum(added.failed for _, added in tools) == sum("error.type" in row["attributes"] for row in calls)
出力python tool-attempts-by-window.py
inc-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 秒を超えたメッセージ数 3 1 3
1 時間でのレイテンシバーンの最大値 4.6 1.3 4.6

エラーバジェットを急速に消費するのは、レート制限の窓だけである。その 1 時間には返信のないメッセージが 11 件あり、エラーバーンは 1 時間で 73.3、5 分で 91.7 である。注入されたレート制限がそれらのリクエストを拒否し、拒否はリトライのバックオフより長く続いたため、それらのメッセージは返信のないまま終わった。

残る二つの窓は、エラーバジェットをまったく消費しない。窓内のすべてのメッセージに返信があったからである。これらのレイテンシバーンは、1 時間でのレイテンシバーンの最大値の行にあり、次の節がページを発報する 14.4 を大きく下回る。また、それが測るのは失敗したメッセージではなく、遅いメッセージである。

計算から規模が分かる。バーン 14.4 は、30 日分のバジェット全体を 50 時間で使い切る。720 時間を 14.4 で割ると 50 になるからである。この速さでは 1 時間で月間バジェットの 2.0% を消費する。次の節のページのしきい値が 14.4 であるのは、この理由による。

実践ルール: 各窓のバーンは、その窓の内側の件数から計算し、各バーンの横に件数を出力する。0.0 という値を見た読者は、それが多数のメッセージの中に失敗がなかったことを意味するのか、メッセージがまったくなかったことを意味するのかを知る必要がある。

障害の日には1回だけページが飛び、平常の日には飛ばない

単一の窓によるバーンレートのアラートは、出来のよいアラートではない。長い窓は、消費が積み上がってからでないと発火せず、長い窓が失敗を保持している間は発火し続ける。短い窓は、短時間のスパイクで発火し、スパイクが終わるとすぐに解除される。Site Reliability Workbook(O'Reilly、2018年)は、その第5章「Alerting on SLOs」でこの二つを組み合わせている。同書の Table 5-8 は、1時間の窓でバーン14.4となったときにページを出し、短い確認には5分の窓を用いる(the workbook)。この表は、各バーンを、それが消費する予算の割合と窓だけで定めており、目標の値には依存しない。そのため、1時間で14.4というバーンは、30日間の予算の2%を消費する。これは99%の目標でも99.9%の目標でも変わらない。変わるのは、それを発火させる失敗の割合だけであり、ここではメッセージの14.4%になる。ワークブックのトラフィックは本書のトラフィックと同じではない。したがって、ここでの14.4は出発点であり、本書が測定した値ではない。

ワークブックの方法は、より遅い窓も組み合わせている。6時間の窓でバーン6、短い窓を30分とするページは予算の5%を消費する。3日間の窓でバーン1、短い窓を6時間とするチケットは予算の10%を消費する。これらは、1時間の組では見逃す、遅くて持続するバーンを捉える。1日分のトラフィックではこれらを検証できないため、本章では1時間の組だけを設定する。

本書のアラートは、1時間のエラーバーンが14.4以上で、直近5分のエラーバーンも14.4以上であり、かつ、その1時間に10件以上のメッセージがあるときにページを出す。最後の条件は本書独自のものである。1時間のメッセージが少ないと、失敗が1件あるだけでバーンが大きく動く。そのため、最小件数に満たない時間はページを出せない。長い窓によって、ページには持続した消費が必要になる。短い窓によって、消費が止まればページが解除される。最小件数によって、二つの読み値はどちらも意味を保つ。ワークブックには、これほど少ないトラフィックを扱う「Low-Traffic Services and Error Budget Alerting」という節があり、その例は1時間あたり10件のリクエストである。そこでは三つの選択肢が示されている。人工的なトラフィックを生成する、小さなサービスをまとめて監視する、プロダクトを変更する、の三つである。本書の最小件数は、この三つのいずれでもない。本番であれば二つ目を採る。つまり、これほど小さなサービスは、そのページに誰かが頼る前に、より大きなサービスと目標を共有する。

次に、このアラートを障害の日に対して5分刻みの各ティックで実行する。対象は、エラー目標とレイテンシ目標である。

alert-on-incident-day.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 合格
"""The two-window burn-rate alert, run on the incident day at each 5-minute tick (chapter 9, `an-alert-that-stays-quiet`).The page fires when the error budget burns at 14.4 or faster over the hour and over the last five minutes, and the hourholds at least 10 messages, so one failed message in a quiet hour cannot page. 14.4 spends 2% of a 30-day budget in anhour (chapter 9, `slo-and-budget`). The short window is what lets the page clear once the burn stops. The alert reads themetric only. It is run for the error objective and for the latency objective, which has the same windows."""from lib.clock import VirtualClockfrom lib.dayrun import run_day_tracedfrom lib.inject import load_incidentsfrom lib.metrics import DayMeter, alert_verdicts, tallies_by_tickfrom lib.report import fmt_burn, fmt_intDAY, STEP_NS, THRESHOLD, MIN_REQUESTS = "2026-12-09", 300 * 1_000_000_000, 14.4, 10meter = DayMeter(DAY)                                 # the assistant's live meter, read after each messagerun_day_traced(DAY, meter_provider=meter.provider, after_message=meter.after)  # live: the contacts server injects faultsmidnight = VirtualClock(DAY).now_nstallies = tallies_by_tick(meter.marks, DAY)errors = alert_verdicts(tallies, slo=0.99, measure="failed", threshold=THRESHOLD, min_requests=MIN_REQUESTS)slow = alert_verdicts(tallies, slo=0.95, measure="slow", threshold=THRESHOLD, min_requests=MIN_REQUESTS)def clock(ns: int) -> str:    """A virtual time as hours and minutes UTC, from the day's midnight."""    offset = (ns - midnight) // 60_000_000_000    return f"{offset // 60:02d}:{offset % 60:02d}"pages = [v for v in errors if v.page]cleared = next(v for v in errors if v.tick_ns > pages[0].tick_ns and not v.page)print("page threshold, burn over 1 hour and over 5 minutes:", fmt_burn(THRESHOLD))print("minimum messages in the hour:", fmt_int(MIN_REQUESTS))print("ticks where the error page fires:", fmt_int(len(pages)), "of", fmt_int(len(errors)))print("first tick the error page fires:", clock(pages[0].tick_ns))print("messages in that hour, with no reply:", fmt_int(pages[0].long.bad), "of", fmt_int(pages[0].long.requests))print("error burn at that tick, 1 hour and 5 minutes:", fmt_burn(pages[0].long.burn), fmt_burn(pages[0].short.burn))print("first tick the error page is clear again:", clock(cleared.tick_ns))print("ticks where the latency page fires:", fmt_int(sum(v.page for v in slow)))print("highest latency burn over an hour, with the minimum met:",      fmt_burn(max(v.long.burn for v in slow if v.long.requests >= MIN_REQUESTS)))for incident in load_incidents():    near = [v for v in errors if incident.start_ns < v.tick_ns <= incident.end_ns + STEP_NS]    print(f"{incident.incident_id}, ticks in or just after the window:", fmt_int(len(near)))    print(f"{incident.incident_id}, ticks where the error page fires:", fmt_int(sum(v.page for v in near)))rate_limit = next(i for i in load_incidents() if i.kind == "rate-limit")assert pages and all(rate_limit.start_ns < v.tick_ns <= rate_limit.end_ns + STEP_NS for v in pages)assert sum(v.page for v in slow) == 0                  # the latency objective never pages on this dayfor incident in load_incidents():    if incident.kind != "rate-limit":        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.py
page 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

このアラートは、障害の日に1回だけページを出す。最初の発火は UTC の15:35であり、ページは15:40に解除される。最初の発火の時点で、その1時間には返信のないメッセージが11 of 15件あった。1日を通して、エラーのページは1 of 288ティックで発火し、レイテンシのページは一度も発火しない。これは例が表明(assert)しているとおりである。

ページが発火するのはレート制限の窓に対してだけであり、ほかには発火しない。タイムアウトの窓は、この目標に対してはページを出さない。この窓は、事例が UTC の13:00に開始するものであり、その前後でエラーのページは0ティックで発火する。この窓の各ルックアップは再試行され(再試行は2回)、すべての試行がタイムアウトし(4回の試行)、回復した再試行はなかった。その後、モデルは、ツールのタイムアウトの結果から返信を書いた。ルックアップがタイムアウトした2件のメッセージには、ルックアップが一度も応答しなかったにもかかわらず、名前が原因だとする返信が返った。どのメッセージにも返信があったため、エラー目標は何も数えない。

代わりに、この窓のメッセージは遅くなる。その窓のレイテンシバーンは4.6に達し、最小件数を満たした場合の1日全体の最高のレイテンシバーンは5.0である。14.4でレイテンシのページを出すには、1時間のメッセージの72%が20秒を超える必要がある。これは5.0%の予算の14.4倍であり、この日はその割合に近づくことすらなかった。モデルが回避して答える障害は、エラー目標には達しない。また、レイテンシ目標は、ページを出すまでに、はるかに大きな割合の遅いメッセージを必要とする。障害はツールの ERROR の試行に現れ、表のツールの行は、それをgen_ai.execute_tool.durationで数えている。

三つ目の窓である連絡先サーバーのエラー応答も、この目標に対しては同じように振る舞う。ツールのエラー結果がモデルに渡され、モデルは再試行なしで答えたからである(再試行は0回)。そのメッセージには返信があり、エラーのページはこの窓の前後で0ティックで発火する。

figure-burn-rate-incident-day.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 the burn rate over the incident day, by window, with the page's threshold (chapter 9, `burn-rate-incident-day`).A 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 fastas the objective allows. The one-hour burn is drawn as a gap wherever the hour holds fewer than the minimum of 10messages, since a burn over two or three messages is noise. The five-minute burn is drawn as a gap wherever its windowholds no message, since a zero there would read as no failures among many. The page fires where the hour and the fiveminutes both reach the threshold. The peaks are printed so a reader can find the spike on the figure."""import mathfrom lib.clock import VirtualClockfrom lib.dayrun import run_day_tracedfrom lib.figures import ACCENT, INK, MUTED, new_figure, savefrom lib.metrics import DayMeter, alert_verdicts, tallies_by_tickfrom lib.report import fmt_burn, fmt_intDAY, THRESHOLD, MIN_REQUESTS = "2026-12-09", 14.4, 10meter = DayMeter(DAY)                                 # the assistant's live meter, read after each messagerun_day_traced(DAY, meter_provider=meter.provider, after_message=meter.after)  # live: faults on virtual timetallies = tallies_by_tick(meter.marks, DAY)errors = alert_verdicts(tallies, slo=0.99, measure="failed", threshold=THRESHOLD, min_requests=MIN_REQUESTS)slow = alert_verdicts(tallies, slo=0.95, measure="slow", threshold=THRESHOLD, min_requests=MIN_REQUESTS)hours = [(v.tick_ns - VirtualClock(DAY).now_ns) / 3_600_000_000_000 for v in errors]   # hours from the day's midnighterror_hour = [v.long.burn if v.long.requests >= MIN_REQUESTS else math.nan for v in errors]error_five = [v.short.burn if v.short.requests else math.nan for v in errors]   # no message in five minutes: no burnlatency_hour = [v.long.burn if v.long.requests >= MIN_REQUESTS else math.nan for v in slow]def peak(series):    """The highest value of a series and the first tick that reaches it, as hours and minutes UTC."""    known = [(x, i) for i, x in enumerate(series) if not math.isnan(x)]    value = max(x for x, _ in known)    index = min(i for x, i in known if x == value)     # the first tick at the peak, not the last    minutes = round(hours[index] * 60)    return fmt_burn(value), f"{minutes // 60:02d}:{minutes % 60:02d}"print("gaps, one-hour burn at ticks under the minimum:", fmt_int(sum(math.isnan(x) for x in error_hour)))print("peak error burn, 1 hour:", *peak(error_hour))print("peak error burn, 5 minutes:", *peak(error_five))print("peak latency burn, 1 hour:", *peak(latency_hour))print("page threshold:", fmt_burn(THRESHOLD))fig, ax = new_figure(height=2.8)ax.plot(hours, error_hour, color=ACCENT, linewidth=1.8, label="error burn, 1 hour")ax.plot(hours, error_five, color=INK, linewidth=1.2, marker="o", markersize=2.5, label="error burn, 5 minutes")ax.plot(hours, latency_hour, color=MUTED, linewidth=1.2, linestyle="--", label="latency burn, 1 hour")ax.axhline(THRESHOLD, color=INK, linewidth=1, linestyle=":", label="page threshold, 14.4")ax.set_xlim(0, 24)ax.set_xticks(range(0, 25, 3), [f"{h:02d}:00" for h in range(0, 25, 3)])ax.set_ylim(0, 130)                                   # headroom above the 91.7 peak, for the legendax.set_yticks(range(0, 101, 20))ax.set_ylabel("burn rate")ax.legend(loc="upper left", ncol=2, frameon=False)    # in the headroom above the data, left of the 15:35 spikesave(fig, "burn-rate-incident-day")
出力python figure-burn-rate-incident-day.py
gaps, 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は、障害の日をオンコールのダッシュボードのように描いたものである。ページのしきい値を超えるスパイクは、レート制限の窓にある1回だけであり、ほかにそれに近づくものはない。5分のエラーバーンはその窓でピークとなり、数分で下がる。これがページが解除される理由である。1時間のエラーバーンは、より長くしきい値を上回ったままになる。5分のバーンが下がった後も、拒否がその1時間の中に残るからである。1時間のレイテンシバーンは、ページのしきい値である14.4に一度も達しない。1時間の線には、その1時間が最小件数に満たない箇所に途切れがあり、1日のうち253ティックである。5分の線には、その窓にメッセージが1件もない箇所に途切れがある。

00:0003:0006:0009:0012:0015:0018:0021:0024:00020406080100burn rateerror burn, 1 hourerror burn, 5 minuteslatency burn, 1 hourpage threshold, 14.4
図 9.1 障害の日のバーンレートを窓ごとに示した図。ページのしきい値は14.4

実践ルール: 長い窓と短い窓がともにしきい値に達したときにだけページを出し、ページの解除には短い窓を用い、メッセージが最小件数に満たない1時間では、どちらの窓でもページを出さないようにする。

同じアラートを静かな日でテストする

静かな日は、テストのもう半分である。ベースライン2日目には注入した障害がなく、同じアラートはどのティックでも、どちらの目標についてもページを発してはならない。

alert-quiet-on-baseline-day-two.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 合格
"""The same alert on baseline day 2, a normal day with no injected incident (chapter 9, `an-alert-that-stays-quiet`).It is the alert's quiet day: the page must not fire at any tick, for either objective. The page is quiet here because nomessage fails, not because of the hour's minimum. The day has 80 messages, so most hours hold fewer than the minimum,and the printed count of the ticks that hold the minimum shows how little of the day the error page could read."""from lib.dayrun import run_day_tracedfrom lib.metrics import DayMeter, alert_verdicts, tallies_by_tickfrom lib.report import fmt_burn, fmt_intDAY, THRESHOLD, MIN_REQUESTS = "2026-12-10", 14.4, 10meter = DayMeter(DAY)                                 # the assistant's live meter, read after each messagerun_day_traced(DAY, live=False, meter_provider=meter.provider, after_message=meter.after)  # no fault on this daytallies = tallies_by_tick(meter.marks, DAY)errors = alert_verdicts(tallies, slo=0.99, measure="failed", threshold=THRESHOLD, min_requests=MIN_REQUESTS)slow = alert_verdicts(tallies, slo=0.95, measure="slow", threshold=THRESHOLD, min_requests=MIN_REQUESTS)total = tallies[-1][1]print("messages, baseline day 2:", fmt_int(total.requests))print("messages with no reply:", fmt_int(total.failed))print("messages over 20 s:", fmt_int(total.slow))print("ticks where the hour holds the minimum:", fmt_int(sum(v.long.requests >= MIN_REQUESTS for v in errors)),      "of", fmt_int(len(errors)))                     # the only ticks a full hour can page on this dayprint("highest error burn over an hour:", fmt_burn(max(v.long.burn for v in errors)))print("highest error burn over 5 minutes:", fmt_burn(max(v.short.burn for v in errors)))print("highest latency burn over an hour, with the minimum met:",      fmt_burn(max(v.long.burn for v in slow if v.long.requests >= MIN_REQUESTS)))print("ticks where the error page fires:", fmt_int(sum(v.page for v in errors)))print("ticks where the latency page fires:", fmt_int(sum(v.page for v in slow)))assert total.failed == 0                               # no message on this day ended without a replyassert not any(v.page for v in errors)                 # the error page stays quiet at every tickassert not any(v.page for v in slow)                   # and so does the latency page
出力python alert-quiet-on-baseline-day-two.py
messages, 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 件に返信がなかった。エラーバーンの最大値は、1時間で 0.0、5分で 0.0 である。

最小件数を満たしたもののうち、レイテンシバーンの最大値は 4.0 であり、14.4 には遠く及ばない。エラーのページが発火するティックは 0 個であり、コードはそのすべてでページが静かであることを検証している。

静かであるのは、メッセージによるものではなく、最小件数によるものである。この日のトラフィックでは、1時間に含まれるメッセージ数が最小件数に達するティックは 21 of 288 個しかない。エラーのページが1時間分を完全に読み取れる可能性があるのは、そのティックだけである。最小件数に満たない1時間は、中身が何であってもページを発することはできない。9件中9件が失敗していても、アラートは沈黙する。最小件数は、件数の少ない1時間に起きた1件の失敗から守るためのものであり、閑散とした日には、判定の大半をこれが決める。より忙しいサービスでこのアラートが妥当かどうかは、本書のトラフィックでは答えられない問いである。

実践ルール: アラートは2つの日でテストする。ページを発しなければならない日と、発してはならない日である。そして、アラートが読み取れなかったティックを、アラートが下した判定の横に出力する。

バーンレートアラートが見えなくなる場所

ユーザーが受け取ったものを数える目標は、モデルが迂回して回答した障害をすべて見逃す。タイムアウトの時間窓では、モデルは連絡先なしで返答し、ページは発報しなかった。通常の対策は、2つ目の目標を置くことである。ツール試行に対する目標か、経路別に最も遅いメッセージのレイテンシに対する目標がそれにあたる。本章の例は、そのどちらも備えていない。このトラフィックでは、ツール単位のページも、読み取れる呼び出し数が少ない。メーターはツール試行をすべて数えるが、ベースライン1日目には、1日を通しても 10 しかないからである。

アラートがメッセージを認識するのは、そのメッセージが終了したときだけである。リトライを待つメッセージは、その時間の件数に遅れて入る。そのメッセージが失敗する場合、その失敗がページに届くのも遅れる。障害が始まった瞬間にページが発報すると期待する運用者は、その時点でまだ実行中だったメッセージのたびに、期待を裏切られる。

実際の障害にはラベルが付いていない。本章の時間窓は事例のものなので、各件数を後から時間窓に対応づけることができる。本番のアラートにはそのような記録がない。第8章の本番の節も、失敗率について同じ点を指摘している。見直すときは、インシデントの開始と終了を件数の横に置いて確認すること。事後の照合を、アラートの評価基準としてそのまま通してはならない。

本章の失敗メッセージ率と第8章のエラー率は、意図的に一致しない。第8章のスパン規則は、回復したメッセージをエラーとして数えるが、本章の目標は数えない。両方を、それぞれを生んだ規則とともに出力すること。第10章のゲートはスパンのステータスでエラーを数えるので、第8章のエラー率のほうが厳しい。ゲートにとって悪く見えるリリースが、目標にとっては問題なく見えることもある。両者は異なる問いに答えているので、どちらの数値も誤りではない。一方の数値を他方の名前で表示するダッシュボードは、誤解を招く。

メトリクスに属性を1つ追加するたびに、保存容量とクエリ時間は増える。追加する前に、カーディナリティの例と同様に、実トラフィックの1日分でその系列数を数え、その数を変更とともに記録しておくこと。SDKが上限を超えて書き込むオーバーフロー系列は、メトリクスを有用に保つための代替手段ではない。その属性が不適切だったことを示すしるしである。

実践ルール: 最初のページの前に、自分のトラフィックでバーンを再計算し、最小値は、自分のサービスで1時間に実際に含まれるメッセージ数から設定すること。

この章で決めたこと

この章の教訓は、ユーザーが得たものに基づく目標は、ユーザーが感じる障害についてはページを発行するが、モデルが回避して応答した障害は見逃す、という点である。したがって、アシスタントのメトリクスに対するアラートには、そうした障害を捉えるための二つ目の数値が必要になる。

  • エラー目標は、応答のないメッセージを数えるものであり、その値は所要時間ヒストグラムから読み取る。スパンのエラーは、第8章の定義に従ってトレースに残り、第10章のゲートがそれを読む。
  • レイテンシ目標は、メッセージの95%を20秒以内に収めることである。この値はベースライン1日目の裾から定め、バケットの境界で読み取る。
  • ページは、1時間と5分の両方でバーンが14.4に達し、かつ1時間内のメッセージが10件以上のときに発行される。この二つの窓と開始値はワークブックに由来し、最小件数はこの本が定めたものである。
  • メトリクスが持つ属性は、レジストリの属性のみである。ルートとユーザーは、そのコストを示すためにスパンから数えるが、メーターには入れない。
  • この章では、ツール単位の目標もルートごとの目標も設定しない。そのため、タイムアウトが続く期間は、この目標ではページが発行されないままとなる。
  • ユーザーが得たものに対するアラートは、ユーザーが感じる障害についてページを発行し、モデルが回避して応答した障害は見逃す。その障害を捉えられるのは、試行回数または裾に対する二つ目の目標である。第10章のゲートは、同じメッセージについて、メッセージ時間、入力トークン、コスト、エラー率、ルート精度でリリースを比較するが、試行回数も裾も読まない。

この版における本章

第2026.11.2版2026年11月23日時点で例が通過この章の8 例件のうち8件が合格

英語版の書籍(版2026.11.2)から翻訳した。

Labs を開始

書籍は引き続き無料で読める。

料金を見る

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全12章中の第9章: Set alerts on the assistant's metrics

  1. アシスタントがエクスポートするメトリクス
  2. カーディナリティ
  3. Service-level objectives
  4. バーンレート
  5. 障害の日には1回だけページが飛び、平常の日には飛ばない
  6. 同じアラートを静かな日でテストする
  7. バーンレートアラートが見えなくなる場所
  8. この章で決めたこと

ページの先頭に戻るすべての章