Set alerts on the assistant's metrics

읽는 데 약 31분, 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.

어시스턴트가 내보내는 메트릭

트레이스는 메시지 하나에 무슨 일이 일어났는지를 알려 준다. 경보에는 다른 종류의 기록이 필요하다. 많은 메시지가 움직일 때 함께 움직이는, 하루의 매 분마다의 수치이다. 6장은 이 장에서 쓰는 메트릭, 카운터, 히스토그램을 정의하고 그것들에서 토큰 합계를 읽는다. 이 절에서는 어시스턴트가 어떤 계측기를 기록하는지, 그리고 각 계측기가 무엇을 세는지를 설명한다.

어시스턴트에는 미터가 있으며, 미터는 각 작업이 끝날 때 그 작업을 기록한다. 소요 시간 히스토그램은 작업 종류마다 하나씩 모두 세 개이다. 메시지 하나는 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은 주입된 장애가 없는 정상적인 하루이므로, 미터가 스팬과 일치하는지 확인하기에 알맞은 날이다. 리플레이는 미터를 연결한 채 하루를 실행하고, 내보낸 결과를 다시 읽어 스팬 자체의 집계와 나란히 놓는다.

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으로 같다. 메시지 히스토그램에는 그날 보낸 메시지마다 점 하나씩, 모두 200개가 담겨 있고, 예제의 단언문은 이 개수를 스팬과 대조해 확인한다. 이날 히스토그램의 시리즈는 1개이며, 정상 메시지의 속성 집합 하나에 해당한다. 이 숫자가 왜 지켜봐야 할 값인지는 다음 절에서 설명한다.

작업 규칙: 경보에 쓸 집계는 각 작업이 끝날 때 기록하는 미터에서 가져온다. 미터의 합이 스팬의 합과 같다는 점은 테스트에서 한 번 단언하고, 그 뒤에는 경보가 실행될 때마다 메트릭을 조회한다.

카디널리티

메트릭은 시계열 하나씩 저장하고 조회한다. 속성 값의 조합이 하나씩 달라질 때마다 새 시계열이 생기고, 대시보드는 시계열마다 선을 하나씩 그린다. 몇 가지 값만 가지는 속성은 선을 몇 개 늘린다. 사용자마다 새로운 값을 가지는 속성은 사용자마다 선을 하나씩 늘리며, 이 절의 나머지 부분은 바로 이 경우를 다룬다.

메트릭의 카디널리티(cardinality)는 그 메트릭을 기록할 때 쓰인 서로 다른 속성 조합의 수이며, 각 조합은 저장해야 할 시계열 하나가 된다.

미터는 각 데이터 포인트에 속성을 다섯 개만 두고 다른 속성은 두지 않는다. 오류 유형, 에이전트 이름, 연산 이름, 프롬프트 버전, 모델 이름이다. 컨벤션의 레지스트리는 이 속성들을 메트릭 속성으로 나열하며, 아래 표는 이를 레지스트리 속성이라고 부른다. 그래서 앞 절에서 출력한 대로, 평상시의 실제 미터는 시계열 하나를 만든다. 운영자가 가장 자주 원하는 두 속성인 경로와 사용자는 미터의 데이터 포인트에 들어 있지 않다. 같은 메시지의 스팬에서 이 둘을 각각 메시지 히스토그램에 추가해 보면 각각 비용이 얼마나 드는지 알 수 있다.

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개의 값마다 하나씩, 고정된 소수의 선을 더한다. 사용자는 메시지를 보낸 사람마다 선을 하나씩 더한다. 이 수는 사용자 수에 따라 늘어나며, 사용자가 더 많은 서비스에서는 다음 문단에서 설명하는 SDK의 한도를 넘는다.

소프트웨어에도 한도가 있다. OpenTelemetry 메트릭 SDK는 한 번의 수집 주기에서 메트릭 스트림당 기본 2,000개의 시계열에서 멈추며, 그 한도를 넘는 속성 집합은 모두 하나의 오버플로 시계열로 합쳐진다(Metrics SDK, v1.45.0). 오버플로 시계열은 합계를 맞게 유지하지만 세부 내용을 숨기므로, 이를 본 운영자는 질문에 답해 줄 선들을 잃은 셈이다.

이런 이유로 어시스턴트의 메트릭에는 사용자 ID를 두지 않으며, 이 책도 사용자 ID를 추가하지 않는다. 한 사용자의 메시지에 대한 답은 트레이스에서 찾는다. 트레이스에서는 메시지 하나가 레코드 하나이고, 그 사용자는 많은 속성 중 하나이다. 한 사용자의 지연 시간에 관한 질문은 트레이스에 던질 질문이다. 어시스턴트 서비스 전체에 관한 질문에는 알림이 답한다.

