실패한 단계 찾기

읽는 데 약 37분, 9절에 7개 예제이(가) 있음.

2026.11.2판 예제 통과 2026년 11월 23 80개 예제 중 80개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.2판을 번역한 것이다. 원문 읽기

Labs

직접 해 보며 이 장을 배운다

모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. 약 30초 안에 열린다.

모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. Labs가 실행을 대신한다: 월 40시간.

Lab에서 열기, 새 탭에서

이용 시간을 확인하는 중…

Lab을 찾는 중…

자신의 컴퓨터에서, 무료로: 이 책의 노트북 내려받기, 코드와 데이터를 포함해 GitHub에서 받을 수 있다.

이 장을 마치면 메시지의 어느 단계가 실패했는지, 얼마나 자주 실패했는지, 왜 실패했는지를 찾을 수 있다. 또 각 횟수를 그 횟수가 나온 행과 함께 출력할 수 있다. 이 사례는 질문을 분명하게 던진다. 쓸모 있는 답을 받지 못한 사용자는 로그만 보고서는 그 이유를 알 수 없다. 라우터가 요청을 잘못된 경로나 대체 응답으로 보냈을 수 있다. 모델이 파서가 읽을 수 없는 도구 호출을 작성했거나, 토큰 상한에서 잘린 응답을 작성했을 수 있다. 연락처 서버가 오류를 반환했거나 아예 응답하지 않았을 수도 있다. 이 중 무엇이 일어났고, 얼마나 자주 일어났는가?

기준일 1은 실제 응답을 바탕으로 얼마나 자주 일어났는지에 답한다. 메시지 200건 중 41건이 잘못된 경로로 갔고, 오류로 끝난 스팬은 하나도 없었다. 이것이 그날의 실제 실패다. 사고일에는 결함을 우리가 주입했으므로 두 번째 종류의 집계가 필요하다. 주입한 결함은 연락처 서버가 너무 늦게 응답하는 구간, 모델이 모든 요청을 거부하는 구간, 연락처 서버가 오류 결과를 반환하는 구간이다. 주입한 결함에는 각각 레이블이 붙어 있고, 그 집계는 별도의 행에 놓이며 기준일 1의 비율에 합산되지 않는다. 주입한 집계를 출력하는 표에는 모두 레이블을 반복해서 적으며, 사고일의 어떤 것도 실제 장애가 아니다.

재생은 재생과 가상 시계의 가상 시계 위에서 실행된다. 이 사례의 트래픽은 이 책을 위해 생성한 것이므로, 여기에 나오는 비율은 이 책 자체의 값이며 어떤 서비스도 나타내지 않는다.

이 장은 스팬이 기록하는 상태에서 잘못된 경로까지, 실패 유형마다 쿼리를 하나씩 만든다.

스팬이 실패를 기록하는 방식

스팬은 자신의 결과를 상태(status)에 기록한다. 규약은 계측 코드가 작업이 오류로 끝났을 때 상태를 Error로 설정하고, 문제가 없었다면 설정하지 않은 채로 두도록 요구한다(recording errors, v1.45.0). 같은 페이지는 실패한 작업에 error.type를 기록하도록 요구한다.

스팬의 상태는 unset, ok, error 중 하나다. error.type는 오류의 이름을 나타낸다. 패키지가 쓰는 클래스 이름이나, 레지스트리에 값이 있다면 그 값을 쓰며, 이렇게 하면 실패를 종류별로 셀 수 있다. 이 책은 레지스트리에 없는 값을 만들어 내지 않는다.

같은 대상을 가리키는 용어를 하나 더 쓴다. 오류는 상태가 ERROR인 스팬이다. 메시지는 스팬 중 하나라도 ERROR이면 오류가 있는 것으로 본다. 10장의 CI 게이트가 세는 오류가 바로 이것이다. 나쁜 결과 가운데 오류가 아닌 것이 두 가지 있다. 토큰 상한에서 잘린 응답은 품질 문제로 분류하며, 경로를 지정하지 않은 라우트 응답도 마찬가지다. 두 경우는 아래에서 함께 센다. 어느 쪽도 스팬의 상태를 설정하지 않는다.

레지스트리가 제시하는 값은 많지 않다. 대체 값은 _OTHER이고, 이 장에서 가장 자주 만나는 두 가지 실패인 타임아웃과 HTTP 429에 대한 값은 없다. 레지스트리는 값이 예측 가능하고 카디널리티가 낮을 것을 요구하며, timeout과 500을 정의된 값이 아니라 예시로 든다(error.md, v1.45.0). 그래서 이 책은 패키지가 발생시키는 클래스 이름을 쓴다. 읽기 타임아웃에는 MCPError, 거부된 모델 요청에는 RateLimitError, 어시스턴트 스스로 포기한 경우에는 ModelUnavailable을 쓴다. 레지스트리의 예시는 정규화된 이름(fully qualified name)이지만, 이 책은 짧은 클래스 이름을 쓴다. 다른 계측 코드는 openai 계측의 openai.RateLimitError처럼 정규화된 이름을 쓰기도 하며, 같은 스팬에 있는 어시스턴트 자신의 exception.type도 정규화된 이름이다. 주입된 429는 이 책의 RateLimitError를 발생시키는데, 이것은 같은 이름의 클라이언트 예외를 대신한다. 따라서 이 값은 이 책의 값이며, 클라이언트 자체의 예외를 쓰는 배포 환경에서는 같은 자리에서 다른 클래스 이름을 보게 된다.

예외는 상태와 별도로 기록된다. 이 책에서 1.45.2인 OpenTelemetry Python SDK가 예외를 기록하면 스팬에 exception 이벤트를 추가하고 상태는 설정하지 않은 채로 둔다. 스팬을 감싸는 두 헬퍼 start_as_current_span와 use_span는 이 동작의 예외다. 예외가 이 헬퍼 밖으로 빠져나가면 기본적으로 상태도 ERROR로 설정한다. recording-errors 페이지는 다른 위치를 요구한다. 작업을 실패시킨 예외는 로그 레코드로 기록해야 한다고 한다. 수신기가 스팬을 보관하는 환경에서는 SDK의 이벤트를 유지하기를 권한다. 이 장의 모든 쿼리는 스팬을 읽고, 집계는 상태에 의존하기 때문이다. 로그 파이프라인이 있는 배포 환경은 상태와 error.type가 여전히 스팬에 도달하기만 하면 다른 방식을 택해도 된다.

