保持するトレースを選ぶ
読了まで約40 分。7 節に6 例を収録。
Labs
この章を実際に手を動かして学ぶ
すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。約 30 秒で開く。
すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。Labs が実行環境を用意する: 月40 時間。
自分のマシンで、無料: 書籍のノートブックをダウンロード、そのコードとデータを GitHub から取得する。
書籍のバージョンでコードを実行する
この章を終えると、バックエンドが保持するトレースを選び、それぞれの選択が何を捨てるのかを説明し、保持したトレースから合計値を区間つきで推定できるようになる。エンジニアが最も必要とするトレースを保持するルールを書き、インシデント当日のデータに対してそのルールを検証する。
Ambrewick はメッセージ1件ごとにトレースを1つ残しており、第1章ではそのすべてを保持した。本書の規模である1日あたり 200 件のメッセージであれば、管理は単純である。しかし、一日中メッセージに応答するサービスははるかに多くのトレースを書き出し、1年分のトレースをすべて保持するバックエンドは、そのすべてに対して費用を払うことになる。サンプラーは一部のトレースを保持し、残りを捨てる。したがって重要なのは、どのトレースを保持するかという判断である。インシデント当日がこの問題を示している。エラーはまれであり、アラートを受けてトレースを開くエンジニアにとっては、典型的なメッセージよりも、それらのエラーと遅いメッセージのほうが必要である。トレースの中身を読まずに選ぶサンプラーは、まれなトレースを他のすべてと同じ割合でしか保持しない。
この章では、トレースのサンプリングが行う3種類の判断と、一部のトレースしか保持しない場合に合計値を求めるための推定を組み立てる。ここでトレースのサンプリングとは、バックエンドがどのトレースを保持するかを決めることを指す。モデルが次に書く単語を選ぶトークンのサンプリングとは無関係である。例には記録済みの2日分のデータを用いる。障害を注入していないベースライン1日目と、第9章のインシデント当日である。どちらも記録用マシン上で記録した。このマシンは 2.10 GHz の 4 vCPU Intel Xeon で、Qwen3-4B-Instruct-2507 を実行しており、どちらのデータも仮想クロック上で再生する。
この部分はまだ翻訳されていないため、英語で表示している。
Head sampling decides before the trace runs
Head sampling decides whether to keep a trace when it starts, before any span has run. The kind this chapter uses keeps a fixed share by the trace ID, so it cannot know whether the message will fail and cannot aim at failures. The ratio is the share of traces kept, and the sample is keyed on the trace ID.
The SDK's ratio sampler compares the trace ID with the ratio. It reads the low 64 bits of the trace ID as a number, and it keeps the trace when that number falls below the ratio's share of the whole range (the sampler in the Python SDK, pinned here at 1.45.2). The decision depends on the ID alone, so every span of a trace agrees with the others, and the same trace gets the same answer on every run. The book's trace IDs count up from 1, and small counts all fall under any ratio above zero, so the book hashes each count to 128 bits before the sampler reads it. The specification deprecates TraceIdRatioBased in favour of ProbabilitySampler, which decides from the 56 bits of randomness that W3C Trace Context Level 2 specifies (the trace SDK specification at v1.50.0). The pinned SDK has no ProbabilitySampler, so the book uses the ratio sampler at the root.
The replay runs every message first and makes the head decision afterward. The decision is applied to the completed traces, and it is the same decision the assistant's own sampler would make at the source, because the trace ID alone settles it. The example's last lines check that claim: at each ratio it uses, a provider with the same sampler starts a root span for every trace ID of the day, and the example asserts that the two decisions agree.
1"""Head sampling on baseline day 1: the share of messages each ratio keeps, and the rule that a larger ratio keeps every2message a smaller one kept. The decision is the SDK's TraceIdRatioBased on each message's trace ID, as its root would3make it, so the same messages stay kept as the ratio grows. A live provider samples the same trace IDs at the source, and4the replayed and the live decisions must agree."""5from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter67from lib.dayrun import run_day_traced8from lib.prices import PriceTable9from lib.report import fmt_int, fmt_share10from lib.sampling import head_ratio, head_sample, live_provider, message_traces, only_messages1112MODEL = "Qwen3-4B-Instruct-2507"13DAY = "2026-12-08" # baseline day 1: no injected faults14RATIOS = (0.01, 0.1, 0.5, 1.0) # 1.0 keeps everything, the check that the ratio is read as a share15traces = only_messages(message_traces(run_day_traced(DAY, live=False).spans, DAY, MODEL, PriceTable()))16print("messages on baseline day 1, of all messages:", fmt_int(len(traces)))17kept = {} # ratio -> the sequential trace IDs it keeps18for ratio in RATIOS:19 kept[ratio] = {t.seq for t in head_sample(traces, ratio)}20 print(f"messages kept at ratio {ratio}, of {len(traces)}:", fmt_int(len(kept[ratio])))21 print(f"share of messages kept at ratio {ratio}:", fmt_share(len(kept[ratio]), len(traces)))22 # The source's own decision: a provider with the same sampler makes one root per trace ID, counting from 1.23 provider = live_provider(head_ratio(ratio), InMemorySpanExporter())24 tracer = provider.get_tracer("ambrewick.assistant")25 live = set()26 for seq in range(1, len(traces) + 1):27 root = tracer.start_span("invoke_agent probe")28 if root.is_recording():29 live.add(seq)30 root.end()31 differ = len(live ^ kept[ratio])32 print(f"trace IDs where the replayed and the live decision differ at ratio {ratio}, of {len(traces)}:", fmt_int(differ))33 assert differ == 034# A trace kept at a small ratio is kept at every larger one: the decision compares one fixed value with the ratio.35assert kept[0.01] <= kept[0.1] <= kept[0.5] <= kept[1.0]36assert len(kept[1.0]) == len(traces)
python head-sample-ratio.pymessages on baseline day 1, of all messages: 200
messages kept at ratio 0.01, of 200: 5
share of messages kept at ratio 0.01: 2.5%
trace IDs where the replayed and the live decision differ at ratio 0.01, of 200: 0
messages kept at ratio 0.1, of 200: 21
share of messages kept at ratio 0.1: 10.5%
trace IDs where the replayed and the live decision differ at ratio 0.1, of 200: 0
messages kept at ratio 0.5, of 200: 96
share of messages kept at ratio 0.5: 48.0%
trace IDs where the replayed and the live decision differ at ratio 0.5, of 200: 0
messages kept at ratio 1.0, of 200: 200
share of messages kept at ratio 1.0: 100.0%
trace IDs where the replayed and the live decision differ at ratio 1.0, of 200: 0
A larger ratio keeps every message that a smaller one kept, and the example checks that first. At 0.1 the backend keeps 21 of the day's 200 messages. The ratio describes the share over many traces, and a single day can land a little above or below it, so the count is the day's and not the ratio's.
Working rule: Pick a head ratio only for traffic whose rare cases you can afford to lose. Run the ratio sampler at the root only, under ParentBased, and leave every other service on the default sampler or another parent-based one. The trace SDK specification recommends the ratio sampler "only for root spans", since different SDKs, and different versions of one SDK, can give inconsistent results for the same input. Print the kept share beside its count, as the example does, and never read the share as a count.
子スパンはルートの判断に従う
トレースはプロセスの境界を越え、連絡先サーバーは2番目のプロセスである。第4章では、トレースの識別情報を traceparent として各リクエストに載せた。このヘッダーのフラグの一つがサンプリング済みフラグである(Trace Context Level 1。本書が採用するバージョンである)。親ベースのサンプリングでは、各スパンが親の判断に従う。ルートスパンはヘッドサンプラーに問い合わせ、その下のすべてのスパンは、自前の比率を実行する代わりに親のフラグを読む。サーバーはアシスタントの比率を知ることがなく、フラグだけを見るため、この点はプロセスをまたぐ場合に重要になる。
連絡先サーバーは独自のサンプラーを設定しない。そのトレーサープロバイダーは、OTEL_TRACES_SAMPLER が未設定の SDK の既定値を使い、これはリモートの親のサンプリング済みフラグに従う。フラグが立っていればサーバーはスパンをサンプリングし、立っていなければ破棄する。以下のプローブは、アシスタントのサンプラーを送信元で比率0.5に設定し、各ルートの下でサーバーが記録する内容を数える。
1"""A parent-based sampler at the assistant decides each message's trace once, at its root, and the contacts server follows2that decision through the traceparent. The point rests on the server's count: no span reaches the receiver from a3trace the assistant did not sample."""4import json5import tempfile6from collections import Counter7from pathlib import Path89from opentelemetry import trace10from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1112from lib.clock import VirtualClock13from lib.report import fmt_int, fmt_share14from lib.sampling import head_ratio, live_provider15from lib.tools import LiveContacts1617DAY, PROBES, RATIO = "2026-12-09", 40, 0.518exporter = InMemorySpanExporter()19provider = live_provider(head_ratio(RATIO), exporter) # the assistant's provider: its roots sampled at 0.5, children follow20trace.set_tracer_provider(provider) # the MCP client span is made by the process's global provider21tracer = provider.get_tracer("ambrewick.assistant")22recorded = {} # trace ID -> whether the assistant's root was recorded23with tempfile.TemporaryDirectory() as folder:24 spans_file = Path(folder) / "contacts-spans.jsonl" # the server writes here, and the file is read after it exits25 with LiveContacts(VirtualClock(DAY), spans_file) as contacts:26 for number in range(PROBES):27 with tracer.start_as_current_span(f"invoke_agent probe {number}") as root:28 recorded[format(root.get_span_context().trace_id, "032x")] = root.is_recording()29 contacts.find("U0028", "Ana") # one tool call, inside this root, so its traceparent carries the root's flag30 server = [json.loads(line) for line in spans_file.read_text(encoding="utf-8").splitlines()]31per_trace = Counter(row["trace_id"] for row in server)32sampled = [t for t, yes in recorded.items() if yes]33unsampled = [t for t, yes in recorded.items() if not yes]34print("probes, one assistant root each:", fmt_int(PROBES))35print(f"roots sampled at ratio {RATIO}, of {PROBES}:", fmt_int(len(sampled)))36print(f"share of roots sampled at ratio {RATIO}:", fmt_share(len(sampled), PROBES))37print("contacts server spans under sampled roots:", fmt_int(sum(per_trace[t] for t in sampled)))38print("contacts server spans under unsampled roots:", fmt_int(sum(per_trace[t] for t in unsampled)))39print("unsampled roots with any server span, of the unsampled:", fmt_int(sum(per_trace[t] > 0 for t in unsampled)))40print("sampled roots with any server span, of the sampled:", fmt_int(sum(per_trace[t] > 0 for t in sampled)))41assert all(t in recorded for t in per_trace) # every server span belongs to a probe's trace42assert not any(per_trace[t] for t in unsampled) # the server records nothing for an unsampled trace43assert all(per_trace[t] for t in sampled) # and everything for a sampled one
python parent-based-follows-root.pyprobes, one assistant root each: 40
roots sampled at ratio 0.5, of 40: 19
share of roots sampled at ratio 0.5: 47.5%
contacts server spans under sampled roots: 39
contacts server spans under unsampled roots: 0
unsampled roots with any server span, of the unsampled: 0
sampled roots with any server span, of the sampled: 19
サンプリングされないルートの下にサーバースパンが現れない理由
+10 件の検証子スパンはルートの判断に従う、11章よりもう一度読む
context propagationを基にする。4章「MCP SDK は traceparent を _meta に書き込む」より
traceparentを基にする。4章「MCP SDK は traceparent を _meta に書き込む」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
プローブは「contacts server spans under unsampled roots: 0」と出力する。この結果を説明するのはどれか。
仕組み
連絡先サーバーは独自の判断を行わなかったため、トレースは両側で記録されるか、どちらでも記録されないかのいずれかになった。サンプリングされなかったルートの下で、サーバーが記録したスパンは 0 件であった。40 件のプローブのルートのうち、アシスタントは 19 をサンプリングし、そのすべてにサーバーのスパンがあった。これは例の中でアサートしている。
実践ルール: サンプリングはルートでのみ行い、他のサービスはすべて既定のサンプラーか、別の親ベースのサンプラーのままにする。別のサービスが独自の比率、アルゴリズム、SDK バージョンを使うと、一つのトレースの二つの半分が別々に残ることになる。同じ比率の同一のサンプラー同士であれば判断が一致するため、これが問題になるのは設定が異なる場合である。我々ならサーバーに独自の比率を与えない。
この部分はまだ翻訳されていないため、英語で表示している。
Tail sampling reads the whole trace
Head sampling decides before the message runs, and the failure happens while it runs. Tail sampling decides once the whole trace is in, by what it holds. The rule in this chapter keeps three kinds of trace, in this order. It keeps a trace whose message has an error, in the sense chapter 8 defines. It keeps a trace whose message ran past the latency objective from chapter 9, which is 20,000.0 ms. And it keeps a trace whose model calls cost more than the 99th percentile of baseline day 1, which is $0.000115 per message, the costly tail that chapter 6 counts. Each kept trace is kept whole, with every span from both processes, and the rule stops once its span budget is spent.
The rule is this book's own code, TailRule in lib/sampling.py, and it runs at the receiver once a trace's root has arrived. In every trace of the incident day the root is the last span to end, so a trace is whole when its root arrives. That is by end time. Spans can arrive over a network in another order, so a receiver should also wait.
The rule reads each whole trace, so the errors it keeps are the ones it found, not the ones a ratio happened to pick. The timeout window is part of this count. Chapter 9 showed that a lookup timeout writes ERROR attempts while the user still gets a reply, so those messages have an error in chapter 8's sense. The engineer needs their cause even though no user complained, and the rule keeps them for that reason.
Before the first run, make a prediction. The incident day has messages with an error, and a 10% head sample decides for each of them before anything runs. Predict how many of those messages the head sample keeps: all of them, about a tenth of them, or none. Write the number down, then run the example.
1"""The incident day's failed messages, kept by a 10 percent head sample and by the tail rule. A message failed when a span2in its trace ends with ERROR (chapter 8). The head sample decides before anything runs, so the count it keeps is chance;3the tail rule reads each whole trace and keeps every failed one. A detached root is judged as a trace of its own."""4from lib.clock import NS_PER_SECOND5from lib.dayrun import run_day_traced6from lib.prices import PriceTable7from lib.report import fmt_int, fmt_ms, fmt_share, fmt_usd8from lib.sampling import TailRule, head_sample, message_traces, only_messages9from lib.stats import nearest_rank1011MODEL = "Qwen3-4B-Instruct-2507"12BASE, INCIDENT = "2026-12-08", "2026-12-09"13SLOW_NS = 20 * NS_PER_SECOND # chapter 9's latency objective: a message over 20 s is slow14price = PriceTable()15# The expensive threshold is baseline day 1's 99th percentile of message cost (nearest rank, PL-5): the incident is16# judged by the day before it, not by itself.17expensive = nearest_rank([t.cost for t in only_messages(message_traces(run_day_traced(BASE, live=False).spans, BASE, MODEL, price))], 99)18live = run_day_traced(INCIDENT) # live: the contacts server runs the injected faults over stdio19traces = message_traces(live.spans + live.server, INCIDENT, MODEL, price) # each trace whole, the server's spans included20messages = only_messages(traces)21failed = [t for t in messages if t.error]22head = head_sample(messages, 0.1)23kept = TailRule(keep_error=True, slow_ns=SLOW_NS, expensive=expensive, budget=sum(len(t.rows) for t in traces)).keep(traces)24print("latency threshold, the 20 s objective:", fmt_ms(SLOW_NS))25print("cost threshold, baseline day 1's 99th percentile per message:", fmt_usd(expensive))26print("messages on the incident day:", fmt_int(len(messages)))27print("detached roots, traces of their own with no message, incident day:", fmt_int(len(traces) - len(messages)))28print("messages with an error, of all messages:", fmt_int(len(failed)))29print("share of messages with an error:", fmt_share(len(failed), len(messages)))30print(f"messages with an error kept by a 10% head sample, of {len(failed)}:", fmt_int(sum(t.error for t in head)))31print("share of messages with an error kept by a 10% head sample:", fmt_share(sum(t.error for t in head), len(failed)))32print(f"messages with an error kept by the tail rule, of {len(failed)}:", fmt_int(sum(t.seq in kept for t in failed)))33print("share of messages with an error kept by the tail rule:", fmt_share(sum(t.seq in kept for t in failed), len(failed)))34assert all(t.seq in kept for t in failed) # the tail rule keeps every failed message35assert sum(t.error for t in head) < len(failed) # the head sample loses most of them36assert all(max(r["end_ns"] for r in t.rows if r["parent_span_id"] is None) == max(r["end_ns"] for r in t.rows)37 for t in traces) # the root ends last, so a trace is whole when its root arrives (B-83)
python tail-rule-keeps-errors.pylatency threshold, the 20 s objective: 20,000.0 ms
cost threshold, baseline day 1's 99th percentile per message: $0.000115
messages on the incident day: 60
detached roots, traces of their own with no message, incident day: 4
messages with an error, of all messages: 17
share of messages with an error: 28.3%
messages with an error kept by a 10% head sample, of 17: 2
share of messages with an error kept by a 10% head sample: 11.8%
messages with an error kept by the tail rule, of 17: 17
share of messages with an error kept by the tail rule: 100.0%
ヘッドサンプルが失敗の大半を見逃す理由
+10 件の検証Tail sampling reads the whole trace、11章よりもう一度読む
errorを基にする。8章「スパンが失敗を記録する方法」より
failed messageを基にする。9章「Service-level objectives」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
22行目は10%のヘッドサンプルを取り、30行目はそのサンプルが保持する失敗メッセージの数を報告している。ヘッドサンプルが失敗メッセージを少数しか保持しない理由を説明しているのはどれか。
仕組み
The incident day has 60 messages, and 17 of them have an error.
The head sample loses most of those errors. It keeps 2 of them, which is 11.8%. The guess of about a tenth came close here, but the head sample had no way to aim at the errors, so its count was a matter of chance.
The tail rule loses none. It keeps all 17 of them.
A rule that keeps every error can still cost too much, so the book's rule also takes a budget of spans for the day. Spans are what the backend stores, and a trace with many model calls holds many of them. Next, the rule is given a budget that the incident day cannot fit whole: 120 spans against a day of 276.
1"""The tail rule under a span budget on the incident day: errors first, then the slowest messages, then the costliest, each2kept whole until the budget is spent. The budget of 120 spans is below the 127 the rule would keep with none, so it has3to drop something; the point rests on every error being kept and the slow message with no error being dropped."""4from lib.clock import NS_PER_SECOND5from lib.dayrun import run_day_traced6from lib.prices import PriceTable7from lib.report import fmt_int, fmt_ms, fmt_share8from lib.sampling import TailRule, message_traces, only_messages, retained_bytes9from lib.stats import nearest_rank1011MODEL = "Qwen3-4B-Instruct-2507"12BASE, INCIDENT = "2026-12-08", "2026-12-09"13BUDGET, SLOW_NS = 120, 20 * NS_PER_SECOND14price = PriceTable()15base = only_messages(message_traces(run_day_traced(BASE, live=False).spans, BASE, MODEL, price))16expensive = nearest_rank([t.cost for t in base], 99) # the baseline day's 99th percentile of cost, as in the last example17live = run_day_traced(INCIDENT) # live: the contacts server runs the injected faults over stdio18traces = message_traces(live.spans + live.server, INCIDENT, MODEL, price) # each trace whole, the server's rows included19messages = only_messages(traces)20spans = sum(len(t.rows) for t in messages)21kept = TailRule(True, SLOW_NS, expensive, BUDGET).keep(traces)22no_budget = TailRule(True, SLOW_NS, expensive, sum(len(t.rows) for t in traces)).keep(traces)23kept_spans = sum(len(t.rows) for t in traces if t.seq in kept)24dropped = [t for t in messages if t.duration_ns > SLOW_NS and not t.error and t.seq not in kept]25print("spans in the incident day's messages:", fmt_int(spans))26print("spans in messages with an error:", fmt_int(sum(len(t.rows) for t in messages if t.error)))27print("span budget:", fmt_int(BUDGET))28print("spans the tail rule keeps with no budget, incident day:", fmt_int(sum(len(t.rows) for t in traces if t.seq in no_budget)))29print("spans kept under the budget, of all spans:", fmt_int(kept_spans))30print("share of spans kept under the budget:", fmt_share(kept_spans, spans))31for reason in ("error", "slow", "expensive"):32 print(f"messages kept for {reason}, under the budget:", fmt_int(sum(v == reason for v in kept.values())))33print("slow messages with no error, dropped for the budget:", fmt_int(len(dropped)))34print("time of the slowest message dropped for the budget:", fmt_ms(max(t.duration_ns for t in dropped)))35print("messages over the expensive threshold with no error or slow time, incident day:",36 fmt_int(sum(t.cost > expensive and not t.error and t.duration_ns <= SLOW_NS for t in messages)))37print("messages over the expensive threshold with no error or slow time, baseline day 1:",38 fmt_int(sum(t.cost > expensive and not t.error and t.duration_ns <= SLOW_NS for t in base)))39# Retention: bytes per message without content, in the JSON-lines export (capture is off until chapter 12).40per_message, kept_bytes, day_bytes = retained_bytes(base, messages, kept)41print("bytes per message without content, baseline day 1:", fmt_int(per_message))42print("bytes kept under the budget, of the incident day's bytes:", fmt_share(kept_bytes, day_bytes))43assert all(t.seq in kept for t in messages if t.error) # the budget leaves every error in44assert kept_spans <= BUDGET45assert sum(len(t.rows) for t in traces if t.seq in no_budget) > BUDGET
python tail-rule-span-budget.pyspans in the incident day's messages: 276
spans in messages with an error: 116
span budget: 120
spans the tail rule keeps with no budget, incident day: 127
spans kept under the budget, of all spans: 116
share of spans kept under the budget: 42.0%
messages kept for error, under the budget: 17
messages kept for slow, under the budget: 0
messages kept for expensive, under the budget: 0
slow messages with no error, dropped for the budget: 1
time of the slowest message dropped for the budget: 22,622.1 ms
messages over the expensive threshold with no error or slow time, incident day: 0
messages over the expensive threshold with no error or slow time, baseline day 1: 0
bytes per message without content, baseline day 1: 2,831
bytes kept under the budget, of the incident day's bytes: 42.6%
スパン予算を予算なしのスパン数よりわずかに下に設定する
+10 件の検証Tail sampling reads the whole trace、11章よりもう一度読む
errorを基にする。8章「スパンが失敗を記録する方法」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
13行目でスパン予算を設定している。この例が下の出力を表示するように、その値を変更せよ。本書の出力と異なるのは、スパン予算の行だけである。 spans in the incident day's messages: 276 spans in messages with an error: 116 span budget: 126 spans the tail rule keeps with no budget, incident day: 127 spans kept under the budget, of all spans: 116 share of spans kept under the budget: 42.0% messages kept for error, under the budget: 17 messages kept for slow, under the budget: 0 messages kept for expensive, under the budget: 0 slow messages with no error, dropped for the budget: 1 time of the slowest message dropped for the budget: 22,622.1 ms messages over the expensive threshold with no error or slow time, incident day: 0 messages over the expensive threshold with no error or slow time, baseline day 1: 0 bytes per message without content, baseline day 1: 2,831 bytes kept under the budget, of the incident day's bytes: 42.6%
仕組み
The budget keeps 116 spans, which is 42.0% of the day's. Those are the spans of the 17 messages with an error, and the rule keeps no slow message and no costly one.
Errors are ranked first, so they take their spans before anything else is considered, and the remainder of the budget is what is left for a slow message. The slow message without an error, which took 22,622.1 ms, holds more spans than that remainder, so the budget drops it. Two assertions in the code hold the rule to this: every error is kept, and the budget binds, since with no budget the rule keeps 127 spans, more than the budget allows.
The budget of 120 spans is the book's choice, not a rule of the method. It is above the spans that the errors take, so every error survives. The messages with an error hold 116 spans between them, so a budget below that would drop one of them, and the rule exists to keep them. A larger budget would also keep the slow message, at the cost of its spans.
The expensive class keeps nothing extra on either day. The number of messages above the expensive threshold with neither an error nor a slow time is 0 on the incident day and 0 on baseline day 1. Every costly message on both recorded days was also an error or a slow message, so the class does no work on them. We keep it in the rule because a costly message with neither mark is possible, and the rule should keep it when one comes. Neither recorded day shows one. The errors this rule keeps are also the traces that chapter 12 scans for personal data, so the rule also decides what that scan reads.
Working rule: Keep errors first, and set the budget above the spans they take on a day you have measured, not from a guess. Count the messages that are costly but neither erroneous nor slow before you trust a cost class, and say what a smaller budget would drop.
サンプルから1日の合計を推定する
サンプリングはスパンを間引くため、残ったスパンから合計した値はその日の実際の値より小さくなる。一方、サンプリングはカウンターを間引かない。第6章では、スパンを合計すると二重に数えることを示した。そのため本書では、アシスタントのメーターがモデル呼び出しの終了ごとに加算するカウンターから合計を読む。第9章もアラートを同じメーターから読むので、サンプリングが合計やアラートを間引くことはない。サンプルからの推定は、カウンターでは行えない内訳のためのものであり、内訳の精度は各部分の保持数で決まる。
ヘッドサンプルの合計をその比率の逆数で拡大すると、全体を推定できる。どのトレースも保持される確率が等しいからである。保持された合計に比率の逆数を掛けた値が、その日の推定値となる。区間は推定値の上下に標準誤差の1.96倍を取った範囲であり、標準誤差はサンプリングされたトレースだけから求める。テールルールは、比率にかかわらず一部のトレースを保持するため、その保持集合はその日の一定の割合にならない。ヘッド比率とテールルールを併用すると(後述の判断)、バックエンドが持つのは両者の和集合であり、これはヘッドサンプルではない。そこで、各トレースに保持された理由を記録し、ヘッドサンプルのトレースだけを拡大する。この節ではヘッドサンプルだけを拡大する。
ベースライン1日目の10%サンプルを10倍すると、その日の全数カウントやトークンカウンターと照らし合わせられる推定値が得られる。
1"""Estimate baseline day 1's total tokens and cost from a 10 percent head sample, scaled by one over the ratio, with the 952percent interval (the estimate plus or minus 1.96 standard errors). The estimate is set against the full count, summed over3every message, and against the token counter's total for the day. The point is coverage: over 2,000 independent samples the4interval holds the full count in only some of them, and the printed count says how many."""5from decimal import Decimal67from opentelemetry.sdk.metrics.export import InMemoryMetricReader89from lib.dayrun import RELEASE, run_day_traced10from lib.metrics import USAGE, make_meter_provider, totals11from lib.prices import PriceTable12from lib.report import fmt_int, fmt_share, fmt_usd13from lib.sampling import draws_holding, estimate_total, head_sample, message_traces, only_messages1415MODEL = "Qwen3-4B-Instruct-2507"16DAY, RATIO, DRAWS, SEED = "2026-12-08", 0.1, 2000, 20261207 # SEED is PL-6's; each draw salts the trace IDs with its number17reader = InMemoryMetricReader()18provider = make_meter_provider(reader, service_instance_id=f"{DAY}-metrics", service_version=RELEASE.service_version)19traced = run_day_traced(DAY, live=False, meter_provider=provider) # the assistant's live meter counts each call's tokens20traces = only_messages(message_traces(traced.spans, DAY, MODEL, PriceTable()))21counter = totals(reader)22counter_tokens = int(counter[USAGE["input"]]["sum"]) + int(counter[USAGE["output"]]["sum"])23sample = head_sample(traces, RATIO)24full_tokens = sum(t.tokens for t in traces)25full_cost = sum((t.cost for t in traces), Decimal(0))26print(f"messages kept at ratio {RATIO}, of {len(traces)}:", fmt_int(len(sample)))27tokens, tokens_interval = estimate_total([t.tokens for t in sample], RATIO)28print("full count of tokens, all messages:", fmt_int(full_tokens))29print("token counter total for the day, input plus output:", fmt_int(counter_tokens))30print(f"estimated tokens, ratio {RATIO}:", fmt_int(int(tokens)))31print("estimate as a share of the full count, tokens:", fmt_share(tokens, full_tokens))32print("interval as shares of the full count, tokens, low end:", fmt_share(tokens_interval[0], full_tokens))33print("interval as shares of the full count, tokens, high end:", fmt_share(tokens_interval[1], full_tokens))34cost, cost_interval = estimate_total([t.cost for t in sample], RATIO)35print("full cost of the day, Qwen3-4B-Instruct-2507 at the book's rates:", fmt_usd(full_cost))36print(f"estimated cost, ratio {RATIO}:", fmt_usd(cost))37print("estimate as a share of the full cost:", fmt_share(cost, full_cost))38print("interval as shares of the full cost, low end:", fmt_share(cost_interval[0], full_cost))39print("interval as shares of the full cost, high end:", fmt_share(cost_interval[1], full_cost))40assert counter_tokens == full_tokens # the counter reads each call once, so it matches the root spans41print("samples of the same day, drawn independently:", fmt_int(DRAWS))42held_tokens, held_cost = draws_holding(traces, RATIO, DRAWS, SEED)43print(f"intervals that hold the full count, of {fmt_int(DRAWS)} samples at ratio {RATIO}, tokens:", fmt_int(held_tokens))44print(f"intervals that hold the full count, of {fmt_int(DRAWS)} samples at ratio {RATIO}, cost:", fmt_int(held_cost))
python estimate-totals-error.pymessages kept at ratio 0.1, of 200: 21
full count of tokens, all messages: 109,807
token counter total for the day, input plus output: 109,807
estimated tokens, ratio 0.1: 98,090
estimate as a share of the full count, tokens: 89.3%
interval as shares of the full count, tokens, low end: 38.7%
interval as shares of the full count, tokens, high end: 140.0%
full cost of the day, Qwen3-4B-Instruct-2507 at the book's rates: $0.007563
estimated cost, ratio 0.1: $0.005524
estimate as a share of the full cost: 73.0%
interval as shares of the full cost, low end: 29.6%
interval as shares of the full cost, high end: 116.5%
samples of the same day, drawn independently: 2,000
intervals that hold the full count, of 2,000 samples at ratio 0.1, tokens: 1,843
intervals that hold the full count, of 2,000 samples at ratio 0.1, cost: 1,854
すべてのメッセージにわたって合計した全体のカウント
+10 件の検証サンプルから1日の合計を推定する、11章よりもう一度読む
counterを基にする。6章「Summing spans double counts」より
token countを基にする。6章「1回の呼び出しごとの三つのカウント」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
24行目は、保持されたメッセージのトークンを合計しているため、全体のカウントが1日全体の値ではなく、サンプルの合計になっている。全体のカウントが1日のすべてのメッセージのトークンになるように、24行目を変更せよ。
仕組み
推定は、ベースライン1日目の10%ヘッドサンプルから始める。このサンプルはその日のメッセージのうち21を保持しており、そのトークン数を10倍する。全数カウントは109,807トークンであり、第6章が合計を読むその日のトークンカウンターも同じ値、109,807になる。
1つのサンプルからは1つの推定値が得られる。区間は、サンプルの引き方を前提として、その日の全数カウントがどこにあり得るかを示す。この区間はサンプル自身の標準誤差から作られており、第7章のブートストラップ区間ではない。この1つのサンプルによるトークン推定値は98,090トークンである。
95%区間は全数カウントの38.7%から140.0%にわたり、この幅では判断の根拠にできない。21件のメッセージというサンプルでは、合計がその範囲のどこにあってもおかしくない。
この区間は、ラベルが示す水準にも届いていない。同じ日から独立に引いた2,000個のサンプルのうち、区間が全数カウントを含むものは1,843であり、区間が想定する95%を下回る。
コストの推定は、同じサンプルに対する別の合計である。推定値は$0.005524であり、本書の料金表book-2026-11-02で見積もったその日の全コスト$0.007563と比べられる。
その区間は全コストの29.6%から116.5%にわたり、同じサンプルのうち1,854がこれを含む。
比率を変えると、誤差が保持量にどう依存するかが分かる。
1"""Draw the error of a head sample's estimate of baseline day 1's total tokens against the sampling ratio, with the 95 percent2interval (chapter 11, `estimating-totals-from-a-sample`). The interval narrows as the ratio rises, and at ratio 1.0 every message3is kept, so the interval has no width. The points the prose names are printed, so a reader can read them off the lines."""4import math56from lib.dayrun import run_day_traced7from lib.figures import ACCENT, INK, MUTED, new_figure, save8from lib.prices import PriceTable9from lib.report import fmt_int, fmt_share10from lib.sampling import estimate_total, head_sample, message_traces, only_messages1112MODEL = "Qwen3-4B-Instruct-2507"13DAY = "2026-12-08"14RATIOS = (0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5, 1.0)15traces = only_messages(message_traces(run_day_traced(DAY, live=False).spans, DAY, MODEL, PriceTable()))16full = sum(t.tokens for t in traces)17points = [] # (ratio, estimate share, interval low share, interval high share)18for ratio in RATIOS:19 sample = head_sample(traces, ratio)20 estimate, (low, high) = estimate_total([t.tokens for t in sample], ratio)21 points.append((ratio, 100 * estimate / full, 100 * low / full, 100 * high / full))22 if ratio in (0.01, 0.1, 0.5):23 print(f"messages kept at ratio {ratio}, of {len(traces)}:", fmt_int(len(sample)))24 print(f"estimate as a share of the full count, ratio {ratio}:", fmt_share(estimate, full))25 print(f"interval low end as a share of the full count, ratio {ratio}:", fmt_share(low, full))26 print(f"interval high end as a share of the full count, ratio {ratio}:", fmt_share(high, full))27print("full count of tokens, all messages:", fmt_int(full))28xs, estimate_share, low, high = zip(*points)29fig, ax = new_figure(height=2.8)30ax.fill_between(xs, low, high, color=MUTED, alpha=0.35, linewidth=0, label="95% interval")31ax.plot(xs, estimate_share, color=ACCENT, linewidth=1.8, marker="o", markersize=3, label="estimate, head sample")32ax.axhline(100, color=INK, linewidth=1, linestyle=":", label="full count")33ax.set_xscale("log")34ax.set_xticks(RATIOS, [f"{r:g}" for r in RATIOS])35ax.set_xlabel("sampling ratio (log scale)")36ax.set_ylabel("estimate, % of full count")37bottom, top = float(min(low)), float(max(high)) # the axis starts at the lowest interval end, not at zero38pad = 0.1 * (top - bottom)39ax.set_ylim(bottom - pad, top + 2 * pad) # headroom above the widest interval, where the legend sits40ax.legend(loc="upper right", ncol=3, frameon=False)41save(fig, "sampling-error-by-ratio")42assert all(math.isclose(p[1], 100) for p in points if p[0] == 1.0) # at ratio 1 every message is kept, so no error43assert all(math.isclose(p[2], p[3]) for p in points if p[0] == 1.0) # and the interval has no width
python figure-sampling-error-by-ratio.pymessages kept at ratio 0.01, of 200: 5
estimate as a share of the full count, ratio 0.01: 251.5%
interval low end as a share of the full count, ratio 0.01: -4.4%
interval high end as a share of the full count, ratio 0.01: 507.5%
messages kept at ratio 0.1, of 200: 21
estimate as a share of the full count, ratio 0.1: 89.3%
interval low end as a share of the full count, ratio 0.1: 38.7%
interval high end as a share of the full count, ratio 0.1: 140.0%
messages kept at ratio 0.5, of 200: 96
estimate as a share of the full count, ratio 0.5: 97.5%
interval low end as a share of the full count, ratio 0.5: 79.4%
interval high end as a share of the full count, ratio 0.5: 115.5%
full count of tokens, all messages: 109,807
figure: figures/sampling-error-by-ratio.svg
図 11.1は、同じ推定を8つの比率で描いたものであり、そのバンドは比率が1.0に達すると閉じる。左端では5件のメッセージが保持され、推定値は全数カウントの251.5%である。区間は-4.4%から507.5%にわたるので下端がゼロを下回る。保持されたトレースがこれほど少ないと、正規近似が成り立たないためである。
0.1では21件のメッセージが保持され、推定値は全数カウントの89.3%であり、区間は38.7%から140.0%にわたる。
比率0.5では96件のメッセージが保持され、推定値は全数カウントの97.5%で、区間は79.4%から115.5%である。比率1.0ではすべてのメッセージが保持されるので、推定値は正確であり区間に幅はない。このことは例の中でアサートしている。
この区間が測るのは、この1日についてのサンプリングの偶然である。別の日でも同じ合計になるかどうかは別の問いであり、この区間はそれには答えない。
実践ルール: ヘッド比率が保持したトレースだけを、その比率の逆数で拡大する。推定値の横に区間を表示し、同じ日のカウンター合計があるときは、推定値をそれと照合する。サンプルによる推定は、カウンターでは行えない内訳にだけ使い、カウンターがすでに保持している合計には決して使わない。
保持されたトレースを保持するコスト
保持期間(リテンション)とは、バックエンドが各種のテレメトリをどれだけの期間保持するかを指す。Data Governance as Codeは、プラットフォームのデータについて同じ考え方を述べており、各種のデータをどれだけの期間保持するかを定める。本章はこの考え方をテレメトリにのみ適用し、期間そのものは定めない。期間は、インシデントの後にエンジニアがどこまで遡って調べる必要があるかと、ストレージのコストによって決まる。この二つはいずれも、バックエンドを運用するチームに属する事柄である。
期間はバイト数で支払うことになる。そのため、保持される割合を出力するテールルールの例は、1件のメッセージのトレースが占める大きさも測定している。ベースライン1日目では、キャプチャを無効にした状態で、JSON Lines形式のエクスポートにおける1件のメッセージのスパン行は2,831バイトを占める。この数え方の対象はスパン行のみである。インシデント当日の保持されたトレースは、その日のバイト数の42.6%を占め、スパン数に対する割合は42.0%である。この例ではバイト数がスパン数にほぼ比例しているため、この日に限れば、スパンの保持割合はバイトの保持割合のおおよその目安になる。
このバイト数にはコンテンツが含まれていない。キャプチャは第12章までは無効のままであり、第12章でそれを名指しした一つの目的のために有効にし、プロンプトと応答がこの同じエクスポート経路に加えるバイト数を測定する。したがって、このバイト数は1件のメッセージのトレースの下限である。また、サンプリングが決めるのは、どのスパンがバックエンドに届くかだけである。破棄したスパンをプロセスがどう扱うかは、サンプリングでは決まらない。第12章では、それらのスパンに含まれるコンテンツをアップロードフックがどう扱うかを示す。
実践ルール: 期間を決める前に、自分のエクスポートで1件のメッセージあたりのバイト数を測定すること。測定は、コンテンツなしの場合と、保持する予定のコンテンツを含めた場合の両方で行う。期間は、それが掛け合わされるバイト数と並べて記録し、そのバイト数が含んでいないものを明記すること。
本番環境でサンプリングが失敗する場面
ヘッド比率は、その割合が示すことだけを行い、それ以上のことはしない。判断がメッセージを読まないため、平穏な日でも新しい障害が起きた日でも、保持される割合の期待値は同じである。テールルールの保持集合は障害に応じて動く。本章で両方を用いるのはそのためである。ヘッドサンプルにも用途はある。通常のトレースの標本を保持するので、典型的なメッセージを読むことができ、その判断にはメッセージを見る必要がない。
テールルールの二つのしきい値は、本書の別の部分に由来しており、動くものである。レイテンシの基準線は第9章の目標である。高コストの基準線は、基準日のコストの99パーセンタイルであり、コストを変えるリリースがあれば、それに伴って動く。したがって、高コストの基準線は、メッセージ1件のコストを変えるリリースのたびに読み直すものであり、最初の基準値のまま保つものではない。
このルールは完全なトレースを必要とし、手元にあるトレースを判定する。切り離されたルートは独自のトレースを開始し、ルールはそのトレースを、そこに含まれる内容によって判定する。障害日の例では、そのようなトレースが4件数えられる。いずれも、タイムアウトした検索の後に、現在のコンテキストがない状態で送られた MCP のnotifications/cancelledスパンであり、それぞれが単独で判定される。そのメッセージの残りは別のトレースにあり、ルールは別の根拠でそれを保持することも破棄することもある。この確認が対象とするのは本書のトレースの形だけであり、本番にはここに現れない別の形が存在しうる。
実践ルール: ルールは、平穏な日ではなく、問題が起きた日に何を保持するかで判定し、測定対象が変わるリリースの後には、各しきい値を読み直す。
この部分はまだ翻訳されていないため、英語で表示している。
The decisions this chapter made
The decisions below follow from one fact the examples show: a sampler's share is set before the message is known, so keeping the messages an engineer needs takes a rule that reads each whole trace.
- We keep the head ratio and the tail rule together. The head sample alone kept 2 of the 17 messages with an error, and the tail rule keeps all of them.
- The tail rule keeps errors first, then slow messages, then costly ones, under a budget of 120 spans. The budget sits above the spans the errors take, and one below them would drop an error.
- Every service samples with parent-based sampling, and only the root's service makes the decision. The contacts server follows the assistant's flag and runs no ratio of its own.
- Chapter 6's rule for totals holds here. A sampled estimate, printed with its interval, is for a split the counters cannot make, and it is only as good as each part's kept count.
- The retention period belongs to the team. We measure the bytes per message first, without content, and chapter 12 adds what content costs.
Two of these are judgements that the examples cannot settle. The budget of 120 spans is one, because it is the book's number and not a measured limit. Parent-based sampling is the other. The probe checks the SDK's default sampler on one server, and it says nothing about services that this book does not run. A reader who copies the rule should measure their own day first: the spans their errors take, the bytes per message, and the messages that are costly but neither erroneous nor slow. Only then should any number in this chapter become a setting.
What the chapter learned is narrower than a rule about sampling. A head sampler's share is fixed by the trace ID before the message runs, so only a rule that reads each whole trace keeps the messages an engineer needs. A total from the kept traces is an estimate, and it carries its interval wherever it is printed.
Working rule: Before you copy a sampling setting, run its example on a day you have recorded yourself, and keep each setting with the example that tests it.
この版における本章
第2026.11.2版2026年11月23日時点で例が通過この章の6 例件のうち6件が合格
英語版の書籍(版2026.11.2)から翻訳した。