작업 규칙: 메트릭에는 출시 전에 목록으로 나열할 수 있는 값의 집합에서 고른 값만 레이블로 붙인다. 후보 속성마다 실제 트래픽이 있는 하루 동안의 시계열 수를 세고, 그 수가 사용자 수에 따라 늘어나는 속성은 제외한다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

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.

소진율

소진율은 개수가 아니라 속도다. 실패 열네 건은 그것이 몇 개의 메시지에서 나왔는지, 오류 예산이 얼마나 큰지 알기 전에는 큰 의미가 없다. 한 구간의 소진율은 그 구간에서 실패한 메시지의 비율을 오류 예산으로 나눈 값이다. 실패 비율은 개수를 개수로 나눈 값이므로, 소진율은 나눗셈을 한 번 더 한 값이며 크기가 다른 구간끼리도 비교할 수 있는 수다.

이 절의 구간은 가상 시간을 기준으로 한다. 1시간 구간과 5분 구간은 하루의 5분 틱마다 읽으며, 각 구간의 개수는 같은 히스토그램을 누적해서 읽은 두 값의 차이다. 히스토그램은 늘어나기만 하므로, 구간의 메시지 수는 두 번 읽는 사이에 히스토그램이 더한 양이다. 예제는 메시지마다 미터를 읽고, 그 값을 틱별로 합산한다. 프로세스가 실행되는 동안 늘어나기만 하는 카운터에서 대시보드가 비율을 읽는 방식이 이와 같다.

아래 예제는 장애가 발생한 날에 주입한 세 구간을 대상으로 하며, 각 구간을 하나의 결함으로 다룬다. 연락처 서버의 타임아웃, 모델의 요청 한도 초과, 연락처 서버의 오류 응답이 그 결함이다. 예제는 구간마다 그 구간 뒤 첫 틱까지 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

한 시간의 읽기가 더하는 메시지 고르기

+10 증명

47번째 줄은 비어 있다. 이 줄을 작성하여 in_hour가 오류 틱까지 지표의 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에서 실행된다

그 시간대의 도구 시도 횟수는 미터의 도구 히스토그램 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

오류 예산을 빠르게 소진하는 구간은 요청 한도 초과 구간뿐이다. 이 구간의 한 시간에는 응답이 없는 메시지가 11건 있으며, 오류 소진율은 1시간 기준 73.3, 5분 기준 91.7이다. 주입한 요청 한도가 해당 요청을 거부했고, 거부가 재시도 백오프보다 오래 이어졌기 때문에 그 메시지들은 응답 없이 끝났다.

나머지 두 구간은 오류 예산을 전혀 소진하지 않는다. 두 구간의 모든 메시지가 응답을 받았기 때문이다. 1시간 기준 최고 지연 소진율 행에 있는 두 구간의 지연 소진율은 다음 절에서 페이지(경보)를 발생시키는 소진율인 14.4보다 훨씬 낮으며, 이 값은 실패한 메시지가 아니라 느린 메시지를 측정한 것이다.

산술로 규모를 알 수 있다. 소진율 14.4는 30일 예산 전체를 50시간 만에 소진한다. 720시간을 14.4로 나누면 50이기 때문이다. 이 속도로는 한 시간에 한 달 예산의 2.0%를 소진하며, 다음 절의 페이지 임계값이 14.4인 것도 이 때문이다.

작업 규칙: 각 구간의 소진율은 그 구간 안의 개수로 계산하고, 소진율마다 그 옆에 개수를 함께 출력한다. 0.0을 보는 독자는 그것이 많은 메시지 가운데 실패가 없다는 뜻인지, 메시지가 아예 없다는 뜻인지 알아야 한다.

사고가 난 날에는 한 번 호출하고, 평온한 날에는 호출하지 않는다