error-status-by-step.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 spans end with ERROR, and what error.type each carries, on the incident day (injected, labelled) and on baselineday 1 (real). The point rests on the baseline's zero ERROR spans: a wrong route is not a span error, so the status cannotfind it, and the incident's faults look alike from outside."""from collections import Counterfrom lib.dayrun import run_day_tracedfrom lib.report import fmt_intreal = run_day_traced("2026-12-08", live=False)  # baseline day 1, replayed: no fault is injected into itreal_errors = [row for row in real.spans if row["status"] == "ERROR"]print("real ERROR spans, baseline day 1 (4B):", fmt_int(len(real_errors)))assert not real_errors  # the baseline's failures are wrong routes and fallback replies, which set no span statuslive = run_day_traced("2026-12-09")  # live: the contacts server runs the injected faults over stdiorows = live.spans + live.servererrors = [row for row in rows if row["status"] == "ERROR"]print("ERROR spans, incident day (injected):", fmt_int(len(errors)))# Each injected fault labels every span it touches, so the label itself tells an injected error from a real one.assert all(row["attributes"].get("ambrewick.incident.injected") for row in errors)  # every ERROR span is injectedcounts = Counter((row["name"], row["attributes"].get("error.type", "none")) for row in errors)for (name, error_type), count in sorted(counts.items()):    print(f"{name}, error.type {error_type}, injected: {count}")
출력python error-status-by-step.py
real ERROR spans, baseline day 1 (4B): 0
ERROR spans, incident day (injected): 75
MCP send tools/call find_contact, error.type none, injected: 4
chat qwen3-4b-instruct-2507, error.type RateLimitError, injected: 47
contacts.lookup, error.type none, injected: 3
execute_tool find_contact, error.type MCPError, injected: 4
execute_tool find_contact, error.type tool_error, injected: 3
invoke_agent ambrewick-assistant, error.type ModelUnavailable, injected: 11
tools/call find_contact, error.type tool_error, injected: 3
연습문제 8.1

실패한 스팬을 상태로 세기

+10 증명

16행은 error.type을 가지고 있는지를 기준으로 ERROR 스팬을 고르므로, error.type이 없는 ERROR 스팬은 모두 빠뜨린다. 상태가 ERROR인 스팬을 모두 고르도록 16행을 바꾼다.

live = run_day_traced("2026-12-09")  # live: the contacts server runs the injected faults over stdiorows = live.spans + live.serverprint("ERROR spans, incident day (injected):", fmt_int(len(errors)))# Each injected fault labels every span it touches, so the label itself tells an injected error from a real one.assert all(row["attributes"].get("ambrewick.incident.injected") for row in errors)  # every ERROR span is injected
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에서 실행된다
연습문제 8.2

오류 종류별로 세기: 오류 종류가 없는 span 포함

+10 증명

20번 줄은 비어 있다. 각 ERROR span이 span 이름과 error.type 기준으로 집계되도록 이 줄을 작성하고, error.type이 없는 span은 none 값으로 집계되도록 한다.

print("ERROR spans, incident day (injected):", fmt_int(len(errors)))# Each injected fault labels every span it touches, so the label itself tells an injected error from a real one.assert all(row["attributes"].get("ambrewick.incident.injected") for row in errors)  # every ERROR span is injectedfor (name, error_type), count in sorted(counts.items()):    print(f"{name}, error.type {error_type}, injected: {count}")
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에는 ERROR 스팬이 전혀 없으며, 이 0이 핵심이다. 잘못된 경로는 상태를 설정하지 않는다. 따라서 그날의 실제 실패는 이 표에 전혀 나타나지 않으며, 장의 나머지 부분은 다른 방법으로 실패를 센다. 사고일은 연락처 서버가 결함을 적용하도록 실시간으로 실행한다. 이 날에는 ERROR 스팬이 75개 있고, 예제는 그 모두가 주입 레이블을 지니고 있음을 단언한다.

행은 먼저 상태별로, 그다음에 error.type별로 읽는다. 일부 ERROR 스팬에는 error.type가 전혀 없다. 타임아웃된 호출에 대한 MCP SDK의 클라이언트 스팬 MCP send tools/call find_contact이 한 종류이며, 이런 스팬이 4개 있다. 주입된 크래시에 대한 연락처 서버의 contacts.lookup 스팬이 다른 한 종류이며, 이런 스팬이 3개 있다. 위에서 설명한 기본 동작은 크래시가 스팬 밖으로 빠져나갈 때 ERROR를 설정하며, error.type를 설정하는 것은 아무것도 없다. error.type만으로 세면 두 종류를 모두 놓친다. 나머지 행은 뒤의 절에서 설명하는 종류다. 거부된 모델 요청은 RateLimitError를 지니며 47개다. 응답을 받지 못한 메시지는 루트 스팬이 ModelUnavailable로 끝나며, 11개다. 실패한 연락처 호출은 세 가지 이름으로 나타난다. 어시스턴트의 시도에는 execute_tool find_contact, 클라이언트 스팬에는 MCP send tools/call find_contact, 서버의 스팬에는 tools/call find_contact이다. 타임아웃과 오류 결과를 다루는 절에서 각각을 읽는다.

작업 규칙: 실패는 스팬 상태로 세고, 각 error.type를 그 개수 옆에 출력한다. error.type가 없는 스팬도 여전히 오류이므로, 실패를 찾으려고 그 속성으로 필터링하지 않는다. 실제 실패와 주입된 실패의 개수는 별도의 행으로 나누고, 주입된 행에는 나타나는 곳마다 레이블을 붙인다.

상한에서 잘린 응답

첫 번째 절의 상태 규칙은 예외를 일으키는 실패를 잡아내지만, 토큰 상한에서 잘린 응답은 아무 예외도 일으키지 않는다. 일부 응답은 모델이 답변을 끝냈기 때문이 아니라 그 상한에 도달했기 때문에 멈춘다. 어시스턴트는 런타임의 종료 사유를 gen_ai.response.finish_reasons에 기록한다. 이 값은 생성 하나당 항목 하나를 담은 배열이며, 항목은 생성의 선택지 순서를 따른다. 종료 사유는 모델이 왜 멈췄는지를 알려 준다. 모델이 스스로 멈췄는지(stop), 토큰 상한에서 멈췄는지(length)를 구분한다. 0.1.0 버전의 GenAI 규약도 추론 스팬의 값을 같은 방식으로 정의한다. 중단된 생성은 제공자가 준 사유 또는 interrupted를 보고하고, 사유가 있어야 하는데 받지 못했다면 error를 보고한다(클라이언트 추론 스팬, 주 18). 따라서 length 응답은 오류가 아니며, 우리도 오류로 세지 않는다. 에이전트 하니스의 종료 사유도 같은 개념이다.

이 런타임에 관한 두 가지 사실이 검사 방식을 정한다. 첫째, 이 런타임은 tool_calls를 결코 보고하지 않는다. 모델의 도구 호출은 응답 안의 텍스트로 돌아오고 종료 사유는 stop로 남으므로, 종료 사유로는 도구 호출을 확인할 수 없다. 이 경우는 다음 절에서 다룬다. 둘째, 답변 단계의 상한은 160 토큰이다. 이 상한은 모든 릴리스와 녹화에서 같다. 이 책이 읽는 어떤 녹화보다도 먼저 한 번 정해졌고, 잘린 응답을 만들어 내려고 편집한 녹화는 하나도 없다.

truncated-replies.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 model replies the runtime cut at its token cap, read from the finish reason the runtime recorded for eachrequest: baseline day 1 (the 4B, release r0) and the model swap (the 0.6B, release r2). A cut reply has finish reasonlength. The runtime never reports tool_calls, so a reply with a tool call is not found this way (malformed-tool-calls)."""import jsonfrom collections import Counterfrom lib.dayrun import DATA, run_day_tracedfrom lib.report import fmt_intdef finish_reasons(recording):    """The finish reason of every model request in one recording, counted by step and reason."""    rows = [json.loads(line) for line in (DATA / recording / "traces.jsonl").read_text(encoding="utf-8").splitlines()]    return [row for row in rows if row["kind"] == "model"], Counter(        (row["step"], row["finish_reason"]) for row in rows if row["kind"] == "model")base_rows, base = finish_reasons("baseline-day-1")for step in ("route", "answer"):    print(f"baseline day 1, {step} requests, finish reason stop: {fmt_int(base[(step, 'stop')])}")    print(f"baseline day 1, {step} requests, finish reason length: {fmt_int(base[(step, 'length')])}")# The replay answers from the same recording, and its chat spans carry the finish reason in an array.replayed = run_day_traced("2026-12-08", live=False).spanschat = [row for row in replayed if row["name"].startswith("chat")]reasons = Counter(reason for row in chat for reason in row["attributes"]["gen_ai.response.finish_reasons"])print(f"baseline day 1, chat spans replayed with finish reason stop: {fmt_int(reasons['stop'])}")assert reasons["length"] == 0 and reasons["stop"] == len(base_rows)  # the replay's spans match the recordingswap_rows, swap = finish_reasons("release-model-swap")manifest = json.loads((DATA / "release-model-swap" / "manifest.json").read_text(encoding="utf-8"))for step in ("route", "answer"):    print(f"model swap (0.6B, release r2), {step} requests, finish reason length: {fmt_int(swap[(step, 'length')])}")cut = [row for row in swap_rows if row["finish_reason"] == "length"]print(f"model swap, answer cap in tokens: {manifest['answer_max_tokens']}")print(f"model swap, cut answer, completion tokens: {cut[0]['completion_tokens']}")assert len(cut) == 1 and cut[0]["step"] == "answer"  # one cut reply, and it is an answerassert cut[0]["completion_tokens"] == manifest["answer_max_tokens"]  # cut at the cap, not at a stop token
출력python truncated-replies.py
baseline day 1, route requests, finish reason stop: 200
baseline day 1, route requests, finish reason length: 0
baseline day 1, answer requests, finish reason stop: 121
baseline day 1, answer requests, finish reason length: 0
baseline day 1, chat spans replayed with finish reason stop: 321
model swap (0.6B, release r2), route requests, finish reason length: 0
model swap (0.6B, release r2), answer requests, finish reason length: 1
model swap, answer cap in tokens: 160
model swap, cut answer, completion tokens: 160

