让隐私数据不进入遥测
阅读约 63分钟,10节中含7个示例。
实验室
通过动手实践学习本章
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。约 30 秒后打开。
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。Labs 为你运行:每月 40小时。
在你自己的机器上,免费: 下载本书的笔记本,附其代码和数据,来源为 GitHub。
在本书所用版本上运行你的代码
读完本章,你将能够默认让个人数据不进入助手的遥测数据,能够为明确的目的开启内容捕获并统计由此泄露的内容,也能说明哪些泄露可以通过脱敏消除,哪些脱敏无法触及。你还将运行扫描,统计剩余的内容,并了解哪些计数是按断言为零,哪些只是实测所得。
Ambrewick 的追踪数据会被没有参与开发助手的人读到。值班工程师在告警之后打开追踪,联系人团队则打开由其自身查询所关联的追踪。这些追踪中有一部分内容属于个人数据。无论是否有人要求捕获内容,每条消息的根跨度都带有用户 ID;而追查某一次错误路由的工程师,会想要看到提示词和回复。捕获这些内容,就会把用户的姓名放进同样的跨度,与请求中提到的人物、地点和关系放在一起。联系人服务器还带来一种泄露,任何捕获开关都无法控制它。这个案例中的问题在于:能解释一次错误路由的追踪,同时也是对话的一份副本。
案例中的用户、工具和联系人都是合成的,请求则来自 MASSIVE。用户的姓名取自固定列表,邮箱地址位于 .example 域名下,案例本身没有支付号码或电话号码。这些请求保留了 MASSIVE 标注的人物、地点和关系取值。这些取值是数据集的众包标注员所写的请求文本,本书保持其原样,并按其槽位加以标记。扫描器读取每个跨度的取值及其捕获的文本,对它查找的每一类内容进行计数,每个匹配计为一项;本章报告的是脱敏无法消除的那部分计数。多数示例回放基线第 1 天。涉及联系人服务器时,示例读取第 9 章中的事故日。
首先关闭内容捕获
第 3 章介绍的内容捕获开关是本章的首要防线,因此放在最前面。开关未设置时,软件包既不记录提示词,也不记录回复,后续步骤便没有内容可供移除。本节之后的所有内容,都针对有人打开了该开关的情形。尚未为内容指明用途的服务应保持开关的默认值,并且要读取其加载的每个软件包的默认值,因为一个软件包的默认值不等于另一个软件包的默认值。
在四种模式下各执行一次模型调用,可以看出每种模式向跨度和日志写入了什么。
1"""The four content modes of the official package, each set before the package is instrumented and run on the same2recorded answer call. The point rests on the printed pairs: only the span modes put the messages on the span, and only3the event modes write a log record, so SPAN_AND_EVENT writes both. The example prints counts, never the messages."""4import lib # lib first: threads and seeds are fixed before anything else56import os78from opentelemetry.instrumentation.genai.openai import OpenAIInstrumentor9from opentelemetry.sdk._logs import LoggerProvider10from opentelemetry.sdk._logs.export import InMemoryLogRecordExporter, SimpleLogRecordProcessor11from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1213from lib.assistant import RELEASES14from lib.clock import VirtualClock15from lib.ids import SequentialIds16from lib.scan import CAPTURE, CONTENT_KEYS, captured_call, model_calls17from lib.tracing import make_provider1819CALL = next(call for call in model_calls("baseline-day-1") if call["step"] == "answer") # the day's first answer call20EXPECTED = {"NO_CONTENT": (0, 0), "SPAN_ONLY": (2, 0), "EVENT_ONLY": (0, 1), "SPAN_AND_EVENT": (2, 1)}212223def run(mode: str) -> tuple[int, int, str]:24 """One call under `mode`: the content attributes on its span, the log records written, and the log's event name."""25 os.environ[CAPTURE] = mode # the package reads the mode when it is instrumented, so it is set first26 spans, logs = InMemorySpanExporter(), InMemoryLogRecordExporter()27 logger_provider = LoggerProvider()28 logger_provider.add_log_record_processor(SimpleLogRecordProcessor(logs)) # where the event modes write their record29 provider = make_provider("ambrewick-assistant", RELEASES["r0"].service_version, "modes",30 VirtualClock("2026-12-08"), SequentialIds(), spans,31 "https://opentelemetry.io/schemas/1.45.0")32 instrumentor = OpenAIInstrumentor()33 instrumentor.instrument(tracer_provider=provider, logger_provider=logger_provider)34 captured_call(CALL)35 instrumentor.uninstrument()36 del os.environ[CAPTURE]37 content = sum(key.startswith(CONTENT_KEYS) for key in spans.get_finished_spans()[0].attributes)38 names = {record.log_record.event_name for record in logs.get_finished_logs()}39 return content, len(logs.get_finished_logs()), ", ".join(sorted(names))404142for mode in EXPECTED:43 content, records, event = run(mode)44 print(f"content attributes on the span, {mode}: {content}")45 print(f"log records, {mode}: {records}")46 if event:47 print(f"event name on the log record, {mode}: {event}")48 assert (content, records) == EXPECTED[mode] # the pairs the prose quotes
python capture-modes.pycontent attributes on the span, NO_CONTENT: 0
log records, NO_CONTENT: 0
content attributes on the span, SPAN_ONLY: 2
log records, SPAN_ONLY: 0
content attributes on the span, EVENT_ONLY: 0
log records, EVENT_ONLY: 1
event name on the log record, EVENT_ONLY: gen_ai.client.inference.operation.details
content attributes on the span, SPAN_AND_EVENT: 2
log records, SPAN_AND_EVENT: 1
event name on the log record, SPAN_AND_EVENT: gen_ai.client.inference.operation.details
自第 2026.11.2 版起由 openai3.56.0至3.57.0 更新。
在插桩之前设置捕获开关
+10 项证明建立在 automatic instrumentation 的基础上,参见第3章,“A call through the client”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 25 行为空。请写出一条语句,把本次运行的模式写入开关,使软件包在第 33 行被插桩时能读取到该模式。
原理何在
开关未设置时,内容两处都不存在:跨度上的内容属性为 0,软件包写入的日志记录为 0。跨度模式把提示词和回复放到跨度上,事件模式则写入日志记录,下一节会说明这一点。这一对结果就是把关闭捕获作为首要防线的全部理由:内容不在遥测数据中,下游便无从泄露。
关闭捕获并不意味着没有任何信息外流。无论设置哪种模式,用户 ID 都出现在每条消息的根跨度上,泄露示例也断言,无论捕获设置如何,每条消息都有一个这样的跨度。该 ID 是用户自己的标识符,而追踪需要某种标识符来回答一条消息来自哪位用户,因此不能省略。它必须在存储之前被替换,带密钥的用户假名说明了做法。
在基线第 1 天的所有跨度中,无论捕获开启还是关闭,都没有出现电子邮件地址。助手的策略要求模型在回复中绝不重复联系人的地址,并且没有任何工具跨度携带其参数,因此地址没有进入跨度的途径。扫描器在脱敏之前和之后都没有发现地址。电子邮件一类的计数为零,是因为设计没有给地址留下途径,而扫描器按原样查找每个用例中的地址,也证实了这一点。
姓名的表现则不同。关闭捕获时,泄露示例断言用户姓名和消息文本都不会进入跨度。只有在开启捕获时才会出现姓名,下一节将对此进行度量。
工作准则: 在每个服务中保持内容捕获关闭,并在部署前读取每个已加载软件包的默认值。只为能够明确说出的用途开启捕获,并且只在后端保留每个跨度之前都有脱敏器对其运行的地方开启。
这部分尚未翻译,因此以英文显示。
What leaks when capture is on
Suppose an engineer turns capture on to debug one wrong route. The reason is a good one, and what it costs is the same for every message that day. Each mode writes content to a different place. In SPAN_ONLY the prompt and the reply go into two span attributes, gen_ai.input.messages and gen_ai.output.messages, the names the registry gives them. The system text is folded into the input messages, so the instructions the model was given travel with the user's text. In EVENT_ONLY the same content goes onto a log record named gen_ai.client.inference.operation.details, and the span holds none of it. SPAN_AND_EVENT writes both. The logs SDK is still published under the private opentelemetry.sdk._logs at 1.45.2. A reader configures a LoggerProvider from it, and InMemoryLogRecordExporter is the class that reads records back. The package writes through the logs API, not that path. A second switch writes content as well. The upload hook writes messages to a store whenever it is on, with capture set or not, and keeping content by reference shows what that does.
A personal-looking value is a person, place or relation name in a request's text, written by the dataset's crowd workers and labelled by its slots; it looks like personal data in a span and is treated as such; it was written for the dataset and is not drawn from anyone's messages, though the dataset keeps some public names as written. Data Governance as Code treats personal data as data that relates to an identifiable person. The handling here, to find, redact and count, is the same. The same reading covers the other slot labels the scanner counts. The scanner finds these values by their words in the captured text. A word that is a value under one label can match under another, so the counts are measures.
Running the day twice, with capture off and then on, shows what each run's spans hold.
1"""What the day's telemetry holds before any redaction, with content capture off and on, and the stack traces that leave the2contacts server with capture off. The point rests on the printed counts: every root span holds its user's ID either way,3the names and the dataset's values appear only with capture on, and the server's error spans carry stack traces that4reach the receiver. The example prints counts and the shape of one path, never a value or a full path."""5import lib # lib first: threads and seeds are fixed before anything else67import re8from pathlib import Path910from lib.case import load_messages11from lib.dayrun import run_day_traced12from lib.report import fmt_int13from lib.scan import KINDS, captured_day, label, live_rows, of_service, scan_rows, spans_holding, stack_traces1415DAY, INCIDENT = "2026-12-08", "2026-12-09" # baseline day 1, and the incident day, whose contacts server fails16assistant = run_day_traced(DAY, live=False).spans # the assistant's own spans; the replay keeps no content17content = captured_day(DAY) # the day's model calls through the package, content on18rows = assistant + content19items, spans = scan_rows(rows), spans_holding(rows)20print("messages on the day:", fmt_int(len(load_messages(DAY))))21print("spans, capture off:", fmt_int(len(assistant)))22print("spans from the package, capture on:", fmt_int(len(content)))23for kind in KINDS:24 if kind != "stacktrace": # the stack traces are on the incident day, below25 print(f"{label(kind)} items, capture off and on: {fmt_int(items[kind])}")26 print(f"{label(kind)} spans holding it: {fmt_int(spans[kind])}")27off = scan_rows(assistant)28assert all(off[kind] == 0 for kind in KINDS if kind not in ("user_id", "stacktrace")) # capture off: no name, no text29assert spans["user_id"] == len(load_messages(DAY)) # one root span per message, each with the user's ID, whatever the capture30assert items["user_name"] > 0 and items["slot:person"] > 0 # capture on: names and the dataset's values reach spans3132# The incident day through the book's receiver, capture off. The contacts server's error spans carry the traceback.33live = live_rows(INCIDENT)34server, mine = of_service(live, "contacts-server"), of_service(live, "ambrewick-assistant")35server_traces = stack_traces(server)36errors = sum(row["status"] == "ERROR" for row in server if row["name"] == "contacts.lookup")37traced = {row["trace_id"] for row in live if stack_traces([row])}38print("contacts server spans the receiver stored:", fmt_int(len(server)))39print("contacts.lookup spans in error:", fmt_int(errors))40print("stack traces on the contacts server's spans:", fmt_int(len(server_traces)))41print("stack traces on the assistant's spans:", fmt_int(len(stack_traces(mine))))42print("incident traces holding a stack trace:", fmt_int(len(traced)))43print("file paths named in the server's stack traces:", fmt_int(sum(t.count('File "') for t in server_traces)))44# The innermost frame names the file and line that raised. Only the file's name is printed; its folder is a placeholder.45path, line, function = re.findall(r'File "([^"]+)", line (\d+), in (\S+)', server_traces[0])[-1]46print(f'innermost frame, first server trace: File "<folder>/{Path(path).name}", line {line}, in {function}')47assert len(server_traces) == errors and stack_traces(mine) # every error span of the server carries its traceback
python leak-with-capture-on.pymessages on the day: 200
spans, capture off: 675
spans from the package, capture on: 321
user_id items, capture off and on: 200
user_id spans holding it: 200
user_name items, capture off and on: 2
user_name spans holding it: 2
email items, capture off and on: 0
email spans holding it: 0
person slot items, capture off and on: 55
person slot spans holding it: 38
place_name slot items, capture off and on: 44
place_name slot spans holding it: 33
relation slot items, capture off and on: 26
relation slot spans holding it: 25
email_address slot items, capture off and on: 0
email_address slot spans holding it: 0
personal_info slot items, capture off and on: 0
personal_info slot spans holding it: 0
contacts server spans the receiver stored: 22
contacts.lookup spans in error: 3
stack traces on the contacts server's spans: 3
stack traces on the assistant's spans: 4
incident traces holding a stack trace: 5
file paths named in the server's stack traces: 9
innermost frame, first server trace: File "<folder>/contacts_server.py", line 164, in find_contact
自第 2026.11.2 版起由 openai3.56.0至3.57.0 更新。
With capture off, each of the 200 messages leaves a user ID on its root span, and no name or message text reaches a span. With capture on, names reach 2 spans and the spans holding a person value number 38. The text sits in the package's model-call spans, of which there are 321, while the assistant's own spans carry no text. The next section's redaction is the answer to what the text leaves behind.
Capture also adds bytes to every message's trace, and chapter 11 asked for that number before any period was set. Measuring the bytes on the same export path puts a number on the cost.
1"""What content capture adds to a message's bytes on baseline day 1, and what the SDK does to a long content value. A2message's bytes are those of its spans' rows in the JSON-lines export. The assistant's own spans carry no content, so the3bytes content adds are the difference between the package's spans for the same calls with capture on and off. The point4rests on the printed bytes per message and on the value limit's count of cut values, which the example also checks."""5import lib # lib first: threads and seeds are fixed before anything else67import os89from lib.case import load_messages10from lib.dayrun import run_day_traced11from lib.report import fmt_int, fmt_share12from lib.sampling import row_bytes13from lib.scan import CONTENT_KEYS, captured_day, is_json1415DAY = "2026-12-08"16LIMIT = 1000 # characters, for the value limit below17messages = len(load_messages(DAY))18assistant = run_day_traced(DAY, live=False).spans # the message's spans, capture off: no content in them19off, on = captured_day(DAY, "NO_CONTENT"), captured_day(DAY, "SPAN_ONLY")20added = row_bytes(on) - row_bytes(off) # the bytes content adds to the package's spans, over every call of the day21total = row_bytes(assistant) + added22print("bytes per message, capture off:", fmt_int(round(row_bytes(assistant) / messages)))23print("bytes content adds per message, capture on:", fmt_int(round(added / messages)))24print("bytes per message, capture on:", fmt_int(round(total / messages)))25print("content share of the bytes, capture on:", fmt_share(added, total))262728values = [value for row in on for key, value in row["attributes"].items() if key.startswith(CONTENT_KEYS)]29os.environ["OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT"] = str(LIMIT) # read when the provider is made: set before captured_day30cut = [value for row in captured_day(DAY) for key, value in row["attributes"].items() if key.startswith(CONTENT_KEYS)]31del os.environ["OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT"]32pairs = [(full, short) for full, short in zip(values, cut) if len(full) > LIMIT] # each value, with and without limit33print("longest content value, no limit:", fmt_int(max(map(len, values))), "characters")34print(f"value length limit: {LIMIT:,} characters")35print("longest content value, cut at the limit:", fmt_int(max(map(len, cut))), "characters")36print("content values on the day:", fmt_int(len(values)))37print("content values cut by the limit:", fmt_int(len(pairs)))38print("cut values that no longer parse as JSON:", fmt_int(sum(not is_json(short) for _, short in pairs)))39# Nothing in the span marks a cut value, so a reader sees a shorter, broken message and no flag.40assert len(cut) == len(values) and max(map(len, cut)) == LIMIT41assert all(len(short) == LIMIT for _, short in pairs)42assert all(not is_json(short) for _, short in pairs) # a value cut at a character is no longer JSON
python content-bytes-per-message.pybytes per message, capture off: 2,831
bytes content adds per message, capture on: 2,716
bytes per message, capture on: 5,547
content share of the bytes, capture on: 49.0%
longest content value, no limit: 2,907 characters
value length limit: 1,000 characters
longest content value, cut at the limit: 1,000 characters
content values on the day: 642
content values cut by the limit: 87
cut values that no longer parse as JSON: 87
自第 2026.11.2 版起由 openai3.56.0至3.57.0 更新。
Content nearly doubles a message's bytes. With capture off, a message's span rows take 2,831 bytes, the figure chapter 11 printed. With capture on they take 5,547, so content adds 2,716 bytes, which is 49.0% of the total. The bytes are those of each span's row in the JSON-lines export.
The SDK can also cut a long value. The longest content value on the day is 2,907 characters long. Under a value length limit of 1,000 characters, that value is cut to the limit. The limit touches 87 of the 642 values, and every cut value fails to parse as JSON. A value cut at a character is shorter, and it no longer reads as the structure it was. The limit counts characters, not bytes, so a value cut at the limit can still take more bytes than the limit suggests.
Working rule: Measure a message's bytes with content on, as well as with it off, before you choose a retention period. Count the bytes against the export the period will keep, and do not assume that a limit leaves a readable value.
这部分尚未翻译,因此以英文显示。
Stack traces leak without capture
The contacts server is a separate process, and its spans reach the receiver by a route the assistant's code does not control. Chapter 4 introduced the server, and chapter 5 showed that it exports its own spans over OTLP when it is given an endpoint. The server opens its contacts.lookup span with start_as_current_span and sets nothing about exceptions, so the API's default, record_exception=True at 1.45.2, writes an exception event on that span when a tool raises. The event can carry exception.stacktrace, the traceback. A traceback names each file by its path, and those paths name the folders of the process that ran the code.
Capture was off when the leak example read the incident day, and the stack traces were there anyway. On that day the receiver stored 22 contacts server spans. 3 of its contacts.lookup spans were in error, and each of those error spans carried a stack trace, 3 in all. Between them the traces name 9 file paths. The innermost frame of the first one is find_contact, in the server's own file, contacts_server.py, under a placeholder for the folder. The output prints the shape of that path and never the path itself, since a full path is what this section is about. The fix below drops only exception.stacktrace: the exception event, with its class and message, stays, as chapter 8 decided.
The assistant's own spans carry stack traces as well, 4 of them on the incident day. The MCP SDK's client dispatcher writes those on the client spans, and the tool-attempt spans carry only the exception's class and message. So the traceback leaves from both processes, and the leak does not depend on what the assistant chooses to record. Tail sampling in chapter 11 keeps a trace whose message has an error, and the scan reads every one of the 5 traces that hold a stack trace, kept or dropped.
A stack trace names no user, but its paths can name the account that ran the process, which is personal data, and they reveal the machine. The scanner counts stack traces as a kind of their own, apart from the personal items. A reader might ask whether the traceback is worth keeping. The engineer who opens a trace needs the exception's class and message, which the span keeps, and the failing tool's name, which it also keeps. The folder names add nothing a fix needs.
This is the leak that capture cannot stop, and the assistant's redactor cannot reach the server's half of it. The redaction section counts what is left after the assistant's redactor runs, and shows where a redactor does reach these traces.
Working rule: Treat a stack trace as sensitive in every service, and keep it out of any backend. Remove it where every service's spans pass. At the source, ask the team that owns the server to set record_exception=False on the span and to set the exception's class and message by hand, since the client's traces can only be removed downstream.
脱敏是纵深防御
脱敏是指在 span 存储之前,把其属性或事件中的个人值替换为占位符:可以在产生该 span 的进程中进行,也可以在所有服务的 span 经过的位置进行。助手的进程使用 span 处理器来完成这项工作,该处理器的定义见第 1 章。这个处理器在 span 结束时导出一份脱敏后的副本。它必须复制,因为 SDK 会在 span 结束时冻结其属性,此后无法再原地修改。Data Governance as Code 中的 redact是对查询列做的 NULL 转换,与这里的操作不同,因为这里的脱敏针对的是遥测数据。
处理器移除的内容是明确的。合成用户的姓名和地址变为占位符 [name] 和 [email]。用户 ID 变为其假名,假名在下一节中定义。堆栈跟踪被直接丢弃而不是替换,因为其中的路径会暴露运行该代码的进程所在的文件夹。file:// 引用保留其协议和文件名,其文件夹变为占位符。span 的状态描述同样会被脱敏,因为它可能包含异常消息。看起来像个人信息的值则原样通过,因为处理器无法区分自由文本中的姓名和其他词,而该案例也没有提供可用于区分二者的标签。
下面的示例对当天的 span 运行该处理器并统计剩余内容,然后对事故当天已存储的行运行接收端的脱敏。
1"""The scanner's count after redaction, with the redacting processor on every set of spans. On baseline day 1 the synthetic2kinds are asserted zero, and MASSIVE's slot labels are counted before and after, their residue printed and never asserted3zero. On the incident day the contacts server's stack traces reach the receiver, and the receiver's redaction removes them4from both processes' spans. The point rests on the zeros and on the residue; the example prints counts only."""5import lib # lib first: threads and seeds are fixed before anything else67from lib.redact import redact_row8from lib.report import fmt_int9from lib.scan import SLOT_LABELS, SYNTHETIC, absolute_paths, assistant_rows, captured_day, label, live_rows, of_service10from lib.scan import scan_rows, stack_traces1112DAY, INCIDENT = "2026-12-08", "2026-12-09"13before = scan_rows(assistant_rows(DAY) + captured_day(DAY)) # the day's spans, as they are made14after = scan_rows(assistant_rows(DAY, redact=True) + captured_day(DAY, redact=True)) # the same, through the processor15for kind in SYNTHETIC:16 print(f"{kind} items before redaction: {fmt_int(before[kind])}")17 print(f"{kind} items after redaction: {fmt_int(after[kind])}")18SLOTS = [f"slot:{name}" for name in SLOT_LABELS]19for kind in SLOTS: # counted in the captured text: measured, not asserted zero20 print(f"{label(kind)}, items before redaction: {fmt_int(before[kind])}")21 print(f"{label(kind)}, residue after redaction: {fmt_int(after[kind])}")22assert all(after[kind] == 0 for kind in SYNTHETIC) # the synthetic users' items are all removed23assert all(after[kind] == before[kind] for kind in SLOTS) # values untouched2425# The incident day's rows as the receiver stores them: the assistant's spans and the contacts server's spans.26live = live_rows(INCIDENT)27cleaned = [redact_row(row) for row in live] # the receiver's redaction, over both processes' spans28OWN, SERVER = "ambrewick-assistant", "contacts-server"29print("stack traces on the assistant's spans, before redaction:", fmt_int(len(stack_traces(of_service(live, OWN)))))30print("stack traces on the contacts server's spans, before redaction:",31 fmt_int(len(stack_traces(of_service(live, SERVER)))))32print("stack traces on the assistant's spans, after redaction at the receiver:",33 fmt_int(len(stack_traces(of_service(cleaned, OWN)))))34print("stack traces on the contacts server's spans, after redaction at the receiver:",35 fmt_int(len(stack_traces(of_service(cleaned, SERVER)))))36assert not stack_traces(cleaned) # the receiver's redaction reaches both processes' spans37assert stack_traces(of_service(live, SERVER)) # the server's spans reach the receiver with their traces38assert absolute_paths(cleaned) == 0 and absolute_paths(live) > 0 # no path survives redaction; the raw rows hold paths
python scan-after-redaction.pyuser_id items before redaction: 200
user_id items after redaction: 0
user_name items before redaction: 2
user_name items after redaction: 0
email items before redaction: 0
email items after redaction: 0
person slot, items before redaction: 55
person slot, residue after redaction: 55
place_name slot, items before redaction: 44
place_name slot, residue after redaction: 44
relation slot, items before redaction: 26
relation slot, residue after redaction: 26
email_address slot, items before redaction: 0
email_address slot, residue after redaction: 0
personal_info slot, items before redaction: 0
personal_info slot, residue after redaction: 0
stack traces on the assistant's spans, before redaction: 4
stack traces on the contacts server's spans, before redaction: 3
stack traces on the assistant's spans, after redaction at the receiver: 0
stack traces on the contacts server's spans, after redaction at the receiver: 0
自第 2026.11.2 版起由 openai3.56.0至3.57.0 更新。
在接收端对已存储的行做脱敏
+10 项证明建立在 OTLP 的基础上,参见第5章,“The exporter sends each span over OTLP”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 27 行为空。请补全这一行,使接收端的脱敏对事件当天已存储的每一行都生效,涵盖两个进程的数据,并让结果成为名为 cleaned 的列表。该行的注释保持不变。
原理何在
脱敏移除了当天包含的所有合成项,并保留了看起来像个人信息的值,示例对这两点都做了断言。200 个用户 ID 和 2 个用户名降为零。邮箱类在脱敏前后都没有条目,原因见第一节。55 个人名值在脱敏后全部仍然存在:残留数为 55,其他槽位标签印在它旁边。
在事故当天,两个进程的堆栈跟踪都到达了接收端,接收端的脱敏会将其移除。助手的 span 含有 4 条堆栈跟踪,联系人服务器的 span 含有 3 条。服务器的 span 从其导出器直接到达接收端,不经过助手的处理器,因此该处理器看不到它们。在接收端脱敏之后,计数分别为 0 和 0。
接收端是两个进程的 span 都经过的位置。第 5 章把它们存储在那里,示例对已存储的行运行同样的脱敏。这就是定义中所说的第二个位置,即所有服务的 span 经过之处;第 5 章中的更换后端一节也指出,Collector 是规则能看到所有服务 span 的位置。在生产环境中,Collector 的脱敏处理器承担这项工作。它删除不在允许列表中的键,并屏蔽匹配阻止列表的值,其 README 称之为“一条防线,而不是唯一的合规措施”。本书中由接收端代表这个位置。
一个进程只能脱敏它自己写出的 span,因此某个服务中的脱敏器只保护该服务,不保护其他服务。脱敏在所有服务的 span 经过之处才能发挥作用,而每个进程中的脱敏器是其后的第二道防线。
工作准则: 在每个进程中运行脱敏,使其覆盖该进程写出的内容;再在所有服务的 span 经过之处运行一次,使其覆盖其他进程写出的内容。两次之后都要统计条目数。合成类条目的计数不为零即为失败,看起来像个人信息的值的计数不为零,则是脱敏器的覆盖范围所致。
带密钥的用户假名
用户 ID 是每条追踪都会保留的唯一标识符,因此脱敏时必须替换它,而不能直接丢弃。带密钥的假名,是用一个密钥对用户 ID 计算 HMAC-SHA256,并截取为十二位十六进制数字,用它来替换该用户 ID;同一用户无论出现在何处,得到的假名都相同。Data Governance as Code 中有它自己的带密钥假名,与这里的假名相关,但并不相同。那本书保留八位数字,对实体类型和经过大小写折叠的值计算哈希,所用密钥只有其语料库作业持有。本章的代码保留十二位数字,对原始用户 ID 计算哈希,所用的是写在代码中的演示密钥,因为这个案例只有一种标识符类型,而密钥在这里只是为了展示这种构造方式。
密钥之所以重要,是因为用户 ID 是连续的,任何人都可以写出全部候选值。对每个候选值计算普通的 SHA-256,就能直接与已存储的哈希匹配,真实 ID 的哈希起不到任何保护作用。密钥改变了这个问题:不持有密钥的读者可以对每个候选值计算哈希,却仍然匹配不到任何结果。
把每个候选 ID 与同一个已存储的哈希逐一比对,就能看出密钥的用途。
1"""The redacting processor, and the keyed pseudonym that replaces a user ID. Redaction is defence in depth: it removes2what the process can recognise from each span before the span is exported. The point rests on two printed results: the3processor's spans hold no synthetic name or address, and a keyed hash resists the enumeration that an unkeyed hash of4the same candidate IDs does not. The demonstration key is in the code, so the last enumeration succeeds, as it must."""5import lib # lib first: threads and seeds are fixed before anything else67import hashlib8import hmac910from opentelemetry.sdk.trace import TracerProvider11from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1213from lib.case import load_users14from lib.ids import SequentialIds15from lib.redact import USER_ID_ATTRIBUTE, RedactingProcessor, hash_user, pseudonym16from lib.report import fmt_int17from lib.scan import SYNTHETIC, captured_day, scan_rows1819DAY = "2026-12-08"20raw, redacted = captured_day(DAY), captured_day(DAY, redact=True) # the same calls, without and with the processor21before, after = scan_rows(raw), scan_rows(redacted)22for kind in SYNTHETIC:23 print(f"{kind} before the processor: {fmt_int(before[kind])}")24 print(f"{kind} after the processor: {fmt_int(after[kind])}")25assert all(after[kind] == 0 for kind in SYNTHETIC) # the processor removes every synthetic item the day's calls hold2627# A root span with a user ID goes through the same processor. The attribute the span exports is the pseudonym.28TARGET = load_users()[0].user_id # one of the case's synthetic users; not printed29exporter = InMemorySpanExporter()30provider = TracerProvider(id_generator=SequentialIds())31provider.add_span_processor(RedactingProcessor(exporter)) # the only path to the exporter32provider.get_tracer("ambrewick.assistant").start_span("invoke_agent ambrewick-assistant",33 attributes={USER_ID_ATTRIBUTE: TARGET}).end()34root = exporter.get_finished_spans()[0]35print("user ID on the root span, after the processor:", root.attributes[USER_ID_ATTRIBUTE])36assert root.attributes[USER_ID_ATTRIBUTE] == pseudonym(TARGET) and TARGET not in str(dict(root.attributes))3738# An attacker holds one stored hash of a user ID and tries every ID the format allows: U0000 to U9999.39CANDIDATES = [f"U{number:04d}" for number in range(10_000)]40stored_plain = hashlib.sha256(TARGET.encode("utf-8")).hexdigest() # an unkeyed SHA-256 of the ID41stored_keyed = hash_user(TARGET) # the keyed pseudonym, as the redactor makes it42print("candidate IDs tried:", fmt_int(len(CANDIDATES)))43found_plain = sum(hashlib.sha256(c.encode("utf-8")).hexdigest() == stored_plain for c in CANDIDATES)44print("unkeyed SHA-256 matches for the stored hash:", fmt_int(found_plain))45guess = b"a key the attacker does not hold"46found_guess = sum(hmac.new(guess, c.encode("utf-8"), hashlib.sha256).hexdigest() == stored_keyed for c in CANDIDATES)47print("keyed HMAC matches, with a key the attacker does not hold:", fmt_int(found_guess))48found_demo = sum(hash_user(c) == stored_keyed for c in CANDIDATES) # with DEMO_KEY, which is in lib/redact.py49print("keyed HMAC matches, with the demonstration key in the code:", fmt_int(found_demo))50assert (found_plain, found_guess, found_demo) == (1, 0, 1) # the key is the protection, and the code shows the one here
python redact-and-hash.pyuser_id before the processor: 0
user_id after the processor: 0
user_name before the processor: 2
user_name after the processor: 0
email before the processor: 0
email after the processor: 0
user ID on the root span, after the processor: user-fd52e7ae5e26
candidate IDs tried: 10,000
unkeyed SHA-256 matches for the stored hash: 1
keyed HMAC matches, with a key the attacker does not hold: 0
keyed HMAC matches, with the demonstration key in the code: 1
自第 2026.11.2 版起由 openai3.56.0至3.57.0 更新。
将无密钥计数与无密钥哈希进行比较
+10 项证明新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 43 行将每个候选项的无密钥哈希与第 41 行的带密钥假名进行比较,而不是与第 40 行中目标的无密钥哈希比较。请修正第 43 行,使无密钥计数与已存储的无密钥哈希进行比较。
原理何在
用带密钥的化名统计候选项
+10 项证明新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 48 行为空白。请补全这一行,统计候选 ID 的个数:对这些 ID 用与第 41 行生成已存储带密钥化名时相同的函数求出化名,结果等于该已存储值。
原理何在
带密钥的哈希能够抵御枚举,不带密钥的哈希则不能。针对同一个已存储的哈希,共尝试了 10,000 个候选 ID:不带密钥的 SHA-256 找到 1 个匹配,即目标本身;而使用攻击者不持有的密钥的 HMAC 找到 0 个。使用演示密钥的同一个带密钥 HMAC 找到 1 个匹配,该密钥就写在本书的代码中。
最后这个数字说明了为什么在实践中密钥必须保密。代码中的演示密钥并不是秘密,因为任何读到该文件的人都持有它。这次运行展示的是这种构造方式,并不能保护任何标识符。我们建议把真实密钥放在密钥存储服务中,与代码和遥测数据分开保管。
这正是假名比原始 ID 更适合放入 span 的原因,第 4 章曾承诺对此作出解释。不过,假名并不是匿名的。稳定的假名仍然会把同一用户的所有 span 关联起来,因此工程师可以找到来自同一用户的全部消息,而且与之相邻的内容仍可能识别出该用户。OpenTelemetry 关于处理敏感数据的指南指出,哈希未必能提供团队所需的匿名性。用户 ID 不会放入 baggage,假名同样不会放进去。在 span 中,假名对于没有密钥的读者不指向任何人;脱敏器还会对出现在消息文本中的用户 ID 应用同一个假名,因此关于同一用户的两个 span 在脱敏之后仍然可以匹配。
工作准则: 为每个假名使用一个遥测数据的读者永远不会持有的秘密密钥,并把密钥放在代码之外。更换密钥必须有计划,因为新密钥会让每个用户的假名重新开始,更换之前生成的追踪也就无法再与更换之后生成的追踪关联起来。
这部分尚未翻译,因此以英文显示。
Keep content by reference
Redaction removes what it knows how to find. Another route keeps the content out of the span altogether. An external content reference puts a pointer in the span, a *_ref attribute, and the content itself in a store with its own access rules.
The package has an upload hook, which the variable OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK names, with the value upload. The specification names the variable OTEL_INSTRUMENTATION_GENAI_CONTENT_HOOK, but the package reads only the completion-hook name, so that is the one to set. The hook writes each call's messages to files and puts references on the span, gen_ai.input.messages_ref and gen_ai.output.messages_ref, which are the registry's names. The hook also needs OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH set, and it imports fsspec, which this book pins at 2026.9.0. Chapter 3 set neither, so this is the first point in the book where the hook runs.
Sending the same twenty calls through the hook three ways sorts out where the content goes.
1"""The upload hook, which writes each call's messages to a store and puts a reference on the span. The same twenty calls2run three ways: capture unset with the span sampled in, capture on, and the span sampled out. The point rests on the3printed counts: with capture unset the span holds only references while the store holds the user's text, and with the4span sampled out nothing is exported and the store still fills. References are printed after the redactor has replaced5their folder. The store is a folder this example makes and removes."""6import lib # lib first: threads and seeds are fixed before anything else78import re9import tempfile10from pathlib import Path1112from opentelemetry.sdk.trace.sampling import ALWAYS_OFF, ALWAYS_ON1314from lib.dayrun import RECORDINGS15from lib.redact import has_absolute_path, redact_text16from lib.report import fmt_int17from lib.scan import CONTENT_KEYS, hooked_calls, model_calls, print_hook_run1819CALLS = model_calls(RECORDINGS["2026-12-08"])[:20] # twenty of baseline day 1's model calls20USER_TEXTS = [next(m["content"] for m in reversed(c["request"]["messages"]) if m["role"] == "user") for c in CALLS]21UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") # the uploaded files' random names2223with tempfile.TemporaryDirectory() as root:24 unset_spans, unset = hooked_calls(CALLS, ALWAYS_ON, None, Path(root) / "unset")25 print_hook_run("capture unset and sampled in", unset_spans, unset)26 on_spans, on = hooked_calls(CALLS, ALWAYS_ON, "SPAN_ONLY", Path(root) / "on")27 print_hook_run("capture on and sampled in", on_spans, on)28 out_spans, out = hooked_calls(CALLS, ALWAYS_OFF, None, Path(root) / "out")29 print_hook_run("capture unset and sampled out", out_spans, out)30 refs = [s.attributes[k] for s in unset_spans for k in s.attributes if k.endswith("_ref")]31 redacted = [redact_text(ref) for ref in refs] # the redactor replaces each reference's folder32 print("reference form on the span, after redaction:", UUID.sub("<id>", redacted[0]))33 print("absolute paths left in the redacted references:", fmt_int(sum(has_absolute_path(r) for r in redacted)))34 held = sum(any(text in body for body in unset["inputs"]) for text in USER_TEXTS)35 print("calls sent through the hook:", fmt_int(len(CALLS)))36 print("calls whose user text is in an uploaded input file, capture unset:", fmt_int(held))3738assert len(unset_spans) == len(CALLS) and len(on_spans) == len(CALLS) # every call's span is exported when sampled in39assert all(any(k.endswith("_ref") for k in s.attributes) for s in unset_spans) # the span holds a reference40assert not any(k in CONTENT_KEYS for s in unset_spans for k in s.attributes) # and no inline content, capture unset41assert all(any(k in CONTENT_KEYS for k in s.attributes) for s in on_spans) # capture on: the content is inline42assert len(out_spans) == 0 and len(out["inputs"]) == len(CALLS) and len(out["outputs"]) == len(CALLS) # sampled out43assert held == len(CALLS) # the store holds each call's user text, with capture unset44assert all(has_absolute_path(ref) for ref in refs) and not any(has_absolute_path(r) for r in redacted)
python content-by-reference.pyspans exported, capture unset and sampled in: 20
spans with a content reference, capture unset and sampled in: 20
spans with inline content, capture unset and sampled in: 0
uploaded inputs, capture unset and sampled in: 20
uploaded outputs, capture unset and sampled in: 20
spans exported, capture on and sampled in: 20
spans with a content reference, capture on and sampled in: 20
spans with inline content, capture on and sampled in: 20
uploaded inputs, capture on and sampled in: 20
uploaded outputs, capture on and sampled in: 20
spans exported, capture unset and sampled out: 0
spans with a content reference, capture unset and sampled out: 0
spans with inline content, capture unset and sampled out: 0
uploaded inputs, capture unset and sampled out: 20
uploaded outputs, capture unset and sampled out: 20
reference form on the span, after redaction: file://<folder>/<id>_inputs.json
absolute paths left in the redacted references: 0
calls sent through the hook: 20
calls whose user text is in an uploaded input file, capture unset: 20
自第 2026.11.2 版起由 openai3.56.0至3.57.0 更新。
在脱敏之后统计路径,而不是之前
+10 项证明来自Keep content by reference,第 12 章再读一遍
建立在 content capture 的基础上,参见第3章,“内容捕获开关”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 33 行统计的是原始引用中的绝对路径,此时脱敏器尚未运行。请修改它,让它改为统计脱敏后的引用中剩余的路径。
原理何在
With capture unset, the span holds a reference and no content, and the store holds the user's text: 20 input files, one for each call. Capture on adds the content inline to each of the 20 spans as well. Sampling the span out keeps it from the exporter altogether, and the hook still uploads each call's inputs and outputs: 20 inputs and 20 outputs, with no span exported.
The hook therefore writes for a span that the exporter never sends. Chapter 11 said that sampling decides which spans reach the backend, and not what the process does with the spans it drops. The third run shows that point in practice. Content goes to the store even when the trace it belongs to is sampled out.
The reference is a file:// address with the upload folder in it, which is an absolute path on the machine that wrote the file, so a reader who finds an unredacted reference learns where the file sits on that machine. The redactor replaces the folder with a placeholder and keeps the scheme and the file name. The example prints the reference after redaction, and the number of redacted references that still name a folder is 0.
The hook is not a privacy control. With capture unset, 20 of the 20 calls had their user text in an uploaded input file. Moving the content moved it. The redactor does not reach the files, so the store needs its own access rules and its own retention, and the same care as the spans the content came from.
Working rule: Do not turn on the upload hook as a way to keep content out of spans. Turn it on only with a store that has its own access and retention rules, and check the store as carefully as the spans, including the spans that sampling drops. Where spans pass, rewrite a reference's machine path, or use a store address that holds no machine path.
统计脱敏后的残留
扫描器统计三组类别,本章在每个表和每幅图中都将它们分开。第一组是合成用户的条目:用户 ID、用户名和电子邮件地址,脱敏必须将它们删除。第二组是堆栈跟踪,前面的一节已经讨论过。第三组是 MASSIVE 的槽位标签,即扫描器在捕获的文本中找到的人物、地点、关系及其他取值。第一组在脱敏后断言为零,第三组则只做测量。
这种划分取决于各组所允许的做法。脱敏器了解合成条目,因为它们来自该用例自己的列表和 .example 域名,所以脱敏器能够将其删除,示例也断言它确实做到了。这个零之所以有意义,是因为扫描器查找的是该用例自己的取值,而不是脱敏器所匹配的模式。脱敏器无法知道请求中的哪些词是人名,因为应用并没有数据集的标签。要对槽位标签断言为零,就需要这些标签。因此示例在脱敏前后分别统计它们,脱敏后的残留是 55 个人物取值。
有两个槽位标签需要再说明一下。本书随附的切片中,英文标注没有给 email_address 任何取值,所以它的模式什么也匹配不到,其零值来自这一切片本身。personal_info 有一个已标注的短语,而扫描器在当天捕获的文本中一个也没有找到。这个零是测量结果,所以它出现在残留中,而不是作为断言。
下一个示例用两个面板绘出包含各类条目的跨度,分别为脱敏前和脱敏后。
1"""How many spans of baseline day 1 hold each kind of personal item, before and after redaction, in two panels: the2synthetic users' items, which redaction removes, and MASSIVE's personal-looking values, which it cannot tell apart from3other words and so leaves. The figure's point rests on the printed counts: the top panel's bars drop to zero, and the4bottom panel's stay where they were."""5import lib # lib first: threads and seeds are fixed before anything else67from lib.figures import ACCENT, MUTED, RULE, new_figure, save8from lib.report import fmt_int9from lib.scan import SLOT_LABELS, SYNTHETIC, assistant_rows, captured_day, spans_holding1011DAY = "2026-12-08"12rows = assistant_rows(DAY) + captured_day(DAY) # the day's spans, capture on for the package's13cleaned = assistant_rows(DAY, redact=True) + captured_day(DAY, redact=True) # the same, through the processor14before, after = spans_holding(rows), spans_holding(cleaned)15for kind in SYNTHETIC + tuple(f"slot:{label}" for label in SLOT_LABELS):16 label = kind.replace("slot:", "") + (" slot" if kind.startswith("slot:") else "")17 print(f"{label} spans before redaction: {fmt_int(before[kind])}")18 print(f"{label} spans after redaction: {fmt_int(after[kind])}")19assert all(after[kind] == 0 for kind in SYNTHETIC) # the synthetic users' spans are all clean after redaction20assert all(after[f"slot:{label}"] == before[f"slot:{label}"] for label in SLOT_LABELS) # measured, not moved2122top_kinds = list(SYNTHETIC)23bottom_kinds = [f"slot:{label}" for label in SLOT_LABELS]24fig, (top, bottom) = new_figure(rows=2, height=5.6, sharex=False) # one x scale per panel: 200 and 55 do not share one252627def panel(ax, kinds, title):28 """Before and after, as horizontal bars, with each count printed at the bar's end."""29 ys = list(range(len(kinds)))30 xmax = max(before[kind] for kind in kinds) * 1.3 or 1 # room for the count and the legend31 ax.barh([y - 0.18 for y in ys], [before[kind] for kind in kinds], height=0.34, color=MUTED,32 label="before redaction")33 ax.barh([y + 0.18 for y in ys], [after[kind] for kind in kinds], height=0.34, color=RULE, edgecolor=ACCENT,34 hatch="////", label="after redaction") # hatched, so the two bars differ by pattern as well as colour35 for y, kind in zip(ys, kinds):36 ax.text(before[kind] + xmax * 0.01, y - 0.18, str(before[kind]), va="center", fontsize=7.5)37 ax.text(after[kind] + xmax * 0.01, y + 0.18, str(after[kind]), va="center", fontsize=7.5)38 ax.set_yticks(ys, [kind.replace("slot:", "") for kind in kinds])39 ax.invert_yaxis()40 ax.set_xlim(0, xmax)41 ax.set_title(title, loc="left", fontsize=9)424344panel(top, top_kinds, "Synthetic users' items: redaction removes them")45panel(bottom, bottom_kinds, "MASSIVE's personal-looking values: counted, not removed")46bottom.set_xlabel("spans holding each kind, baseline day 1")47top.legend(loc="lower right", fontsize=7.5)48save(fig, "personal-items-before-after")
python figure-personal-items-before-after.pyuser_id spans before redaction: 200
user_id spans after redaction: 0
user_name spans before redaction: 2
user_name spans after redaction: 0
email spans before redaction: 0
email spans after redaction: 0
person slot spans before redaction: 38
person slot spans after redaction: 38
place_name slot spans before redaction: 33
place_name slot spans after redaction: 33
relation slot spans before redaction: 25
relation slot spans after redaction: 25
email_address slot spans before redaction: 0
email_address slot spans after redaction: 0
personal_info slot spans before redaction: 0
personal_info slot spans after redaction: 0
figure: figures/personal-items-before-after.svg
自第 2026.11.2 版起由 openai3.56.0至3.57.0 更新。
图 12.1用两个面板绘出基线第 1 天中包含各类条目的跨度,分别为脱敏前和脱敏后。上方面板中的合成类别在脱敏后降为零。下方面板中看似个人信息的取值保持脱敏前的柱高:人物取值在脱敏前有 38 个跨度,脱敏后有 38 个。每个面板有各自的刻度,因此应在同一面板内比较柱,而不要跨两个面板比较。图统计的是跨度,扫描统计的是条目,所以下方面板的柱比扫描中同类别的计数要小,而且两者在脱敏前后都保持不变。在每一对柱中,第二根柱是脱敏后的计数。
脱敏后残留的 55 个人物取值,衡量的是脱敏器无法触及的请求文本有多少。这是对脱敏器触及范围的计数,不是对任何人记录的计数,读者不应将其视为后者。
**工作准则:**只对脱敏器被设计用来删除的类别断言为零,其他每个类别都作为测量值打印出来。脱敏器无法触及的计数是需要报告的事实,不会影响已通过的检查。
谁可以读取剩下的内容
经过脱敏的追踪记录仍然包含数据,谁可以读取这些数据,与脱敏器删除了什么同样重要。留下的行中,用户 ID 被替换为假名,还包括脱敏器未能找到的槽位值,以及某个服务写入、之后又没有任何步骤删除的堆栈跟踪。内容存储完整保存着用户的文本。因此,即使某个跨度中没有任何姓名,读取该跨度也属于读取个人数据。
我们建议按各个读取者的目的,只向其提供所需的行。处理告警的人员读取脱敏后的行,这些行带有假名、路由和耗时信息,他们不需要内容。调试某条指定路由的人员可以读取内容,但仅限于开启捕获时所声明的目的,并且仅在该目的持续期间有效。联系人团队读取其自有服务器的跨度,这些跨度归该团队所有。谁可以读取哪些行,由后端的访问控制来强制执行,而本书的接收器并不提供访问控制,因此只有当后端能够按角色限制内容属性或内容存储时,这些规则才能成立。我们建议选用能做到这一点的后端。
让个人数据不进入模型自身的上下文,是另一项工作。在《LLM 应用与智能体的安全》(Securing LLM Applications and Agents)中,隐藏上下文指系统提示词中对用户不可见的内容,例如密钥。本章讨论的是模型运行之后,遥测数据中保存了什么。
**工作准则:**在开启捕获之前,先写明谁可以读取原始内容、出于什么目的、直到何时为止。向其他所有读取者提供脱敏后的行,并对内容存储适用同样的规则。
在生产环境中防止私有数据外泄
本章的脱敏处理针对的是本书运行的这个案例,而生产环境在几个方面与之不同。脱敏器知道案例中的各个名称,并按区分大小写的方式匹配。它的地址规则匹配的是 .example 域名。真实的姓名或真实的地址会直接通过。脱敏器还不处理跨度(span)的名称、资源、链接和数组值。生产团队需要一个针对自己所持数据的检测器,例如针对个人数据训练的 PII 模型,并且应当用带标注的数据来衡量该检测器的漏检情况,而本书没有这样的数据。
堆栈跟踪规则只依据一个属性名,即 exception.stacktrace。以其他名称写入的回溯信息会通过,出现在消息文本中的路径也会通过。扫描器把堆栈跟踪单独计为一类,因此团队可以在每次发布后统计它们,并查看是否有新的服务开始写入堆栈跟踪。
原始跨度在接收端脱敏之前,还要经过网络传输。在这段时间里,传输层和接收端自身的日志都保存着原始内容,它们需要与路径上的其他环节得到同样的重视。只有路径上没有其他环节留存所接收的内容,进行脱敏的接收端才是安全的。
化名的私密程度取决于它的密钥。像本书这样把密钥写在代码中,任何读到代码的人都可以比对候选 ID,密钥泄露也会带来同样的结果。在生产环境中,应从密钥库中取 32 个随机字节作为密钥:RFC 2104 建议 HMAC 密钥不要短于哈希输出的长度。十二位十六进制数字适合本案例的 200 个用户,但庞大的用户群需要更多位数,因为在一千万用户的规模下,两个用户共用同一个化名已不再是不太可能的事。轮换密钥会使每个用户的化名重新生成,因此这一变更需要事先制定计划。
内容存储完整地保存用户的文本,其保留期限由它自己决定。第 11 章把这个期限留给了运行后端的团队,内容存储的期限同样归该团队负责。没有保留期限的存储,只要自身存在,就会一直保存这些文本。
工作准则: 每次发布之后,对一天的流量运行扫描,脱敏后计数仍高于零的任何类别,在有人能够说明其可以保留的原因之前,都视为一项发现。在同一次扫描中统计堆栈跟踪和各项条目,这样两者任何一个新来源都会出现在同一份报告里。
本章做出的决定
一个进程只能删除它自己写出的内容,因此下面的每项决定,都把检查放在所有进程的输出汇合之处。
- 我们在每个服务中都关闭内容捕获。关闭捕获后,每条消息的根 span 上仍然带有用户 ID,因此带密钥的假名属于默认做法,而不是额外措施。
- 我们在所有服务的 span 都会经过的位置丢弃堆栈跟踪,在本书中这个位置是接收端,我们也建议在生产环境的 Collector 中采取同样的步骤。联系人团队应当在其查找 span 上设置
record_exception=False,但我们并不依赖这一改动来保护数据。 - 我们在每个进程中对该进程所写的内容执行脱敏,并在所有服务的 span 都会经过的位置再执行一次,堆栈跟踪则显示了这一限制所付出的代价。
- 我们用遥测数据的读取者无法持有的密钥来生成用户假名。代码中的演示密钥只展示这种构造方式。
- 只有在具备独立的访问和保留规则时,我们才会把内容保存在存储中,因为只要上传钩子处于开启状态,它就会写入,包括被采样丢弃的 span。
- 对于脱敏会删除的各类合成数据,我们断言其数量为零,并打印数据集中各值的残留量,以此衡量脱敏器无法触及的部分。
- 我们对每个版本的输出都运行扫描,这样,堆栈跟踪或条目的任何新来源都会在一份报告中显现出来。
本章,在本版次中
版次 2026.11.2示例于 2026年11月23日 通过7 of 7个示例 in this chapter pass
译自英文版图书,版次 2026.11.2。