テレメトリに個人データを残さない
読了まで約51 分。10 節に7 例を収録。
Labs
この章を実際に手を動かして学ぶ
すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。約 30 秒で開く。
すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。Labs が実行環境を用意する: 月40 時間。
自分のマシンで、無料: 書籍のノートブックをダウンロード、そのコードとデータを GitHub から取得する。
書籍のバージョンでコードを実行する
この章を読み終えると、アシスタントのテレメトリに個人データを既定で残さないようにできる。目的を明示したうえでコンテンツの取得を有効にし、それによる漏えいを数えることもできる。さらに、リダクションで除去できる漏えいと、手が届かない漏えいを区別して説明できる。残ったものを数えるスキャンも実行する。その中で、どの件数が断言によってゼロであり、どの件数が測定されただけの値であるかも確認する。
Ambrewick のトレースは、アシスタントを書いていない人々が読む。オンコールのエンジニアはアラートの後にトレースを開き、連絡先チームは自チームの検索が結合したトレースを開く。それらのトレースが保持する内容の一部は個人に関わるものである。すべてのメッセージのルートスパンには、誰もコンテンツを求めていなくてもユーザー ID が付く。また、誤ったルートを追跡するエンジニアは、プロンプトと応答を見たがるだろう。それらを取得すると、リクエストが言及する人物、場所、関係の隣に、ユーザーの名前が同じスパンの中に入ってしまう。連絡先サーバーは、どの取得スイッチでも制御できない漏えいを加える。このケースでの問題は、誤ったルートを説明するトレースが、会話のコピーでもあるという点にある。
ユーザー、ツール、連絡先は合成されたものであり、requests は MASSIVE のものである。ユーザーの名前は固定のリストから取られ、そのアドレスは .example ドメインにあり、このケース自体には支払い番号も電話番号もない。リクエストには、MASSIVE が注釈する人物、場所、関係の値がそのまま残っている。これらの値はデータセットのクラウドワーカーが書いたリクエスト文であり、本書は書かれたままにして、スロットで分類している。スキャナーは各スパンの値と取得されたテキストを読み、探す種類ごとに、一致 1 件につき 1 項目として数える。この章では、リダクションで除去できない件数を報告する。例の大半はベースライン 1 日目を再生する。連絡先サーバーが関わる箇所では、第 9 章の障害発生日を読み込む。
最初にキャプチャを無効にする
3章で扱ったコンテンツキャプチャのスイッチは、この章における第一の防御であり、最初に行うべきものである。スイッチを未設定にしておけば、パッケージはプロンプトも返信も記録しないので、後の段階で取り除くべきものが存在しない。この節より後の内容は、誰かがスイッチを有効にした場合のためのものである。コンテンツの用途を明示していないサービスは、スイッチを既定値のままにしておく。また、読み込む各パッケージの既定値を個別に確認する。あるパッケージの既定値が別のパッケージの既定値と同じとは限らないからである。
4つのモードのそれぞれで1回ずつモデルを呼び出すと、各モードがスパンとログに何を書き込むかが分かる。
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 件の検証最初にキャプチャを無効にする、12章よりもう一度読む
automatic instrumentationを基にする。3章「A call through the client」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
25行目は空行である。この実行のモードをスイッチに設定する文を書け。そうすれば、33行目でパッケージがインストルメンテーションされるときに、パッケージがそのモードを参照できる。
仕組み
スイッチが未設定であれば、コンテンツはどちらにも存在しない。スパンのコンテンツ属性は0件であり、パッケージが書き込むログレコードは0件である。スパンモードではプロンプトと返信がスパンに載り、イベントモードではログレコードが書き込まれる。これについては次の節で述べる。この対比が第一の防御の根拠のすべてである。コンテンツがテレメトリに含まれないので、下流で漏えいすることはない。
キャプチャを無効にしても、何も外部に出ないわけではない。ユーザーIDは、どのモードを設定していても各メッセージのルートスパンに載る。漏えいの例は、キャプチャの設定にかかわらず、メッセージごとにそのようなスパンが1つあることを検証している。このIDはユーザー自身の識別子である。トレースには、メッセージがどのユーザーから来たのかに答えるための識別子が必要なので、省くことはできない。そのため、保存する前に置き換える必要があり、その方法は鍵付きユーザー仮名に示している。
ベースライン1日目のどのスパンにも、キャプチャが有効か無効かにかかわらず、メールアドレスは現れない。アシスタントのポリシーは、連絡先のアドレスを返信で繰り返さないようモデルに指示しており、どのツールスパンも引数を保持しないので、アドレスがスパンに入る経路はない。スキャナは、リダクションの前でも後でもアドレスを検出しない。メールの種別が0になるのは、設計上アドレスに経路が与えられていないからであり、各ケースのアドレスを記載どおりに探すスキャナがそれを裏付けている。
名前の場合は挙動が異なる。キャプチャを無効にしている場合、漏えいの例は、ユーザー名もメッセージ本文もスパンに到達しないことを検証している。名前が現れるのはキャプチャが有効な場合に限られ、これは次の節で測定する。
実践ルール: コンテンツキャプチャはすべてのサービスで無効にしておき、デプロイの前に、読み込む各パッケージの既定値を確認する。キャプチャを有効にするのは、具体的に説明できる目的がある場合に限り、かつ、バックエンドが保持する前にすべてのスパンに対してリダクタが動作している場合に限る。
この部分はまだ翻訳されていないため、英語で表示している。
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.
キャプチャがなくてもスタックトレースは漏れる
連絡先サーバーは別プロセスであり、そのスパンは、アシスタントのコードが制御できない経路でレシーバーに届く。第4章でこのサーバーを紹介し、第5章では、エンドポイントを与えられたサーバーが自身のスパンを OTLP で送出することを示した。サーバーは contacts.lookup スパンを start_as_current_span で開き、例外については何も設定しない。そのため、ツールが例外を送出すると、API の既定である 1.45.2 の record_exception=True によって、そのスパンに exception イベントが書き込まれる。このイベントは、トレースバックである exception.stacktrace を持つことがある。トレースバックは各ファイルをパスで示し、そのパスは、コードを実行したプロセスのフォルダー名を示す。
漏えいの例が障害当日のデータを読んだとき、キャプチャはオフであったが、スタックトレースはそれでも存在していた。その日、レシーバーは連絡先サーバーのスパンを 22 件保存していた。そのうち contacts.lookup スパンの 3 件がエラーであり、エラースパンはいずれもスタックトレースを持っていて、合計は 3 件であった。これらのトレースが示すファイルパスは 9 件である。最初のトレースの最も内側のフレームは find_contact であり、サーバー自身のファイル contacts_server.py にあって、フォルダー部分はプレースホルダーになっている。出力が示すのはパスの形だけで、パスそのものは示さない。完全なパスこそ、この節が扱う対象だからである。以下の修正で削除するのは exception.stacktrace だけである。第8章で決めたとおり、クラスとメッセージを持つ例外イベントは残す。
アシスタント自身のスパンにもスタックトレースがあり、障害当日には 4 件であった。これらは MCP SDK のクライアントディスパッチャーがクライアントスパンに書き込むもので、ツール試行のスパンが持つのは例外のクラスとメッセージだけである。したがって、トレースバックは両方のプロセスから外へ出ており、漏えいはアシスタントが何を記録するかに左右されない。第11章のテイルサンプリングは、エラーを含むトレースを保持するが、スキャンは、保持されたか破棄されたかを問わず、スタックトレースを持つ 5 件のトレースをすべて読む。
スタックトレースはユーザーを特定しないが、そのパスはプロセスを実行したアカウントを示すことがあり、これは個人データにあたる。また、パスはマシンの情報も明らかにする。スキャナーは、スタックトレースを個人情報の項目とは別の独立した種類として数える。トレースバックを残す価値があるのかと問う読者もいるだろう。トレースを開くエンジニアに必要なのは、例外のクラスとメッセージ、そして失敗したツールの名前であり、スパンはそのどちらも保持している。フォルダー名は、修正に必要な情報を何も加えない。
これはキャプチャでは止められない漏えいであり、アシスタントのリダクターはその半分、つまりサーバー側には手が届かない。リダクションの節では、アシスタントのリダクターが実行された後に何が残るかを数え、リダクターがこれらのトレースに届く箇所を示す。
実践ルール: スタックトレースはすべてのサービスで機密として扱い、どのバックエンドにも残さない。すべてのサービスのスパンが通過する場所で取り除く。発生源では、サーバーを所有するチームに依頼し、スパンに record_exception=False を設定させ、例外のクラスとメッセージを手動で設定させる。クライアント側のスタックトレースは下流でしか取り除けないからである。
墨消しは多層防御である
墨消し(redaction)とは、スパンを保存する前に、その属性やイベントに含まれる個人の値をプレースホルダに置き換える処理である。置き換えは、スパンを生成したプロセス内で行うか、すべてのサービスのスパンが通過する場所で行う。アシスタントのプロセスでは、第1章で定義したスパンプロセッサがこれを行う。このプロセッサは、スパンが終了する時点で、墨消し済みのコピーをエクスポートする。コピーが必要なのは、SDK がスパンの終了時に属性を凍結し、その後は直接書き換えられないためである。Data Governance as Code の redactはクエリの列に対する NULL へのキャストであり、本章の墨消しとは別の操作である。本章の墨消しはテレメトリを対象とする。
プロセッサが除去する対象は具体的に決まっている。合成ユーザーの名前とアドレスは、プレースホルダ [name] と [email] になる。ユーザー ID は仮名に置き換わる。仮名は次の節で定義する。スタックトレースは置き換えずに削除する。そのパスに、コードを実行したプロセスのフォルダ名が含まれるためである。file:// 参照は、スキームとファイル名を残し、フォルダをプレースホルダにする。スパンのステータス記述も墨消しされる。例外のメッセージを含むことがあるためである。個人情報らしく見える値は、そのまま通過する。プロセッサは自由文中の名前を他の単語と区別できず、このケースには両者を見分けるラベルもないからである。
次の例では、プロセッサをその日のスパンに適用して残ったものを数え、続いてインシデント当日の保存済み行に受信側の墨消しを適用する。
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 件の検証墨消しは多層防御である、12章よりもう一度読む
OTLPを基にする。5章「The exporter sends each span over OTLP」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
27行目は空白である。レシーバーの墨消し処理が、事件当日に保存されたすべての行に対して、両方のプロセスの分を対象として実行され、その結果が cleaned という名前のリストになるように、この行を書け。この行のコメントはそのまま残す。
仕組み
墨消しは、その日に含まれる合成項目をすべて除去し、個人情報らしく見える値はそのまま残す。例はこの両方を表明(assert)で確かめている。ユーザー ID 200 件とユーザー名 2 件は 0 になる。メールの種類には、最初の節で述べた理由により、墨消しの前にも後にも項目がない。人物の値 55 件は、墨消し後もすべて残っている。残余は 55 であり、他のスロットのラベルも並べて表示している。
インシデント当日には、スタックトレースが両方のプロセスから受信側に届き、受信側の墨消しがそれを除去する。アシスタントのスパンには 4 件、連絡先サーバーのスパンには 3 件のスタックトレースがある。サーバーのスパンは、エクスポータから受信側へ、アシスタントのプロセッサを通らずに届くため、そのプロセッサには見えない。受信側での墨消し後の件数は、0 と 0 である。
受信側は、両方のプロセスのスパンが通過する場所である。第5章でスパンをそこに保存しており、例では保存済みの行に同じ墨消しを適用している。これは定義が挙げる二つ目の場所、すなわちすべてのサービスのスパンが通過する場所にあたる。また、第5章のバックエンドの変更では、ルールがすべてのサービスのスパンを見渡せる場所として Collector を挙げた。実運用では、Collector の redaction プロセッサがこの役割を担う。許可リストにないキーを削除し、ブロックリストに一致する値をマスクする。その README はこれを「one line of defence rather than the only compliance measure in place」と呼んでいる。本書では、受信側がその場所の代わりを務める。
プロセスが墨消しできるのは、自分が書き出すスパンだけである。そのため、あるサービスの墨消し器が守るのはそのサービスだけである。墨消しが有効に働くのは、すべてのサービスのスパンが通過する場所であり、各プロセスの墨消し器はその背後の第二の防衛線となる。
実践ルール: 墨消しはすべてのプロセスで実行し、そのプロセスが書き出す内容を対象にする。さらに、すべてのサービスのスパンが通過する場所でも再度実行し、他のプロセスが書き出す内容を対象にする。両方の後で項目を数える。合成の種類で 0 でない件数が出れば失敗である。個人情報らしく見える値で 0 でない件数が出れば、それは墨消し器の及ぶ範囲を示している。
鍵付きユーザー仮名
ユーザー ID はすべてのトレースが保持する唯一の識別子であるため、リダクションではこれを削除せずに置き換えなければならない。鍵付き仮名は、ユーザー ID を、ある鍵のもとでの HMAC-SHA256 に置き換え、16 進数 12 桁に切り詰めたものである。同じユーザーであれば、どこに現れても同じ値になる。Data Governance as Codeにも独自の鍵付き仮名があるが、これは本書のものと関連はあっても同一ではない。同書は 8 桁を保持し、エンティティ型と大文字小文字を統一した値を、コーパスのジョブだけが持つ鍵のもとでハッシュする。本章のコードは 12 桁を保持し、コード内にあるデモ用の鍵のもとで生のユーザー ID をハッシュする。このケースでは識別子の型が 1 種類しかなく、鍵は仕組みを示すために置いてあるからである。
鍵が重要なのは、ユーザー ID が連番であり、誰でもすべての候補を書き出せるためである。各候補の単純な SHA-256 は保存されたハッシュと直接一致するので、実在する ID のハッシュは何も守らない。鍵は問いの性質を変える。鍵を持たない読み手は、すべての候補をハッシュしても、何にも一致させられない。
1 つの保存済みハッシュに対してすべての候補 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行目は、各候補の鍵なしハッシュを、40行目で得た対象の鍵なしハッシュではなく、41行目の鍵付き仮名と比較している。鍵なしの件数が、保存された鍵なしハッシュと比較されるように43行目を修正せよ。
仕組み
鍵付き仮名で候補を数える
+10 件の検証この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
48行目は空白である。41行目に保存された鍵付き仮名を作った関数と同じ関数で候補IDの仮名を作り、それが保存された値と等しくなる候補IDの数を数えるように、この行を書け。
仕組み
鍵付きハッシュは、鍵なしのハッシュでは耐えられない列挙に耐える。1 つの保存済みハッシュに対して試した 10,000 個の候補 ID のうち、鍵なしの SHA-256 は標的である 1 件の一致を見つける。一方、攻撃者が持たない鍵を使った鍵付き HMAC では 0 件である。同じ鍵付き HMAC でも、本書のコードに書かれているデモ用の鍵を使えば、1 件の一致を見つける。
最後の件数が、実運用で鍵を秘密にしなければならない理由である。コード内のデモ用の鍵は、ファイルを読めば誰でも手にできるので秘密ではない。この実行は仕組みを示すものであり、識別子を守るものではない。実際の鍵には、コードやテレメトリから離したシークレットストアを使うことを推奨する。
これが、スパンに入れる値として生の ID よりも仮名のほうが安全である理由であり、第 4 章で説明を約束した点である。ただし、仮名は匿名ではない。安定した仮名は 1 人のユーザーのすべてのスパンを結び付けるため、エンジニアは同じユーザーのすべてのメッセージを探し出せる。また、その横にある内容からユーザーが特定される場合もある。機微なデータの扱いに関する OpenTelemetry のガイダンスは、ハッシュ化ではチームが必要とする匿名性が得られない場合があると述べている。ユーザー ID はバゲージに入れず、仮名もバゲージには入れない。スパンの中では、仮名は鍵を持たない読み手には誰のものか分からない。また、リダクタはメッセージ本文に現れるユーザー ID にも同じ仮名を適用するので、1 人のユーザーに関する 2 つのスパンは、リダクションの後でも一致する。
実践ルール: すべての仮名には、テレメトリの読み手が決して持たない秘密の鍵を使い、その鍵をコードの外に置くこと。鍵の変更は計画を立てた場合にのみ行うこと。新しい鍵ではすべてのユーザーの仮名が新しくなり、変更前に作られたトレースと変更後に作られたトレースが結合できなくなるからである。
この部分はまだ翻訳されていないため、英語で表示している。
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行目は、リダクタが実行される前の、生の参照に含まれる絶対パスを数えている。これを、リダクタによる処理後の参照に残っているパスを数えるように変更せよ。
仕組み
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 件の人物の値は、リクエストテキストのうち赤字処理器が届かない部分の大きさを示す。これは赤字処理器が及ぶ範囲の数であり、誰かの記録の数ではない。読者はそのように受け取ってはならない。
実践ルール: ゼロを表明するのは、赤字処理器が取り除くように作られた種類に限り、それ以外の種類はすべて測定値として出力する。赤字処理器が届かない数は報告すべき事実であり、合格した検査の結果を損なうものではない。
残されたデータを誰が読めるか
秘匿化したトレースにもデータは残っており、誰がそれを読めるかは、秘匿化処理が何を取り除いたかと同じくらい重要である。残った行には、ユーザー ID の代わりの仮名、秘匿化処理が見つけられなかったスロット値、サービスが書き出したまま後続のどの処理でも取り除かれなかったスタックトレースが含まれる。コンテンツストアはユーザーのテキストをそのまま保持している。したがって、スパンを読むことは、そのスパンに名前が含まれていなくても、個人データを読むことの一種である。
各読み手には、その目的に必要な行だけを与えることを推奨する。アラートに対応する担当者は、仮名、ルート、タイミングを含む秘匿化済みの行を読む。内容は必要としない。名前の付いたルートをデバッグする担当者は、キャプチャを有効にしたときに示した目的のために、その目的が続く間に限り、内容を読んでよい。連絡先チームは、自らが所有するサーバーのスパンを読む。どの行を誰が読むかはバックエンドのアクセス制御によって強制される。本書のレシーバーにはその機能がないため、これらのルールが成り立つのは、バックエンドがコンテンツ属性やコンテンツストアをロールごとに制限できる場合に限られる。それができるバックエンドを推奨する。
個人データをモデル自身のコンテキストに入れないことは、別の課題である。Securing LLM Applications and Agents では、隠れたコンテキストとは、シークレットなどのように、システムプロンプトがユーザーの目から隠して保持するものを指す。本章が扱うのは、モデルの実行後にテレメトリが保持しているものである。
実践ルール: キャプチャを有効にする前に、生の内容を誰が、どの目的で、いつまで読めるかを書き留める。それ以外のすべての読み手には秘匿化済みの行を与え、同じルールをコンテンツストアにも適用する。
本番で個人データを外に出さないために
本章のリダクションは、本書が扱う事例を対象に動作するものであり、本番環境とはいくつかの点で異なる。このリダクタは事例に登場する名前を知っており、大文字と小文字を区別して照合する。アドレスのルールが照合するのは .example ドメインである。実在の名前や実在のアドレスは、そのまま通過する。また、リダクタはスパンの名前、リソース、リンク、配列の値には手を加えない。本番のチームには、自分たちが保持するデータに合った検出器が必要である。たとえば、個人データ向けに訓練された PII モデル がそれにあたる。さらに、その検出器の見逃しを、ラベル付きデータに照らして測定すべきである。本書にはそのようなデータはない。
スタックトレースのルールは、exception.stacktrace という一つの属性名だけを手がかりにしている。別の名前で書かれたトレースバックは通過し、メッセージ本文に現れるパスも同様に通過する。スキャナはスタックトレースを独立した種類として数えるので、チームはリリースのたびにその数を調べ、新しいサービスがスタックトレースを書き始めたかどうかを確認できる。
生のスパンは、レシーバがリダクションを行う前にネットワークも通過する。その間、トランスポートとレシーバ自身のログには生の内容が残るため、経路の他の部分と同じ注意が必要である。リダクションを行うレシーバが安全であるのは、経路上の他の何も受け取った内容を保持していない場合に限られる。
仮名の秘匿性は、その鍵の秘匿性を超えない。本書のようにコードの中に鍵を置くと、コードを読んだ者は誰でも候補の ID を照合できてしまう。鍵が漏えいした場合も同じ結果になる。本番では、シークレットストアから 32 バイトの乱数として鍵を生成する。RFC 2104 は、ハッシュの出力より短い HMAC 鍵を使わないよう勧めている。16 進数 12 桁は事例の 200 人のユーザーには足りるが、ユーザー数が多い場合はより多くの桁が必要になる。ユーザーが一千万人になると、仮名が重複する可能性はもはや低くないからである。鍵をローテーションすると、すべてのユーザーの仮名が新しくなるため、この変更には計画が必要である。
コンテンツストアはユーザーのテキストを完全な形で保持し、その保持期間はストア固有のものである。第11章 は期間の決定をバックエンドを運用するチームに任せたが、ストアの期間もそのチームが決めるものである。期間の定めがないストアは、存在する限りテキストを保持し続ける。
実践ルール: リリースのたびに、1 日分のトラフィックに対してスキャンを実行し、リダクション後もカウントがゼロを超える種類は、残ってよい理由を誰かが説明できるまで、検出事項として扱う。スタックトレースとその他の項目は同じスキャンで数え、どちらの新たな発生源も一つのレポートに現れるようにする。
本章で下した判断
プロセスが除去できるのは、自らが書き出すものだけである。そのため、以下の各判断では、すべてのプロセスの出力が行き着く場所に検査を置く。
- すべてのサービスで内容の取得を無効にする。取得を無効にしても、各メッセージのルートスパンにはユーザー ID が残る。したがって、鍵付きの仮名はあとから加える措置ではなく、既定の構成の一部である。
- スタックトレースは、すべてのサービスのスパンが通る場所で削除する。本書ではそれはレシーバーである。本番の Collector でも同じ手順を勧める。連絡先チームは、検索スパンに
record_exception=Falseを設定するのがよい。ただし、データの保護をこの変更に依存することはしない。 - 墨消し(リダクション)は、各プロセスがそのプロセス自身の書き出すものに対して実行し、さらにすべてのサービスのスパンが通る場所でもう一度実行する。この限界にどれだけの代償が伴うかは、スタックトレースが示している。
- ユーザーの仮名には、テレメトリの読み手が決して持たない秘密で鍵を付ける。コード中のデモ用の鍵が示すのは、構成方法だけである。
- 内容を保存先に残すのは、その保存先に固有のアクセス規則と保持規則がある場合に限る。アップロードフックは、有効であればサンプリングで破棄されるスパンについても書き込むからである。
- リダクションが除去する合成種別については、ゼロであることを検証する。また、データセットの値の残余を出力し、リダクションが及ばない範囲の尺度とする。
- スキャンはすべてのリリースの出力に対して実行する。これにより、スタックトレースや項目の新たな発生源が、一つのレポートに現れる。
この版における本章
第2026.11.2版2026年11月23日時点で例が通過この章の7 例件のうち7件が合格
英語版の書籍(版2026.11.2)から翻訳した。