4B 모델의 응답 중에는 상한에 도달한 것이 없다. 경로 응답 200개와 답변 응답 121개는 모두 스스로 멈췄고, 재생한 채팅 스팬도 같은 사유를 담고 있다. 즉 321개 모두 stop이다.

모델 교체 릴리스는 Qwen3-0.6B를 실행하며 프롬프트에 /no_think를 덧붙이므로, 기준선 1일 차와의 차이는 더 작은 모델과 이 접미사가 함께 만든 것이다. 여기서는 잘림이 나타난다. 경로 응답 중에는 잘린 것이 없고, 답변 단계에서는 1개의 응답이 160 토큰에서 잘렸는데, 이 값이 곧 상한이다.

잘린 그 응답은 품질 문제로 판단한다. 스팬은 오류가 아니지만, 사용자는 중간에 끊긴 응답을 받는다. 이를 품질로 분류하고, 그 의미를 판단하기 전에 본문을 읽는다.

작업 규칙: 모든 릴리스에서 단계별로 length 종료 사유의 개수를 세고, 응답이 완전하다고 말하기 전에 그 개수 옆에 상한을 함께 출력한다. 한 녹화에서 0이라고 해서 다른 녹화에 대해 알 수 있는 것은 없다. 잘린 응답은 품질 문제로 읽고, 오류로 분류하지 않는다.

파싱되지 않는 도구 호출

모델은 도구가 필요하면 응답에 <tool_call> 블록을 쓰고, 어시스턴트는 그 블록을 다시 읽는다. 런타임의 종료 사유로는 잘못된 블록을 확인할 수 없다. 블록이 깨진 응답도 스스로 멈추기 때문이다. 형식이 잘못된 호출은 응답을 파싱해야만 찾을 수 있다. 닫는 태그가 없는 블록은 형식이 잘못된 것이다. 본문이 JSON이 아닌 경우, 이름이 없는 호출, 인자가 객체가 아닌 호출도 마찬가지다. 형식이 잘못된 호출은 해당 메시지에서 한 번씩 센다. 어시스턴트는 모델에게 호출을 읽을 수 없었다고 알리고, 도구 없이 답하도록 요청한다.

다른 종류의 실패는 도구 자체에 이른다. 호출이 파싱되더라도 도구의 인자 모델을 통과하지 못할 수 있다. 이것은 형식이 잘못된 응답이 아니다. 이 경우 도구 시도는 ERROR로 끝나고, error.type에는 ValidationError 클래스가 설정되며, 쿼리 절은 이러한 시도를 도구 시도에 포함해 센다.

