选择保留哪些追踪
阅读约 48分钟,7节中含6个示例。
实验室
通过动手实践学习本章
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。约 30 秒后打开。
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。Labs 为你运行:每月 40小时。
在你自己的机器上,免费: 下载本书的笔记本,附其代码和数据,来源为 GitHub。
在本书所用版本上运行你的代码
读完本章,你将能够选择后端保留哪些追踪,说明每种选择会丢弃什么,并根据保留下来的追踪推算总量,同时给出结果的区间。你会编写一条规则,保留工程师最需要的追踪,并用事故日的数据检验这条规则。
Ambrewick 为每条消息保留一条追踪,第 1 章也全部保留了。按本书的规模,即每天 200 条消息,这样做管理起来很简单。但一个全天都在应答消息的服务会写出多得多的数据,而一个把所有追踪保存一年的后端要为每一条付费。采样器保留一部分追踪,丢弃其余的,因此关键的决定是保留哪些。事故日说明了这个问题。事故日的错误很少见,告警之后打开追踪的工程师,比起任何一条典型消息,更需要这些错误和缓慢的消息。一个不读取追踪内容就挑选追踪的采样器,保留稀有追踪的比例与保留其他追踪的比例相同。
本章构建追踪采样所做的三类决定,以及只保留部分追踪时推算总量所需的估计方法。这里的追踪采样指决定后端保留哪些追踪,它与词元采样无关,后者是为模型选择下一个要写出的词。示例运行在两个已记录的日期上:没有注入故障的基线日 1,以及第 9 章中的事故日。两者都记录于记录机器上,这台机器配备 4 个 vCPU、主频 2.10 GHz 的 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.
子跨度遵循根跨度的决定
一条追踪会跨越进程边界,而联系人服务器就是第二个进程。第 4 章把追踪的标识作为 traceparent 放进了每个请求,该请求头的标志位之一是采样标志(Trace Context Level 1,本书所固定的版本)。基于父级的采样让每个跨度都遵循其父级的决定。根跨度向头部采样器询问,其下的每个跨度则读取父级的标志,而不是自己再运行一次比例采样。这一点在跨进程时很重要,因为服务器看不到助手的采样比例,只能看到标志。
联系人服务器没有设置自己的采样器。它的追踪器提供者采用 SDK 的默认值,即 OTEL_TRACES_SAMPLER 未设置,这会遵循远程父级的采样标志:标志已设置时,服务器对该跨度采样;未设置时,服务器丢弃它。下面的探测在源头开启助手的采样器,比例为 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
为什么未采样的根没有服务端 span
+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章,“span 如何记录失败”
建立在 failed message 的基础上,参见第9章,“服务级别目标”
新版次改变了本节所练习的内容。版次 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%
预算略低于无预算时的 span 数量
+10 项证明来自Tail sampling reads the whole trace,第 11 章再读一遍
建立在 error 的基础上,参见第8章,“span 如何记录失败”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 13 行设定了 span 预算。请修改它,使该示例打印出下面的输出,其中只有 span 预算那一行与本书的输出不同。 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.
用样本估算当天的总量
采样会稀疏化 span,因此由保留下来的 span 加总得到的总量小于当天的实际总量,而采样并不会稀疏化计数器。第 6 章说明了对 span 求和会重复计数,所以本书从计数器读取总量,计数器由助手的计量器在每次模型调用结束时累加。第 9 章的告警也读取同一个计量器,因此采样不会稀疏化任何总量或告警。样本给出的估计用于计数器无法做出的拆分,而拆分的质量只取决于每一部分保留下来的数量。
把头部采样的总量按其比例的倒数放大,就能估计整体,因为每条 trace 被保留的概率相同:保留的总量乘以比例的倒数,即估计当天的总量。区间为估计值加减 1.96 个标准误,标准误只由被采样的 trace 计算。尾部规则无论比例如何都会保留一些 trace,所以它保留的集合不是当天固定的一部分。头部比例与尾部规则一起运行时(见下文的决策),后端保存的是二者的并集,它不是头部样本,因此应为每条 trace 标记其被保留的原因,只对头部样本中的 trace 放大。本节只放大头部样本。
把基线第 1 天的一个 10% 样本放大十倍,得到的估计可以与当天的完整计数以及 token 计数器对照。
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 项证明来自用样本估算当天的总量,第 11 章再读一遍
建立在 counter 的基础上,参见第6章,“对跨度求和会重复计数”
建立在 token count 的基础上,参见第6章,“每次调用的三个计数”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 24 行对保留下来的消息的词元数求和,所以完整计数是样本的总量,而不是全天的总量。请修改第 24 行,使完整计数等于当天每条消息的词元数之和。
原理何在
该估计从基线第 1 天的 10% 头部采样出发,这个样本保留了当天 21 条消息,并把它们的 token 放大十倍。完整计数为 109,807 个 token,第 6 章读取总量所用的当天 token 计数器,加总后得到相同的数值:109,807。
一个样本只给出一个估计,区间说明在样本这样抽取的前提下,当天的完整计数可能落在何处。这个区间由样本自身的标准误构造,不是第 7 章的 bootstrap 区间。该样本给出的 token 估计为 98,090 个 token。
95% 区间从完整计数的 38.7% 延伸到 140.0%,宽到无法据此行动:21 条消息的样本使总量可以落在这一范围内的任何位置。
区间的实际覆盖率也低于其标称水平。对同一天独立抽取的 2,000 个样本,有 1,843 的区间包含完整计数,而该区间本应达到 95%。
成本估计是对同一样本另做的一次求和。它为 $0.005524,而当天的完整成本为 $0.007563,按本书的价格表 book-2026-11-02 计价。
其区间从完整成本的 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在八个比例下绘出同一估计,比例趋近 1.0 时其带状区间收拢。在最左端保留了 5 条消息,估计为完整计数的 251.5%。其区间从 -4.4% 延伸到 507.5%,所以下端低于零,保留的 trace 太少,正态近似在这里失效。
比例为 0.1 时,保留了 21 条消息,估计为完整计数的 89.3%,区间从 38.7% 延伸到 140.0%。
比例为 0.5 时保留 96 条消息,估计为完整计数的 97.5%,区间从 79.4% 到 115.5%。比例为 1.0 时每条消息都被保留,所以估计是精确的,区间没有宽度,示例对此做了断言。
该区间度量的是这一天中采样的偶然性。换一天是否会得到同样的总量是另一个问题,这个区间并不回答它。
工作准则: 只对头部比例保留的 trace 按其比例的倒数放大,把区间与估计并列打印,并在存在同一天的计数器总量时,用它核对估计。只在计数器无法做出的拆分上使用采样估计,对计数器已有的总量绝不使用。
保留一条追踪的存储成本
留存期是后端对每一类遥测数据的保存时长。Data Governance as Code针对平台数据表达了同样的思想:每一类数据保存多久。本章只把它用于遥测数据,并不规定具体期限。期限取决于事故之后工程师需要回溯多久,也取决于存储的成本,而这两点都由运行后端的团队决定。
期限的代价以字节计,因此,打印出保留比例的尾部规则示例也测量了一条消息的追踪占用多少空间。在基线第 1 天,不开启内容捕获时,一条消息的 span 行在 JSON-lines 导出中占 2,831 字节,这个数字只统计 span 行。事故当天被保留的追踪占当天字节数的 42.6%,而其 span 的占比为 42.0%。这里字节数与 span 数的变化十分接近,所以在这一天,span 的保留比例可以较好地反映字节的保留比例。
这个计数不含内容。内容捕获在第 12 章之前一直处于关闭状态,第 12 章会为一个指定的目的将其开启,并测量提示词和回复在同一条导出路径上增加的字节数。因此,上述字节数只是一条消息追踪大小的下限。此外,采样只决定哪些 span 会到达后端,并不决定进程如何处理被丢弃的 span,第 12 章会说明上传钩子如何处理这些 span 中的内容。
工作准则: 在设定期限之前,先在自己的导出数据上测量每条消息的字节数,先测不含内容的情形,再测计划保留的各类内容。把期限与它所乘的字节数放在一起,并写明这些字节没有包括什么。
生产环境中采样出错的地方
头部比例采样只做它的比例所承诺的事,不多也不少。无论是平静的一天,还是出现新故障的一天,它保留的期望份额都相同,因为它的决策从不读取消息。尾部规则保留的集合则会随故障而变化,本章因此同时使用这两种方法。头部采样仍有其用处:它保留一份普通追踪的样本,使人可以阅读典型的消息,而且它的决策无需查看消息。
尾部规则的两个阈值来自本书的其他部分,并且会发生变化。延迟线是第 9 章的目标。昂贵线是基线日成本的第 99 百分位数,而改变成本的发布会使它随之移动。因此,每次发布改变了一条消息的成本之后,都要重新读取昂贵线,而不是沿用最初的基线。
该规则需要完整的追踪,并且只能判断它手头已有的追踪。分离根会开启一条属于自己的追踪,规则依据这条追踪所含的内容来判断它。在事故日,该示例统计到 4 条这样的追踪,每一条都是在查询超时、且当前没有上下文之后发送的 MCP notifications/cancelled span,并且各自被单独判断。该消息的其余部分位于另一条追踪中,规则可能出于其他理由保留或丢弃它。这一检查只涵盖本书中追踪的形态,生产环境中可能存在它没有显示的其他形态。
工作准则: 评判一条规则,要看它在出问题的日子里保留了什么,而不是看它在平静日子里的表现;在发布改变了某个阈值所度量的对象之后,要重新读取该阈值。
这部分尚未翻译,因此以英文显示。
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 of 6个示例 in this chapter pass
译自英文版图书,版次 2026.11.2。