讓私人資料不進入遙測
閱讀約 64 分鐘,10 節 中共有 7 個範例。
Labs
透過實作學習本章
完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。約 30 秒內開啟。
完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。由 Labs 為你執行:每月 40 小時。
於您自己的電腦,免費: 下載本書的筆記本,連同其程式碼與資料,皆取自 GitHub。
在本書的版本上執行你的程式碼
讀完本章,你將能夠:預設讓個人資料不進入助理的遙測資料;為了明確的目的開啟內容擷取,並計算這樣做洩漏了多少;說明哪些洩漏可以用遮蔽(redaction)移除,哪些則無法處理。你還會執行掃描,計算剩餘的資料量,並看出哪些計數是由斷言保證為零,哪些只是量測的結果。
Ambrewick 的追蹤(trace)會被並非助理作者的人閱讀。值班工程師在警報後開啟追蹤,聯絡人團隊則開啟與自己的查詢相關聯的追蹤。這些追蹤所含的內容有一部分屬於個人資料。無論有沒有人要求擷取內容,每則訊息的根 span 都帶有使用者 ID;而追查某個錯誤路由的工程師,會想看到提示與回覆。擷取這些內容,會讓使用者的姓名出現在同一批 span 中,與 requests 所提到的人物、地點和關係並列。聯絡人伺服器還帶來一種任何擷取開關都控制不了的洩漏。本案例的問題在於:能解釋錯誤路由的追蹤,同時也是這段對話的副本。
使用者、工具與聯絡人都是合成的,requests 則取自 MASSIVE。使用者的姓名來自固定的清單,他們的地址位於 .example 網域,本案例本身沒有付款號碼或電話號碼。requests 保留了 MASSIVE 標註的人物、地點與關係的值。這些值是資料集的群眾外包工作者所寫的請求文字,本書照原樣保留,並以其欄位(slot)標示。掃描器會讀取每個 span 的值與其擷取的文字,為它所尋找的每一種類型計數,每個相符項目算一筆;本章報告的是遮蔽無法移除的計數。多數範例重播基準線第 1 天的資料;在聯絡人伺服器有影響的地方,則讀取第 9 章的事故日資料。
首先關閉內容擷取
第 3 章的內容擷取開關是本章的第一道防線,也是最優先的一道。開關未設定時,套件不會記錄任何提示詞或回覆,因此後續步驟沒有東西需要移除。本節之後的所有內容,都是針對有人開啟了這個開關的情況。若服務沒有為內容指定明確的用途,就應讓開關維持預設值,並且要讀取它所載入的每個套件的預設值,因為某個套件的預設值不等於另一個套件的預設值。
在四種模式下各執行一次模型呼叫,可以看出每種模式會把什麼寫入 span 與日誌。
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 版由 openai 3.56.0 至 3.57.0 更新。
在插入檢測程式碼之前設定擷取開關
+10 則證明建立於 automatic instrumentation,出自第 3 章「A call through the client」
新版次已改變本練習所涵蓋的內容。版次 2026.11.2 的變更內容
第 25 行是空白的。請寫出一個陳述式,將這次執行的模式放入開關中,讓套件在第 33 行進行檢測(instrument)時能讀取到它。
為何有效
開關未設定時,內容兩處都沒有:span 上有 0 個內容屬性,套件寫出 0 筆日誌記錄。span 模式會把提示詞與回覆放在 span 上,事件模式則寫入一筆日誌記錄,下一節會說明。這一組對照正是第一道防線的完整理由:內容不在遙測資料中,下游就無從洩漏。
關閉擷取並不表示完全沒有資料外流。無論設定哪一種模式,使用者的 ID 都會出現在每則訊息的根 span 上,而洩漏範例無論擷取設定為何,都會為每則訊息斷言一個這樣的 span。這個 ID 是使用者自己的識別碼,而追蹤需要某種識別碼才能回答一則訊息來自哪位使用者,所以無法省略。它必須在儲存之前被取代,金鑰式使用者假名說明了做法。
在基準第 1 天的任何 span 中,無論擷取開啟或關閉,都沒有出現電子郵件地址。助理的政策要求模型絕不在回覆中重複聯絡人的地址,而且沒有任何工具 span 帶有其引數,因此地址沒有進入 span 的途徑。掃描器在遮蔽之前與之後都找不到任何地址。電子郵件這一類別的數值為零,是因為設計上沒有讓地址進入的途徑,而掃描器會依原樣尋找所有案例中的地址,並確認了這一點。
姓名的情況不同。擷取關閉時,洩漏範例斷言沒有任何使用者姓名與訊息文字進入 span。姓名只在擷取開啟時才會出現,下一節會對此進行量測。
實用原則: 在每個服務中都保持內容擷取關閉,並在部署前讀取每個已載入套件的預設值。只有在有明確可說明的用途時才開啟擷取,而且只在每個 span 於後端保存之前都會經過遮蔽器處理的地方開啟。
此部分尚未翻譯,因此以英文呈現。
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 版由 openai 3.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 版由 openai 3.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.
遮蔽是縱深防禦
遮蔽(redaction)是在 span 儲存之前,將其屬性或事件中的個人值換成佔位符:可以在產生該 span 的行程中進行,也可以在所有服務的 span 都會經過的位置進行。助理的行程使用 span 處理器來做這件事,其定義見第 1 章。這個處理器會在 span 結束時匯出一份經過遮蔽的副本。它必須複製,因為 SDK 會在 span 結束時凍結其屬性,之後就無法就地修改。Data Governance as Code 的 redact是對查詢欄位做的 NULL 轉型,與這裡的操作不同,因為這裡的遮蔽針對的是遙測資料。
處理器移除的內容很明確。合成使用者的姓名與電子郵件地址會變成佔位符 [name] 與 [email]。使用者 ID 會變成其假名,假名的定義見下一節。堆疊追蹤會被直接丟棄而不是替換,因為其中的路徑會指出執行該程式碼之行程的資料夾名稱。file:// 參照會保留其配置(scheme)與檔名,資料夾則換成佔位符。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 版由 openai 3.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 是連續的,任何人都能列出所有候選 ID。對每個候選 ID 計算單純的 SHA-256,就能直接比對出已儲存的雜湊值,真實 ID 的雜湊也就起不了任何保護作用。金鑰改變了問題的性質:沒有金鑰的讀者即使對每個候選 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 版由 openai 3.56.0 至 3.57.0 更新。
將未加金鑰的計數與未加金鑰的雜湊值比對
+10 則證明新版次已改變本練習所涵蓋的內容。版次 2026.11.2 的變更內容
第 43 行將每個候選值的未加金鑰雜湊值,拿去和第 41 行的加金鑰假名比對,而不是和第 40 行目標的未加金鑰雜湊值比對。請修正第 43 行,讓未加金鑰的計數與儲存的未加金鑰雜湊值比對。
為何有效
以金鑰化假名計算候選者數量
+10 則證明新版次已改變本練習所涵蓋的內容。版次 2026.11.2 的變更內容
第 48 行是空白的。請撰寫這一行,讓它計算符合下列條件的候選者 ID 數量:以產生第 41 行所儲存之金鑰化假名的同一個函式,為候選者產生假名,其結果等於該儲存值。
為何有效
具金鑰的雜湊能抵擋窮舉攻擊,無金鑰的雜湊則不能。在對同一個已儲存雜湊值嘗試的 10,000 個候選 ID 中,無金鑰的 SHA-256 找到 1 筆相符,也就是目標本身;而攻擊者不持有金鑰時,具金鑰的 HMAC 找到 0 筆。同樣的具金鑰 HMAC 若使用本書程式碼中公開寫出的示範金鑰,則找到 1 筆相符。
最後這個數字說明了為何在實務上金鑰必須保密。程式碼中的示範金鑰並不是祕密,因為任何讀到該檔案的人都持有它。這次執行展示的是建構方式,並不能保護任何識別碼。我們建議以祕密儲存庫保管真正的金鑰,並使其遠離程式碼與遙測資料。
這就是為什麼在 span 中放入假名比放入原始 ID 更安全,也就是第 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 版由 openai 3.56.0 至 3.57.0 更新。
在遮蔽之後計算路徑,而不是在之前
+10 則證明來自 Keep content by reference,第 12 章再讀一次
建立於 content capture,出自第 3 章「內容擷取開關」
新版次已改變本練習所涵蓋的內容。版次 2026.11.2 的變更內容
第 33 行計算的是原始參照中的絕對路徑,也就是在遮蔽器(redactor)執行之前的結果。請將它改為計算遮蔽後的參照中所剩下的路徑。
為何有效
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 版由 openai 3.56.0 至 3.57.0 更新。
圖 12.1以兩個面板,繪出基準第 1 天中各類項目所在的跨度,分別為遮蔽前與遮蔽後。上方面板的合成類別在遮蔽後降為零。下方面板中看似個人資料的值,則保有遮蔽前的長條:人名值在遮蔽前有 38 個跨度,遮蔽後有 38 個。每個面板各有自己的刻度,因此應在同一面板內比較長條,而不要跨兩個面板比較。圖計算的是跨度,掃描計算的是項目,所以下方面板的長條比掃描對同類別的計數小,而兩者在遮蔽前後都維持不變。在每一對長條中,第二根長條是遮蔽後的計數。
遮蔽後殘留的 55 個人名值,衡量的是遮蔽器無法觸及的請求文字有多少。這是遮蔽器觸及範圍的計數,不是任何人的紀錄的計數,讀者不應將它當成後者。
實用原則: 只對遮蔽器設計用來移除的類別斷言為零,其餘每一類都以量測值印出。遮蔽器無法觸及的計數是應當回報的事實,並不會抵銷已通過的檢查。
誰可以讀取剩下的資料
經過遮蔽處理的追蹤紀錄(trace)仍然含有資料,誰可以讀取這些資料,與遮蔽工具移除了什麼同樣重要。留下的資料列以假名取代使用者 ID,其中還有遮蔽工具未能找到的槽位值,以及服務寫入、後續步驟又未移除的堆疊追蹤。內容儲存區則完整保存使用者的文字。因此,即使某個 span 不含任何姓名,讀取它仍屬於讀取個人資料。
我們建議依各讀取者的目的,只提供其所需的資料列。處理警示的人員讀取經遮蔽的資料列,其中包含假名、路由與時間資訊,他們不需要內容。除錯特定路由的人員,可以基於開啟擷取時所載明的目的讀取內容,且僅限於該目的持續的期間。聯絡人團隊讀取自己所擁有之伺服器的 span。誰可以讀取哪些資料列,是由後端的存取控制來強制執行的,而本書的接收器(receiver)並沒有這項功能,因此只有在後端能依角色限制內容屬性或內容儲存區時,這些規則才會成立。我們建議採用能做到這一點的後端。
避免個人資料進入模型自身的情境(context),則是另一項工作。在《Securing LLM Applications and Agents》中,隱藏情境指系統提示詞(system prompt)不讓使用者看見的內容,例如機密。本章討論的是模型執行之後,遙測資料中所保存的內容。
實用原則: 在開啟擷取之前,先寫下誰可以讀取原始內容、基於什麼目的,以及到何時為止。其他所有讀取者一律提供經遮蔽的資料列,並將同一項規則套用於內容儲存區。
在正式環境中防止私人資料外洩
本章的遮蔽處理是針對本書所執行的案例而設計,正式環境在好幾個方面有所不同。遮蔽器知道案例中的名稱,並以區分大小寫的方式比對。它的位址規則比對的是 .example 網域。真實的姓名或真實的位址會直接通過。遮蔽器也不處理 span 的名稱、資源、連結與陣列值。正式環境的團隊需要一個適用於其所持有資料的偵測器,例如針對個人資料訓練的 PII 模型,並且應以標註過的資料來衡量該偵測器的漏檢情形,而本書並沒有這類資料。
堆疊追蹤規則只依據一個屬性名稱 exception.stacktrace。以其他名稱寫入的 traceback 會通過,出現在訊息文字中的路徑也會通過。掃描器把堆疊追蹤視為獨立的一類,因此團隊可以在每次發布後計算其數量,並觀察是否有新的服務開始寫入堆疊追蹤。
原始 span 在接收器進行遮蔽之前,也會先經過網路傳輸。傳輸層與接收器自身的日誌在這段時間內保有原始內容,因此需要與路徑上的其他部分受到同樣的審慎對待。只有在路徑上沒有任何其他環節保存其所接收的內容時,會進行遮蔽的接收器才是安全的。
假名的私密程度取決於其金鑰。如本書所做的,把金鑰放在程式碼中,會讓任何讀到程式碼的人都能比對候選的 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。