malformed-tool-calls.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 answer replies carry a tool call the parser cannot read, on baseline day 1 (the 4B) and the model swap (the 0.6B).A malformed call is found by parsing the reply, because its finish reason is stop either way. The constructed repliesat the end are not recorded and never become spans: they show that the parser rejects what it should."""import globimport jsonfrom pathlib import Pathfrom lib.assistant import MalformedToolCall, parse_tool_callfrom lib.dayrun import DATA, run_day_tracedfrom lib.report import fmt_intdef check_answers(recording):    """Parse every answer reply in one recording. Returns the reply count, the replies with a tool call, and the    message IDs whose reply the parser rejects."""    paths = sorted(glob.glob(str(DATA / recording / "calls" / "*.json")))    calls = [json.loads(Path(path).read_text(encoding="utf-8")) for path in paths]    answers = sorted((call for call in calls if call["kind"] == "model" and call["step"] == "answer"),                     key=lambda call: call["seq"])  # the recorder's sequence number, unique per request    tool_calls, rejected = 0, []    for call in answers:        try:            tool_calls += parse_tool_call(call["text"]) is not None        except MalformedToolCall:            rejected.append(call["message_id"])    return len(answers), tool_calls, rejectedanswers, tool_calls, rejected = check_answers("baseline-day-1")print(f"baseline day 1 (4B), answer replies: {fmt_int(answers)}")print(f"baseline day 1 (4B), replies with a tool call: {fmt_int(tool_calls)}")print(f"baseline day 1 (4B), malformed tool calls: {fmt_int(len(rejected))}")# The replay parses the same recorded texts with the same parser, so its count should agree with the parse above.replayed = sum(run.outcome.malformed_tool_calls for run in run_day_traced("2026-12-08", live=False).runs)print(f"baseline day 1 (4B), malformed tool calls in the replay: {fmt_int(replayed)}")assert not rejected and replayed == 0answers, tool_calls, rejected = check_answers("release-model-swap")print(f"model swap (0.6B, release r2), answer replies: {fmt_int(answers)}")print(f"model swap (0.6B, release r2), replies with a tool call: {fmt_int(tool_calls)}")  # one call tests nothingprint(f"model swap (0.6B, release r2), malformed tool calls: {fmt_int(len(rejected))}")assert not rejected# Constructed, not recorded: two replies a model could write, passed straight to the parser.for label, text in {"unclosed block": '<tool_call>{"name": "find_contact", "arguments": {}',                    "body is not JSON": "<tool_call>find the contact</tool_call>"}.items():    try:        parse_tool_call(text)        raise AssertionError(f"{label} was not rejected")    except MalformedToolCall:        print(f"constructed reply, {label}, rejected by the parser: yes")
출력python malformed-tool-calls.py
baseline day 1 (4B), answer replies: 121
baseline day 1 (4B), replies with a tool call: 10
baseline day 1 (4B), malformed tool calls: 0
baseline day 1 (4B), malformed tool calls in the replay: 0
model swap (0.6B, release r2), answer replies: 57
model swap (0.6B, release r2), replies with a tool call: 1
model swap (0.6B, release r2), malformed tool calls: 0
constructed reply, unclosed block, rejected by the parser: yes
constructed reply, body is not JSON, rejected by the parser: yes

기준일 1일 차에 기록된 응답 중에는 깨진 블록을 가진 것이 없었다. 4B 모델은 121개의 답변 응답을 썼고, 그중 10개가 도구 호출을 담았으며, 파서가 거부한 것은 0개였다. 파싱 실패와 스키마 거부를 합산하는 리플레이의 결과도 0개로, 이와 일치한다.

프롬프트에 /no_think을 붙인 Qwen3-0.6B 모델 교체 릴리스는 57개의 답변을 썼고, 그중 도구 호출을 담은 것은 1개뿐이었다. 그 호출은 파싱되었다. 호출 하나로는 작은 모델의 도구 사용에 대해 아무것도 검증할 수 없으므로, 이 절은 그에 대해 어떤 주장도 하지 않는다.

두 기록 모두 깨진 블록을 담고 있지 않다. 파서가 무엇을 거부하는지 보이기 위해, 이 장을 위해 작성한 응답 두 개를 파서에 직접 넘기면 파서는 둘 다 거부한다. 이 응답들은 기록된 적이 없고 스팬, 행, 기록물이 되지도 않으므로, 기록된 날에 대해서는 아무것도 말해 주지 않는다.

그러나 리시버는 파싱 실패를 찾을 수 없다. 형식이 잘못된 응답은 어시스턴트 내부에서 예외를 일으키고 메시지의 결과에 집계되며, 어떤 스팬도 이를 오류로 기록하지 않는다. 따라서 위의 집계는 응답에서 나온 것이다. 리시버가 보여 줄 수 있는 것과 없는 것은 쿼리 절에서 설명한다.

작업 규칙: 도구 호출을 담을 수 있는 모든 응답을 파싱하고, 형식이 잘못된 응답은 종료 사유가 아니라 파서 자체의 집계로 센다. 호출을 담은 응답을 그 집계 옆에 함께 출력하여, 도구 사용의 표본이 얼마나 작은지 독자가 알 수 있게 한다.

타임아웃 상황의 재시도

첫 번째 절의 상태 규칙은 예외를 일으키는 실패를 잡아낸다. 첫 번째로 주입한 장애가 그런 경우이며, 타임아웃은 프로세스 경계를 넘어 예외로 발생한다. 연락처 서버는 별도의 프로세스이고 find_contact는 그 안에서 실행되므로, 이 도구의 실패는 MCP SDK가 예외를 일으키는 방식 그대로 어시스턴트에 전달된다. 우리는 이 장애를 사고 당일에 주입했다. 13:00부터 13:12까지(UTC) 연락처 서버는 클라이언트의 읽기 타임아웃인 2,000.0 ms이 지난 뒤에야 find_contact에 응답하고, 클라이언트는 기다리다 포기한다. 도구 래퍼는 대기한 뒤 한 번 더 시도한다. SDK가 이 타임아웃을 응답이 아닌 예외로 발생시키는 방식은 4장에서 설명한다.

재시도는 실패한 호출에 대한 또 한 번의 시도이며, 자체 스팬으로 기록한다. 우리는 시도마다 스팬을 하나씩 두기를 권하며, 도구 호출의 각 시도를 execute_tool 스팬으로 따로 기록하고 ambrewick.attempt 번호를 붙인다. 따라서 실패한 시도는 ERROR 스팬이 되고, 호출의 성공은 성공한 시도에 나타난다. 호출 전체를 나타내는 스팬은 없다. 그 이유는 4장의 선택에 나와 있으며, 첫 번째 시도의 타임아웃은 사용자의 메시지가 겪은 실패 중 하나이므로 집계에 포함된다.

retries-under-incident.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 통과
"""What each injected window does to the calls it covers, on the incident day, run live so the contacts server applies itsfaults. A timed-out find_contact is two attempts that end ERROR with MCP code -32001, the retry starting after the readtimeout and the retry delay; a refused model request is retried on the assistant's backoff. Every line here is labelledwith its window: injected, not a natural rate."""import tomllibfrom lib import injectfrom lib.case import CASE_DIRfrom lib.dayrun import run_day_tracedfrom lib.report import fmt_int, fmt_msfrom lib.tools import REQUEST_TIMEOUT_NS, RETRY_DELAY_NSlive = run_day_traced("2026-12-09")# Spans carry no message ID, so each message is found by its trace: the root spans come in arrival order, as the runs do.roots = sorted((row for row in live.spans if row["name"].startswith("invoke_agent")), key=lambda row: row["trace_seq"])message_of = {root["trace_id"]: run.message.message_id for root, run in zip(roots, live.runs, strict=True)}windows = {incident.incident_id: incident for incident in inject.load_incidents()}schedule = {row["id"]: row for row in tomllib.loads((CASE_DIR / "incidents.toml").read_text(encoding="utf-8"))["incident"]}finds = [row for row in live.spans if row["name"] == "execute_tool find_contact"]refused = [row for row in live.spans if row["attributes"].get("error.type") == "RateLimitError"]def inside(name, row):    """Whether a span starts inside the named window (the window's virtual start, inclusive, to its end)."""    return windows[name].start_ns <= row["start_ns"] < windows[name].end_nsdef say(name, label, value):    """Print one labelled value for a window."""    print(f"{name} (injected), {label}: {value}")TIMEOUT = "inc-contacts-timeout"# The schedule's stamps read 2026-12-09T13:00:00.000000Z, so characters 11 to 16 hold the UTC clock time.say(TIMEOUT, "window start (UTC)", schedule[TIMEOUT]["start"][11:16])say(TIMEOUT, "window end (UTC)", schedule[TIMEOUT]["end"][11:16])timeouts = sorted((row for row in finds if inside(TIMEOUT, row)                   and row["attributes"].get("error.type") == "MCPError"), key=lambda row: row["start_ns"])assert all(row["status"] == "ERROR" and row["attributes"]["ambrewick.mcp.error_code"] == -32001 for row in timeouts)assert all(row["end_ns"] - row["start_ns"] == REQUEST_TIMEOUT_NS for row in timeouts)  # each attempt waits the read timeoutsay(TIMEOUT, "attempts that time out", fmt_int(len(timeouts)))say(TIMEOUT, "MCP error code", timeouts[0]["attributes"]["ambrewick.mcp.error_code"])say(TIMEOUT, "read timeout", fmt_ms(REQUEST_TIMEOUT_NS))pairs = [(a, b) for a, b in zip(timeouts, timeouts[1:]) if a["trace_id"] == b["trace_id"]]assert all(b["start_ns"] - a["start_ns"] == REQUEST_TIMEOUT_NS + RETRY_DELAY_NS for a, b in pairs)say(TIMEOUT, "retries", fmt_int(len(pairs)))say(TIMEOUT, "retry wait", fmt_ms(RETRY_DELAY_NS))say(TIMEOUT, "retry starts after the first attempt", fmt_ms(pairs[0][1]["start_ns"] - pairs[0][0]["start_ns"]))errors = [row for row in finds if inside("inc-mcp-error", row)]say("inc-mcp-error", "retries", fmt_int(sum(row["attributes"]["ambrewick.attempt"] > 1 for row in errors)))replied = [run for run in live.runs if run.outcome.source == "model" and run.message.message_id in schedule["inc-rate-limit"]["message_ids"]]retried = [run for run in replied if any(message_of[row["trace_id"]] == run.message.message_id for row in refused)]say("inc-rate-limit", "messages that got a reply after a refused attempt", fmt_int(len(retried)))assert len(retried) == len(replied)  # every reply in the window came after a refusal
출력python retries-under-incident.py
inc-contacts-timeout (injected), window start (UTC): 13:00
inc-contacts-timeout (injected), window end (UTC): 13:12
inc-contacts-timeout (injected), attempts that time out: 4
inc-contacts-timeout (injected), MCP error code: -32001
inc-contacts-timeout (injected), read timeout: 2,000.0 ms
inc-contacts-timeout (injected), retries: 2
inc-contacts-timeout (injected), retry wait: 500.0 ms
inc-contacts-timeout (injected), retry starts after the first attempt: 2,500.0 ms
inc-mcp-error (injected), retries: 0
inc-rate-limit (injected), messages that got a reply after a refused attempt: 1
연습문제 8.3

시도가 아니라 재시도를 센다

+10 증명

46번째 줄은 재시도가 아니라 시간 초과된 모든 시도를 센다. 이 줄이 시간 초과 구간의 재시도 횟수를 출력하도록 고쳐라.

say(TIMEOUT, "read timeout", fmt_ms(REQUEST_TIMEOUT_NS))pairs = [(a, b) for a, b in zip(timeouts, timeouts[1:]) if a["trace_id"] == b["trace_id"]]assert all(b["start_ns"] - a["start_ns"] == REQUEST_TIMEOUT_NS + RETRY_DELAY_NS for a, b in pairs)say(TIMEOUT, "retry wait", fmt_ms(RETRY_DELAY_NS))say(TIMEOUT, "retry starts after the first attempt", fmt_ms(pairs[0][1]["start_ns"] - pairs[0][0]["start_ns"]))
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에서 실행된다

여기서는 사고 당일을 실시간으로 실행하므로 연락처 서버가 장애를 적용하고, 각 스팬은 자신의 구간별로 묶인다. 모든 줄에는 구간의 이름과 주입되었다는 표시가 있다. 타임아웃 구간에서 타임아웃된 시도는 4건이었다. 각 시도는 error.type이 MCPError인 ERROR로 끝나며, MCP 코드는 ambrewick.mcp.error_code에 기록된다. 이 코드는 -32001으로, 4장에서 설명했듯이 프로토콜 코드가 아니라 읽기 타임아웃을 가리키는 SDK의 이름이다. 재시도는 2이었다. 타임아웃된 두 메시지의 재시도도 모두 타임아웃되었으므로, 도구는 타임아웃 응답을 모델에 돌려주었다. 각 두 번째 시도는 첫 번째 시도가 시작된 지 2,500.0 ms 뒤에 시작하는데, 이는 읽기 타임아웃에 재시도 전 대기 시간을 더한 값이다.

모델 구간도 같은 방식으로 동작하지만, 여기서 실패는 거부이다. 이 구간의 모든 모델 요청에는 429가 응답되고, 어시스턴트는 백오프를 두고 재시도한다. 거부된 시도마다 길이가 0인 chat 스팬이 ERROR로 남으며 error.type은 RateLimitError이고, 주입된 구간에서 거부된 요청은 47건이었다. 백오프가 소진되면 메시지는 응답 없이 끝나며, 그런 메시지는 11건이었다. 한 메시지는 거부된 시도 뒤에 응답을 받았고, 그 수는 1건이다. 스팬 규칙에 따르면 이 메시지는 사용자가 응답을 받았더라도 오류로 집계된다. 집계는 스팬을 따른다. 이것이 비율에 어떤 영향을 주는지는 프로덕션 절에서 설명한다.

작업 규칙: 호출이 나중에 성공하더라도 실패한 시도는 실패로 집계하고, 주입된 것으로 세기 전에 그 구간의 이름을 먼저 밝힌다.

MCP 오류

contacts 서버에는 실패하는 방식이 하나 더 있으며, 이 방식은 아무 예외도 일으키지 않는다. MCP 도구 명세에 따르면 도구 자체의 실패는 프로토콜 오류가 아니라 isError가 설정된 결과로 돌아온다(tools, 2026-07-28 개정판). 이 책에서 2.3.0을 사용하는 MCP Python SDK는 이 규칙을 따른다. 주입된 mcp-error 구간에서는 그 구간 안의 모든 find_contact 호출이 오류 결과로 돌아오고, 클라이언트는 그 결과를 응답으로서 어시스턴트에 넘겨 준다.

오류 결과는 예외가 아니므로 이름을 붙일 예외가 없다. 시도는 ERROR로 끝나며 error.type는 tool_error이다. 이 값은 MCP 규약이 isError 결과에 대해 정의한 값이다(MCP conventions, v0.1.0). 상태 설명은 "find_contact returned an error result"이다. 예외 이벤트는 기록되지 않으며 재시도도 이어지지 않는다.

사고 당일의 행에는 세 가지 기록이 나타난다. 어시스턴트는 3개의 시도를 tool_error로 기록했고, 서버도 같은 호출을 tool_error로 기록했으며 그 수는 3개였다. 구간의 재시도 행은 0이므로 이 시도들 가운데 재시도된 것은 없다. 이 호출들에 대해 contacts 서버의 contacts.lookup 스팬도 ERROR이며, 여기에는 error.type가 없다. 규약은 클라이언트 스팬에도 tool_error를 요구하고, 실패한 모든 클라이언트 스팬에 error.type를 요구한다. 타임아웃의 경우에는 예외의 클래스 이름이 들어간다. 2.3.0의 MCP SDK는 이 두 가지를 모두 따르지 않는다. 오류 결과에 대한 클라이언트 스팬은 설정되지 않은 상태로 남고, 타임아웃에 대한 스팬은 error.type 없이 ERROR가 된다. 첫 번째 표에서 클라이언트 쪽 ERROR 행은 4개의 타임아웃뿐이다.

따라서 주입된 결함 하나는 ERROR 기록 세 개를 남긴다. 상태별로 스팬을 세면 하나의 결함이 세 번 집계된다. 사용자의 메시지가 맞닥뜨린 실패는 시도이다. 시도가 메시지 자체의 호출이 수행한 작업이기 때문이다. 서버의 스팬은 원인이며, 4장에서 전파하는 컨텍스트를 통해 메시지의 트레이스에 합류한다. 쿼리 절은 각 오류 결과 시도를 같은 트레이스에 있는 서버 스팬과 짝지으며, 사고 당일(주입됨)의 결과는 3쌍이다.

작업 규칙: 실패한 작업은 호출자가 만든 스팬에서 한 번만 세고, 원인은 그 옆에 있는 서버의 스팬에서 읽는다. 이 버전의 MCP SDK에서는 규약이 tool_error를 요구하더라도 오류 결과에 대한 클라이언트 스팬이 설정되지 않은 상태로 남는다고 예상해야 한다. 어느 쪽이든 호출자의 시도를 기준으로 센다.

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

Wrong routes against the labels

A wrong route is the one failure with no error anywhere in the trace. The call succeeds, its reply stops on its own, and the answer is a fallback reply, or a tool route the message did not need. To find it, the book needs a source of truth, and the case has one. MASSIVE labels each utterance with a scenario. The scenario table maps each scenario to one route, and the routes are calendar, alarms, lists, messages, devices, media and fallback. A scenario goes to the route whose tool or articles resolve it, and to fallback only when no tool and no article do. A wrong route is a routed choice that differs from the table's. The router writes its choice on the route span, and the check event on that span holds the table's answer, so the trace records whether the route was right.

The fallback reply is defined in chapter 1. The table adds the rule for when it is the right answer. It is right for a message that no tool or article resolves, and for no other message. A fallback reply to any other scenario is a wrong route that the user sees as a refusal. The check is code, and it reads the trace, not the reply's text. Judging whether an answer is right is a separate job, and Evaluating LLM Applications covers the checks that read a reply.

The dev day shows the case in small. Of its 20 messages, 5 were routed wrong, and 3 of those got the fallback reply for a scenario that needed a tool or an article.

wrong-routes-by-label.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 통과
"""How often the router chose a route other than the scenario table's, on baseline day 1 (the 4B), the same messages underthe 0.6B (the model swap, from its recorded route replies) and the dev day. Each message's check event on its route spanholds the table's answer; the 0.6B's replies are read with the same parser. The interval is a bootstrap over messages."""import jsonfrom fractions import Fractionfrom lib.assistant import parse_routefrom lib.case import load_messages, scenario_to_routefrom lib.dayrun import DATA, run_day, run_day_tracedfrom lib.report import fmt_int, fmt_sharefrom lib.stats import bootstrap_intervaldef recorded_routes(recording, day):    """(expected, chosen) for each route reply in one recording, in order. A reply that names no route is the fallback."""    messages = {message.message_id: message for message in load_messages(day)}    paths = sorted((DATA / recording / "calls").glob("*.json"))    calls = sorted((json.loads(path.read_text(encoding="utf-8")) for path in paths), key=lambda call: call["seq"])    return [(scenario_to_route(messages[c["message_id"]].scenario), parse_route(c["text"]) or "fallback")            for c in calls if c["kind"] == "model" and c["step"] == "route"]traced = run_day_traced("2026-12-08", live=False)runs = traced.runs# The check event is on each route span: the trace itself says whether the route was correct.checks = [event["attributes"] for row in traced.spans for event in row["events"] if event["name"] == "ambrewick.check"]wrong = [run.outcome.route != run.outcome.expected_route for run in runs]assert len(checks) == len(runs) and sum(not check["ambrewick.route.correct"] for check in checks) == sum(wrong)print(f"baseline day 1 (4B), messages: {fmt_int(len(runs))}")RESAMPLES = 2000low, high = bootstrap_interval(wrong, lambda units: Fraction(sum(units), len(units)), n=RESAMPLES)print(f"bootstrap resamples of messages, baseline day 1: {fmt_int(RESAMPLES)}")print(f"wrong routes, baseline day 1, 95% interval: {fmt_share(low.numerator, low.denominator)} to {fmt_share(high.numerator, high.denominator)}")for route in sorted({run.outcome.expected_route for run in runs}):    print(f"{route}, wrong routes of {fmt_int(sum(run.outcome.expected_route == route for run in runs))} messages: "          f"{fmt_int(sum(run.outcome.route != route for run in runs if run.outcome.expected_route == route))}")print("fallback replies to a scenario that is not fallback, baseline day 1: "      f"{fmt_int(sum(run.outcome.route == 'fallback' and run.outcome.expected_route != 'fallback' for run in runs))}")# The same messages under the 0.6B, from its recorded replies; the 4B's recorded replies must give the replay's count.base = recorded_routes("baseline-day-1", "2026-12-08")assert sum(expected != chosen for expected, chosen in base) == sum(wrong)swap = recorded_routes("release-model-swap", "2026-12-08")print(f"wrong routes, model swap (0.6B, release r2): {fmt_int(sum(e != c for e, c in swap))} of {fmt_int(len(swap))} messages")print("fallback replies to a scenario that is not fallback, model swap: "      f"{fmt_int(sum(c == 'fallback' and e != 'fallback' for e, c in swap))}")# The dev day's 20 messages, for chapter 1's fallback replies, checked against the same table.dev = run_day("2026-12-07")print(f"dev day, messages: {fmt_int(len(dev))}")print(f"wrong routes, dev day (20 messages): {fmt_int(sum(run.outcome.route != run.outcome.expected_route for run in dev))}")print(f"fallback replies to a scenario that is not fallback, dev day: {fmt_int(sum(run.outcome.route == 'fallback' and run.outcome.expected_route != 'fallback' for run in dev))}")
출력python wrong-routes-by-label.py
baseline day 1 (4B), messages: 200
bootstrap resamples of messages, baseline day 1: 2,000
wrong routes, baseline day 1, 95% interval: 15.0% to 26.5%
alarms, wrong routes of 6 messages: 0
calendar, wrong routes of 42 messages: 16
devices, wrong routes of 17 messages: 1
fallback, wrong routes of 82 messages: 11
lists, wrong routes of 7 messages: 0
media, wrong routes of 29 messages: 3
messages, wrong routes of 17 messages: 10
fallback replies to a scenario that is not fallback, baseline day 1: 18
wrong routes, model swap (0.6B, release r2): 83 of 200 messages
fallback replies to a scenario that is not fallback, model swap: 68
dev day, messages: 20
wrong routes, dev day (20 messages): 5
fallback replies to a scenario that is not fallback, dev day: 3
연습문제 8.4

각 메시지를 표와 대조해 오답으로 표시하기

+10 증명

27행은 비어 있다. 각 실행 결과에 있는 경로와 기대 경로를 사용해, 라우팅된 선택이 시나리오 표의 답과 다를 때 해당 메시지를 오답으로 표시하도록 27행을 작성하라.

runs = traced.runs# The check event is on each route span: the trace itself says whether the route was correct.checks = [event["attributes"] for row in traced.spans for event in row["events"] if event["name"] == "ambrewick.check"]assert len(checks) == len(runs) and sum(not check["ambrewick.route.correct"] for check in checks) == sum(wrong)print(f"baseline day 1 (4B), messages: {fmt_int(len(runs))}")RESAMPLES = 2000
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에서 실행된다
연습문제 8.5

도구로 간 잘못된 경로 세기

+10 증명

37행과 38행은 다른 시나리오로 간 대체 응답을 센다. 이 예제가 대체 응답 줄 대신 '도구 경로로 간 잘못된 경로, 기준 1일차: 23'이라는 줄을 출력하도록 고쳐라. 나머지 줄은 모두 그대로 두어야 한다.

for route in sorted({run.outcome.expected_route for run in runs}):    print(f"{route}, wrong routes of {fmt_int(sum(run.outcome.expected_route == route for run in runs))} messages: "          f"{fmt_int(sum(run.outcome.route != route for run in runs if run.outcome.expected_route == route))}")# The same messages under the 0.6B, from its recorded replies; the 4B's recorded replies must give the replay's count.base = recorded_routes("baseline-day-1", "2026-12-08")

얻어야 할 출력

baseline day 1 (4B), messages: 200
bootstrap resamples of messages, baseline day 1: 2,000
wrong routes, baseline day 1, 95% interval: 15.0% to 26.5%
alarms, wrong routes of 6 messages: 0
calendar, wrong routes of 42 messages: 16
devices, wrong routes of 17 messages: 1
fallback, wrong routes of 82 messages: 11
lists, wrong routes of 7 messages: 0
media, wrong routes of 29 messages: 3
messages, wrong routes of 17 messages: 10
wrong routes to a tool route, baseline day 1: 23
wrong routes, model swap (0.6B, release r2): 83 of 200 messages
fallback replies to a scenario that is not fallback, model swap: 68
dev day, messages: 20
wrong routes, dev day (20 messages): 5
fallback replies to a scenario that is not fallback, dev day: 3
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에서 실행된다

On baseline day 1 the 4B routed 41 of its messages wrong. The 95% interval runs from 15.0% to 26.5%, from 2,000 resamples of messages.

For one day of 200 messages that interval is wide, and the rate should be read with it. Of the wrong routes, 18 were fallback replies to scenarios that needed a tool or an article. The rest went to a tool route.

The routes differ a great deal. Of the messages whose scenario belongs to the messages route, 10 of 17 were wrong, and every one of them was a fallback reply. Calendar was the other large case: 16 of 42 were wrong.

The fallback scenarios show the opposite error. They went to a tool route 11 times, out of 82. The alarms and lists routes had no wrong routes at all, but with 6 and 7 messages, those zeros say little.

The model-swap release routed 83 of 200 messages wrong, and 68 of those were fallback replies to scenarios that needed a tool or an article. The two releases answer the same 200 messages. Its prompt also carries /no_think, so the difference from the 4B is the smaller model and the suffix together.

figure-failure-modes-by-route.py Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 통과
"""Draw, for each scenario route on baseline day 1, how many of its messages the router sent right, to another tool route,or to the fallback reply. The failing modes are coloured; the modes with no count on this day (truncated replies,malformed tool calls) are printed as zero and named in the caption. Every value the figure draws is printed first."""from lib.dayrun import run_day_tracedfrom lib.figures import ACCENT, INK, MUTED, new_figure, savefrom lib.report import fmt_inttraced = run_day_traced("2026-12-08", live=False)  # the 4B's real replies, replayed from the recordingruns = traced.runsmalformed = sum(run.outcome.malformed_tool_calls for run in runs)  # calls the parser rejectedtruncated = sum("length" in row["attributes"]["gen_ai.response.finish_reasons"]  # replies cut at the cap                for row in traced.spans if row["name"].startswith("chat"))assert malformed == 0 and truncated == 0rows = []for route in sorted({run.outcome.expected_route for run in runs}):    group = [run for run in runs if run.outcome.expected_route == route]    right = sum(run.outcome.route == route for run in group)    fallback = sum(run.outcome.route == "fallback" and route != "fallback" for run in group)    other = len(group) - right - fallback    assert right + fallback + other == len(group)    rows.append((route, len(group), right, other, fallback))    print(f"route {route}, messages (n): {fmt_int(len(group))}")    print(f"route {route}, routed right: {fmt_int(right)}")    print(f"route {route}, wrong, to another tool route: {fmt_int(other)}")    print(f"route {route}, wrong, to the fallback reply: {fmt_int(fallback)}")print(f"truncated replies, baseline day 1: {fmt_int(truncated)}")print(f"malformed tool calls, baseline day 1: {fmt_int(malformed)}")fig, ax = new_figure(height=3.4)ys = list(range(len(rows)))[::-1]  # the first route at the topfor y, (route, n, right, other, fallback) in zip(ys, rows):    ax.barh(y, right, color=MUTED, alpha=0.35, label="routed right" if y == ys[0] else None)    ax.barh(y, other, left=right, color=INK, label="wrong, to another tool route" if y == ys[0] else None)    ax.barh(y, fallback, left=right + other, color=ACCENT, label="wrong, to the fallback reply" if y == ys[0] else None)ax.set_xlim(0, 1.12 * max(right + other + fallback for _, _, right, other, fallback in rows))   # headroom so the longest bar is not clippedax.set_yticks(ys, [f"{route} (n = {n})" for route, n, *_ in rows])ax.set_xlabel("messages on baseline day 1")ax.legend(loc="lower right", frameon=False)save(fig, "failure-modes-by-route")
출력python figure-failure-modes-by-route.py
route alarms, messages (n): 6
route alarms, routed right: 6
route alarms, wrong, to another tool route: 0
route alarms, wrong, to the fallback reply: 0
route calendar, messages (n): 42
route calendar, routed right: 26
route calendar, wrong, to another tool route: 12
route calendar, wrong, to the fallback reply: 4
route devices, messages (n): 17
route devices, routed right: 16
route devices, wrong, to another tool route: 0
route devices, wrong, to the fallback reply: 1
route fallback, messages (n): 82
route fallback, routed right: 71
route fallback, wrong, to another tool route: 11
route fallback, wrong, to the fallback reply: 0
route lists, messages (n): 7
route lists, routed right: 7
route lists, wrong, to another tool route: 0
route lists, wrong, to the fallback reply: 0
route media, messages (n): 29
route media, routed right: 26
route media, wrong, to another tool route: 0
route media, wrong, to the fallback reply: 3
route messages, messages (n): 17
route messages, routed right: 7
route messages, wrong, to another tool route: 0
route messages, wrong, to the fallback reply: 10
truncated replies, baseline day 1: 0
malformed tool calls, baseline day 1: 0
figure: figures/failure-modes-by-route.svg

그림 8.1 draws the same messages by route. Each bar is an expected route from the scenario table, and it holds that route's messages, split into the ones routed right, the ones wrong to another tool route, and the ones wrong to the fallback reply. Most wrong routes sit in the calendar, fallback and messages bars. Two modes count zero on this day, truncated replies and malformed tool calls, and the figure does not draw them. Chapter 7 counts the same day's messages by the route the assistant chose, not the expected one, so its counts differ: 7 messages and 31 media there, against 17 and 29 here.

020406080messages on baseline day 1alarms (n = 6)calendar (n = 42)devices (n = 17)fallback (n = 82)lists (n = 7)media (n = 29)messages (n = 17)routed rightwrong, to another tool routewrong, to the fallback reply
그림 8.1 Each route's messages on baseline day 1: routed right, wrong to a tool route, or wrong to the fallback reply

Working rule: Check each route against the scenario table on the trace, count fallback replies to other scenarios apart from the other wrong routes, and print every rate with its interval. Compare two releases only on the same messages, and name any suffix or prompt change beside the comparison.

장애 유형별 쿼리

각 장애 유형마다 수신기의 행을 대상으로 쿼리를 하나씩 작성하며, 수신기는 하루치 데이터를 각각 별도의 파일에 보관한다. 기준일과 장애 발생일은 따로 보관하므로, 주입한 행이 실제 집계에 섞이는 일은 없다. 수신기는 5장에서 보인 것처럼 어시스턴트의 내보내기가 기록하는 행과 같은 행을 담고 있다.

failure-modes-query.py Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · 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 통과
"""One query per failure mode over the stored rows: baseline day 1 (real) and the incident day (injected, labelled), eachkept in its own receiver file. The baseline's real failures are wrong routes and fallback replies; its span errors andtruncated replies print zero. A receiver holds spans only, so no query here counts a parse failure."""import tempfilefrom lib import queryfrom lib.dayrun import run_day_tracedfrom lib.export import write_jsonlfrom lib.report import fmt_intfolder = tempfile.mkdtemp()baseline = run_day_traced("2026-12-08", live=False)write_jsonl(f"{folder}/baseline.jsonl", baseline.spans)incident = run_day_traced("2026-12-09")  # live: the contacts server's rows go to the incident day's receiverwrite_jsonl(f"{folder}/incident.jsonl", incident.spans + incident.server)base, inc = query.connect(f"{folder}/baseline.jsonl"), query.connect(f"{folder}/incident.jsonl")# A check event sits in the event list of its route span; the route the span chose is in the span's own attributes.WRONG = """SELECT count(*) FROM spans, UNNEST(from_json(events, '["json"]')) AS t(e)  WHERE json_extract_string(e, '$.name') = 'ambrewick.check'  AND json_extract_string(e, '$.attributes."ambrewick.route.correct"') = 'false'"""FALLBACK = """SELECT count(*) FROM spans, UNNEST(from_json(events, '["json"]')) AS t(e)  WHERE json_extract_string(e, '$.name') = 'ambrewick.check'  AND json_extract_string(e, '$.attributes."ambrewick.route.correct"') = 'false'  AND json_extract_string(attributes, '$."ambrewick.route"') = 'fallback'  AND json_extract_string(e, '$.attributes."ambrewick.route.expected"') != 'fallback'"""TRUNCATED = """SELECT count(*) FROM spans WHERE name LIKE 'chat %'  AND json_extract_string(attributes, '$."gen_ai.response.finish_reasons"') LIKE '%length%'"""# Each error-result attempt joined to the contacts server's tools/call span in the same trace: one pair per injected error.PAIRED = """SELECT count(*) FROM spans AS a JOIN spans AS s ON s.trace_id = a.trace_id  WHERE a.name LIKE 'execute_tool %' AND s.name LIKE 'tools/call %'  AND a.status = 'ERROR' AND json_extract_string(a.attributes, '$."error.type"') = 'tool_error'  AND s.status = 'ERROR' AND json_extract_string(s.attributes, '$."error.type"') = 'tool_error'"""# Errors on tool attempts and on the contacts server's spans, one row per span name and error.type, with a tie-break.ERRORS = """SELECT name, json_extract_string(attributes, '$."error.type"') AS error_type, count(*) AS n FROM spans  WHERE status = 'ERROR' AND (name LIKE 'execute_tool %' OR name LIKE 'tools/call %')  GROUP BY name, error_type ORDER BY n DESC, name, error_type"""REFUSED = """SELECT count(*) FROM spans WHERE json_extract_string(attributes, '$."error.type"') = 'RateLimitError'"""def one(connection, sql):    return connection.execute(sql).fetchone()[0]print("wrong routes, baseline day 1 (real):", fmt_int(one(base, WRONG)))print("wrong routes, incident day (real):", fmt_int(one(inc, WRONG)))print("fallback replies to a scenario that is not fallback, baseline day 1 (real):", fmt_int(one(base, FALLBACK)))print("truncated replies, baseline day 1 (real):", fmt_int(one(base, TRUNCATED)))print("ERROR tool-attempt and server spans, baseline day 1 (real):", fmt_int(sum(n for *_, n in base.execute(ERRORS).fetchall())))for name, error_type, n in inc.execute(ERRORS).fetchall():    print(f"{name}, error.type {error_type}, incident day (injected): {fmt_int(n)}")print("error-result attempts paired with their server span, incident day (injected):", fmt_int(one(inc, PAIRED)))print("model requests refused, incident day (injected):", fmt_int(one(inc, REFUSED)))
출력python failure-modes-query.py
wrong routes, baseline day 1 (real): 41
wrong routes, incident day (real): 13
fallback replies to a scenario that is not fallback, baseline day 1 (real): 18
truncated replies, baseline day 1 (real): 0
ERROR tool-attempt and server spans, baseline day 1 (real): 0
execute_tool find_contact, error.type MCPError, incident day (injected): 4
execute_tool find_contact, error.type tool_error, incident day (injected): 3
tools/call find_contact, error.type tool_error, incident day (injected): 3
error-result attempts paired with their server span, incident day (injected): 3
model requests refused, incident day (injected): 47