하나의 창만 쓰는 번 레이트 경보는 부실한 경보다. 긴 창은 소모가 쌓인 뒤에야 울리고, 긴 창이 실패를 담고 있는 동안에는 계속 울린다. 짧은 창은 잠깐의 급증에도 울리지만 급증이 끝나면 곧바로 해제된다. Site Reliability Workbook(O'Reilly, 2018)은 5장 "Alerting on SLOs"에서 두 창을 짝지어 쓴다. 이 책의 Table 5-8은 1시간 동안 번 14.4에서 호출하도록 하고, 짧은 확인용 창으로 5분 창을 쓴다(워크북). 이 표는 각 번을 그 번이 소모하는 예산의 비율과 창만으로 정의한다. 그래서 1시간 동안 번 14.4는 30일 예산의 2%를 소모한다. 이는 목표가 99%이든 99.9%이든 같다. 달라지는 것은 경보를 일으키는 실패 비율뿐이며, 여기서는 메시지의 14.4%가 된다. 워크북의 트래픽은 이 책의 트래픽과 다르므로, 여기서 14.4는 출발점일 뿐 이 책이 측정한 값이 아니다.

워크북의 방법은 더 느린 창도 짝지어 쓴다. 6시간 동안 번 6에서 호출하고 짧은 창은 30분이며 예산의 5%를 소모하는 경우, 그리고 3일 동안 번 1에서 티켓을 발행하고 짧은 창은 6시간이며 예산의 10%를 소모하는 경우다. 이 둘은 1시간 짝이 놓치는 느리고 지속적인 소모를 잡는다. 하루치 트래픽으로는 이를 시험할 수 없으므로, 이 장은 1시간 짝만 설정한다.

이 책의 경보는 한 시간 동안의 오류 번이 14.4 이상이고, 최근 5분 동안의 오류 번도 14.4 이상이며, 그 한 시간에 메시지가 10개 이상일 때 호출한다. 마지막 조건은 이 책이 따로 둔 것이다. 한 시간의 메시지가 적으면 실패 하나만으로도 번이 크게 움직이므로, 최소치에 못 미치는 시간은 호출할 수 없다. 긴 창은 호출에 지속적인 소모를 요구하고, 짧은 창은 소모가 멈추면 호출이 해제되게 하며, 최소치는 두 값이 모두 의미를 갖게 한다. 워크북에는 이처럼 트래픽이 적은 서비스를 다루는 "Low-Traffic Services and Error Budget Alerting" 절이 있고, 그 예도 시간당 10 requests다. 이 절은 세 가지 선택지를 제시한다. 인공 트래픽을 생성하거나, 작은 서비스를 묶어 모니터링하거나, 제품을 바꾸는 것이다. 이 책의 최소치는 셋 중 어느 것도 아니다. 실제 운영에서는 두 번째를 택할 것이다. 이렇게 작은 서비스는 누군가 그 호출에 의존하기 전에 더 큰 서비스와 목표를 공유하게 한다.

다음으로, 경보를 사고가 난 날에 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

경보는 사고가 난 날 한 번 호출한다. 처음 울린 시각은 15:35 UTC이고, 호출은 15:40에 해제된다. 처음 울린 시점에 그 한 시간에는 답장을 받지 못한 메시지가 11 of 15개 있었다. 하루 동안 오류 호출은 1 of 288개 틱에서 울리고, 지연 호출은 예제가 단언하듯 한 번도 울리지 않는다.

호출은 속도 제한 구간에서만 울리고, 다른 구간에서는 울리지 않는다. 타임아웃 구간은 이 목표에서 호출을 일으키지 않는다. 이 구간은 사례가 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개 틱에서 울린다.

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은 사고가 난 날을 당직 대시보드처럼 그린다. 속도 제한 구간에서 급증 하나가 호출 임계값을 넘고, 다른 어떤 것도 그 근처에 이르지 못한다. 5분 동안의 오류 번은 그 구간에서 정점에 이르고 몇 분 안에 내려오며, 그래서 호출이 해제된다. 1시간 동안의 오류 번은 임계값 위에 더 오래 머문다. 5분 번이 내려온 뒤에도 거부된 메시지가 그 한 시간 안에 남아 있기 때문이다. 1시간 동안의 지연 번은 호출 임계값인 14.4에 한 번도 이르지 않는다. 1시간 선에는 그 시간의 메시지가 최소치보다 적은 곳에 끊김이 있으며, 하루 중 253개 틱이 그렇다. 5분 선에는 그 창에 메시지가 하나도 없는 곳에 끊김이 있다.

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

작업 규칙: 긴 창과 짧은 창이 모두 임계값에 이를 때만 호출하고, 짧은 창으로 호출을 해제하며, 메시지가 최소치보다 적은 시간에는 어느 창도 호출하지 못하게 한다.

조용한 날에도 같은 경보를 시험한다

조용한 날은 시험의 나머지 절반이다. 기준선 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일차에는 하루 전체에 10건뿐이기 때문이다.

경보는 메시지가 끝나는 시점에야 그 메시지를 본다. 재시도를 기다리는 메시지는 그 시간의 집계에 늦게 들어가고, 실패가 있다면 그 실패도 페이지에 늦게 닿는다. 결함이 시작되는 순간 페이지가 울리리라 기대하는 운영자는, 그 시점에 아직 실행 중이던 모든 메시지 때문에 실망하게 된다.

실제 결함에는 이름표가 없다. 이 장의 구간은 사례에서 정해진 것이므로 각 집계를 나중에 구간에 대응시킬 수 있다. 운영 환경의 경보에는 그런 기록이 없으며, 8장의 운영 절도 실패율에 대해 같은 점을 지적한다. 집계를 검토할 때는 사고의 시작과 끝을 집계 옆에 함께 두고, 사후에 맞춰 본 결과를 경보의 척도로 삼지 않아야 한다.

이 장의 실패 메시지 비율과 8장의 오류율은 의도적으로 서로 다르다. 8장의 스팬 규칙은 복구된 메시지를 오류로 세지만, 여기의 목표는 세지 않는다. 두 값을 모두 출력하되, 각각 그 값을 만든 규칙과 함께 보여 준다. 10장의 관문은 스팬 상태로 오류를 세므로 8장의 오류율이 더 엄격하며, 관문에는 나빠 보이는 릴리스가 목표에는 괜찮아 보일 수 있다. 두 값은 서로 다른 질문에 답하므로 어느 쪽도 틀리지 않았다. 한 값을 다른 값의 이름으로 보여 주는 대시보드는 오해를 낳는다.

메트릭에 속성을 하나 추가할 때마다 저장 공간과 질의 시간이 곱으로 늘어난다. 속성을 추가하기 전에, 카디널리티 예제가 하는 것처럼 실제 트래픽 하루치에서 시계열 수를 세고 그 수를 변경과 함께 보관한다. SDK가 한도를 넘어서 기록하는 오버플로 시계열은 메트릭을 계속 쓸 만하게 지켜 주는 대체 수단이 아니다. 그 속성이 잘못된 선택이었다는 신호다.

작업 규칙: 첫 페이지를 내기 전에 자신의 트래픽으로 소진율을 다시 계산하고, 최소값은 서비스가 한 시간에 실제로 처리하는 메시지 수에서 정한다.

이 장이 결정한 것

이 장의 교훈은 사용자가 받은 결과를 기준으로 한 목표는 사용자가 체감하는 결함에 대해서만 페이지를 보내고, 모델이 우회해서 답한 결함은 놓친다는 것이다. 따라서 어시스턴트의 지표에 대한 경보에는 그런 결함을 보기 위한 두 번째 수치가 필요하다.

  • 오류 목표는 응답이 없는 메시지를 센다. 이 수치는 지속 시간 히스토그램에서 읽는다. 스팬 오류는 8장의 정의에 따라 트레이스에 남으며, 10장의 게이트가 이를 읽는다.
  • 지연 시간 목표는 메시지의 95%가 20초 이내에 처리되는 것이다. 이 값은 기준선 1일 차의 꼬리에서 정했으며, 버킷의 경계에서 읽는다.
  • 페이지는 1시간과 5분 두 구간에서 소진율이 14.4일 때 발생하며, 1시간 동안 메시지가 최소 10개 있어야 한다. 이 구간의 쌍과 시작 수치는 워크북에서 가져왔고, 최소 건수는 이 책이 정한 값이다.
  • 지표에는 레지스트리의 속성만 담는다. 경로와 사용자는 비용이 얼마나 드는지 보이기 위해 스팬에서 센 것이며, 미터에는 넣지 않는다.
  • 이 장에서는 도구 수준 목표나 경로별 목표를 정하지 않는다. 따라서 타임아웃이 발생한 구간은 이 목표로는 페이지가 가지 않은 채로 남는다.
  • 사용자가 받은 결과에 대한 경보는 사용자가 체감하는 결함에 대해 페이지를 보내며, 모델이 우회해서 답한 결함은 놓친다. 그런 결함을 잡는 것은 시도 횟수나 꼬리에 대한 두 번째 목표다. 10장의 게이트는 같은 메시지를 놓고 릴리스를 메시지 시간, 입력 토큰, 비용, 오류율, 경로 정확도로 비교하며, 시도 횟수와 꼬리는 읽지 않는다.

이 판의 이 장

2026.11.2판예제 통과 2026년 11월 238 of 8개 예제 in this chapter pass

영어판 2026.11.2판을 번역한 것이다.

Labs 시작

도서는 계속 무료로 읽을 수 있다.

요금 보기

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

12장 중 9장: Set alerts on the assistant's metrics

  1. 어시스턴트가 내보내는 메트릭
  2. 카디널리티
  3. Service-level objectives
  4. 소진율
  5. 사고가 난 날에는 한 번 호출하고, 평온한 날에는 호출하지 않는다
  6. 조용한 날에도 같은 경보를 시험한다
  7. 소진율 경보가 보지 못하는 곳
  8. 이 장이 결정한 것

맨 위로 돌아가기전체 장