2026.11.2판에서 duckdb 2.0.0에서 2.0.1(으)로에서 업데이트됨.

기준일에서 실제로 발생한 장애는 잘못된 라우팅 41건과, 도구나 문서가 필요한 시나리오에 대한 폴백 응답 18건이다. 장애 발생일의 잘못된 라우팅 13건은 주입한 결함이 아니라 모델이 실제로 내린 라우팅 선택이다. 주입한 결함은 여기에 아무것도 더하지 않는다. 거부된 라우팅 시도는 기록된 같은 응답으로 재시도되고, 포기한 메시지에는 비교할 확인 이벤트가 없으므로, 주입 구간은 잘못된 라우팅을 늘리지 않는다. 이 장은 그날의 비율을 출력하지 않는다.

나머지 유형은 기준일에 0으로 나온다. 잘린 응답은 0건이다. 기준일에는 잘린 응답이 없으므로 이 0은 여기서 검증되지 않았다. 해당 유형이 있는 날에 쿼리를 실행해 본 적이 없기 때문이다. ERROR가 붙은 도구 시도와 서버 스팬은 0건이다. 기준일 1일차에 형식이 잘못된 도구 호출의 실제 횟수는 0이며, 이는 파싱되지 않는 도구 호출을 다룬 절의 응답에서 센 값이고, 수신기에는 쿼리할 데이터가 없다.

장애 발생일에는 같은 도구 쿼리가 주입된 시도를 찾아낸다. 시도에서의 타임아웃이 4건, 시도에서의 오류 결과가 3건이며, 같은 호출에 대한 연락처 서버의 스팬에서는 3건이다. 거부된 모델 요청은 47건이다. 이들은 모두 출력에서 주입된 것으로 표시되며, 모두 장애 발생일의 파일에 들어 있다.

작업 규칙: 장애 유형마다 쿼리를 하나씩 작성하고, 쿼리가 읽는 속성이나 이벤트를 명시하며, 그 유형이 있는 날에 실행해 보기 전에는 0이라는 결과를 신뢰하지 않는다. 어떤 스팬에도 없는 속성에 대한 쿼리는 모든 날에 0을 반환하며, 그 0은 비율이 아니라 쿼리의 버그다.

운영 환경의 실패

마지막으로 변경된 판: 2026.11.2판

운영 환경은 장애가 났던 날과 같은 모습이 아니다. 여기서 다루는 결함은 사례가 직접 배치한 것이므로, 각 결함을 나중에 시간 구간과 대응시킬 수 있다. 실제 결함에는 이름표가 없다. 그렇다면 구간별 집계는 사후에 누군가가 고른 시간 구간에 속한 횟수를 센 것이고, 그 정확도는 장애의 시작과 끝에 대한 기록의 정확도를 넘지 못한다. 사례의 incidents 파일이 하듯이 그 기록을 집계 옆에 두고, 어느 집계가 그 기록에서 나왔는지 밝혀라.

다른 라이브러리는 status를 각자의 방식으로 설정한다. 첫 번째 표에서 MCP SDK의 span이 타임아웃에 대해 그렇게 하듯이, 클라이언트 span이 error.type 없이 ERROR로 표시되는 경우가 있다. 실패는 먼저 status로 센다. 그리고 error.type은 각 집계에 덧붙이는 레이블로 취급하고, 실패로 세는 조건으로 삼지 않는다. 클라이언트 라이브러리 내부의 재시도에도 주의가 필요하다. 3.57.0 버전의 openai 클라이언트는 기본적으로 한 번의 호출 안에서 재시도한다(max_retries). 그래서 그 호출을 감싼 계측은 span을 하나만 기록하고, 재시도된 거부는 span이 되지 않으므로 span 규칙으로는 세지 못한다. 그것들을 보려면 max_retries=0으로 설정하고 이 책처럼 자신의 코드에서 재시도하라.

자신의 코드에서 하는 재시도에는 별도의 속성이 필요하다. HTTP 규약은 다시 보낸 HTTP 요청에 대해 http.request.resend_count을 정의한다(HTTP span, v1.45.0). 이 속성은 MCP 호출을 설명하지 않으므로, 이 책의 재시도는 ambrewick.attempt를 사용한다. 호출에 쓰는 프로토콜이 무엇이든 그 프로토콜에서 시도를 가리키는 이름의 속성을 골라라.

마지막으로, span 규칙은 복구된 메시지도 센다. 재시도 절에서 보듯이, 첫 모델 요청이 거부되었지만 이후 요청이 응답을 받은 메시지는 오류로 센다. 10장의 게이트는 복구된 메시지를 오류로 센다. 9장의 목표는 사용자가 본 것을 세므로, 재시도 후에 응답을 받은 메시지는 거기서는 실패가 아니다(서비스 수준 목표). 첫 도구 시도가 타임아웃되었다가 재시도가 성공한 메시지도 오류로 센다. 장애가 났던 날에는 타임아웃된 두 메시지의 재시도도 모두 타임아웃되었으므로 그런 경우가 없었다. 두 수치가 시스템에서 서로 다른 이야기를 한다면 둘 다 측정하고, 각각을 산출한 규칙과 함께 출력하라.

작업 규칙: 운영 환경의 실패율을 공개하기 전에, 그 집계 수, 집계가 다루는 구간, 그리고 실패 중 몇 건이 복구되었는지를 출력하라. 실패의 종류마다 오류 유형을 명시하고, 유형이 전혀 없는 종류가 무엇인지 밝혀라. 그 수치가 사용자가 본 것일 때는 9장의 목표처럼 메시지 결과 기준으로 세라.

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

What this chapter decided

A failure is found at the span that records it, so each decision below names the span it reads.

  • We define an error as a span with status ERROR, and we count a message by any of its spans. error-status-by-step prints the counts that rule gives, and retries-under-incident shows the message that recovered and still counts.
  • We write the class name the package raises into error.type, or the conventions' value where one is defined, such as tool_error for an isError result. The registry has no value for a timeout or a 429. error-status-by-step shows the names, and retries-under-incident shows the timeouts.
  • We keep the SDK's exception event rather than a log record, because the receiver holds spans and every query here reads them. Chapter 4's timeout example shows the event.
  • We count each failed attempt as its own error, so the first timeout counts. retries-under-incident prints the timed-out attempts and the retries they led to.
  • We read a cut reply and a wrong route as quality findings, not errors. truncated-replies and wrong-routes-by-label print both, with the cap and the scenario table beside them.
  • We parse each reply for a tool call, because the finish reason cannot show one. malformed-tool-calls prints the parser's counts.
  • We keep real and injected failures in separate rows and files, and we label every injected count. failure-modes-query reads two receivers, and error-status-by-step asserts that every ERROR span on the incident day carries the injected label.

이 판의 이 장

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

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

Labs 시작

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

요금 보기

이 절 인용

형식

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

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

이 페이지의 내용

12장 중 8장: 실패한 단계 찾기

  1. 스팬이 실패를 기록하는 방식
  2. 상한에서 잘린 응답
  3. 파싱되지 않는 도구 호출
  4. 타임아웃 상황의 재시도
  5. MCP 오류
  6. Wrong routes against the labels
  7. 장애 유형별 쿼리
  8. 운영 환경의 실패
  9. What this chapter decided

맨 위로 돌아가기전체 장