텔레메트리에서 개인 데이터 제외하기
읽는 데 약 43분, 10절에 7개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.2판을 번역한 것이다. 원문 읽기
Labs
직접 해 보며 이 장을 배운다
모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. 약 30초 안에 열린다.
모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. Labs가 실행을 대신한다: 월 40시간.
자신의 컴퓨터에서, 무료로: 이 책의 노트북 내려받기, 코드와 데이터를 포함해 GitHub에서 받을 수 있다.
책의 버전에서 코드 실행하기
이 장을 마치면 어시스턴트의 텔레메트리에서 개인 데이터를 기본적으로 제외하고, 명시한 목적에 맞게 콘텐츠 캡처를 켜고 그로 인한 유출을 집계하며, 마스킹으로 제거할 수 있는 유출과 닿지 않는 유출을 구분해 설명할 수 있다. 또 남은 항목을 집계하는 스캔을 실행하고, 어떤 집계가 단언으로 0이 되고 어떤 집계가 측정만 되는지 확인한다.
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판에서 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는 모든 메시지의 루트 스팬에 들어 있으며, 유출 예제는 캡처 설정과 관계없이 메시지마다 이러한 스팬이 하나씩 있음을 검증한다. 이 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.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
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)는 스팬을 저장하기 전에 스팬의 속성이나 이벤트에 있는 개인 값을 자리 표시자로 바꾸는 작업이다. 이 작업은 스팬을 만든 프로세스에서 하거나, 모든 서비스의 스팬이 지나가는 지점에서 한다. 어시스턴트의 프로세스는 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라는 목록으로 만든다. 이 줄의 주석은 그대로 둔다.
작동 원리
삭제 처리는 그날 들어 있던 합성 항목을 모두 제거하고 개인 정보처럼 보이는 값은 그대로 남기며, 예제는 이 두 가지를 모두 단언한다. 사용자 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진수 열두 자리로 줄여 쓴다. 한 사용자의 가명은 어디에 나타나든 같다. 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판에서 openai 3.56.0에서 3.57.0(으)로에서 업데이트됨.
키 없는 개수를 키 없는 해시와 비교한다
+10 증명키를 사용한 사용자 가명의 12장에서다시 읽는다
이 연습이 다루던 내용이 새 판에서 바뀌었다. 2026.11.2판에서 바뀐 내용
43행은 각 후보의 키 없는 해시를 40행에서 구한 대상의 키 없는 해시와 비교하지 않고, 41행의 키 있는 가명과 비교한다. 키 없는 개수가 저장된 키 없는 해시와 비교되도록 43행을 고쳐라.
작동 원리
키가 있는 가명으로 후보 세기
+10 증명키를 사용한 사용자 가명의 12장에서다시 읽는다
이 연습이 다루던 내용이 새 판에서 바뀌었다. 2026.11.2판에서 바뀐 내용
48번째 줄은 비어 있다. 41번째 줄에서 저장된 키 기반 가명을 만든 것과 같은 함수로 만든 가명이 그 저장된 값과 같은 후보 ID의 수를 세도록 이 줄을 작성하라.
작동 원리
키를 사용한 해시는 키 없는 해시가 막지 못하는 전수 대입에 저항한다. 저장된 해시 하나에 대해 시도한 후보 ID 10,000개 가운데, 키 없는 SHA-256은 대상인 1개를 찾아내고, 공격자가 갖지 못한 키를 쓴 HMAC은 0개를 찾아낸다. 이 책의 코드에 적혀 있는 시연용 키를 쓴 같은 HMAC은 1개를 찾아낸다.
마지막 수치가 실제로 키를 비밀로 해야 하는 이유이다. 코드에 있는 시연용 키는 비밀이 아니며, 파일을 읽는 사람이면 누구나 이를 가진다. 이 실행은 구성 방식을 보여 줄 뿐 식별자를 보호하지는 않는다. 실제 키에는 비밀 저장소를 사용하고, 코드와 텔레메트리에서 떨어뜨려 보관할 것을 권한다.
이것이 가명이 원본 ID보다 스팬에 넣기에 안전한 이유이며, 4장에서 설명하겠다고 약속한 내용이다. 그렇다고 가명이 익명은 아니다. 안정적인 가명은 여전히 한 사용자의 모든 스팬을 연결하므로, 엔지니어는 같은 사용자의 모든 메시지를 찾을 수 있고, 가명 옆에 있는 내용이 사용자를 식별할 수도 있다. 민감한 데이터 처리에 관한 OpenTelemetry의 지침은 해시가 팀에 필요한 익명성을 제공하지 못할 수 있다고 지적한다. 사용자 ID는 베기지(baggage)에 넣지 않으며, 가명도 거기에 넣지 않는다. 스팬에서 가명은 키가 없는 독자에게 누구인지 알려 주지 않는다. 또한 비식별화 도구는 메시지 본문에 나타나는 사용자 ID에도 같은 가명을 적용하므로, 한 사용자에 관한 두 스팬은 비식별화 후에도 서로 일치한다.
작업 규칙: 모든 가명에는 텔레메트리 독자가 결코 갖지 못하는 비밀 키를 사용하고, 그 키는 코드 밖에 보관한다. 키는 계획을 세운 뒤에만 바꾼다. 새 키는 모든 사용자의 가명을 처음부터 다시 만들기 때문에, 변경 전에 만든 트레이스는 변경 후에 만든 트레이스와 더 이상 결합되지 않는다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
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, 사용자 이름, 이메일 주소가 여기에 속하며 수정(redaction)으로 반드시 제거해야 한다. 둘째 군은 스택 트레이스로, 앞선 절에서 다루었다. 셋째 군은 MASSIVE의 슬롯 레이블로, 스캐너가 수집된 텍스트에서 찾아내는 사람, 장소, 관계 등의 값이다. 첫째 군은 수정 후 0이어야 한다고 단언한다. 셋째 군은 측정한다.
이렇게 나누는 기준은 각 군이 허용하는 바에 있다. 수정기는 합성 항목을 안다. 합성 항목은 사례 자체의 목록과 .example 도메인에서 나오기 때문이다. 따라서 수정기는 이를 제거할 수 있고, 예제는 실제로 제거되었음을 단언한다. 스캐너가 수정기가 매칭하는 패턴이 아니라 사례 자체의 값을 찾기 때문에 이 0은 의미가 있다. 반면 수정기는 요청 속 어떤 단어가 사람 이름인지 알 수 없다. 앱에는 데이터셋의 레이블이 없기 때문이다. 슬롯 레이블에 대해 0을 단언하려면 그 레이블이 필요하다. 그래서 예제는 수정 전후에 슬롯 레이블을 세며, 수정 후 남는 값은 사람 값 55개이다.
슬롯 레이블 두 가지는 따로 설명이 필요하다. 이 책이 싣는 슬라이스의 영어 주석에는 email_address에 해당하는 값이 전혀 없으므로, 이 패턴은 아무것도 매칭하지 않고 0은 슬라이스에서 비롯된 결과이다. personal_info에는 주석이 달린 구가 하나 있으나, 스캐너는 그날 수집된 텍스트에서 이를 하나도 찾지 못한다. 이 0은 측정값이며, 그래서 단언이 아니라 남은 항목에 나타난다.
다음 예제는 각 종류의 항목을 담은 스팬을 수정 전과 후로 나누어 두 패널에 그린다.
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일차에서 각 종류의 항목을 담은 스팬을 수정 전후로 두 패널에 그린 것이다. 위쪽 패널의 합성 종류는 수정 후 0으로 떨어진다. 아래쪽 패널의 개인 정보처럼 보이는 값은 수정 전과 같은 막대를 유지하며, 사람 값의 스팬은 수정 전 38개, 수정 후 38개이다. 각 패널은 자체 눈금을 쓰므로 막대는 한 패널 안에서 비교하고 두 패널 사이에서는 비교하지 않는다. 그림은 스팬을 세고 스캔은 항목을 세므로, 같은 종류라도 아래쪽 패널의 막대는 스캔의 개수보다 작으며, 두 값 모두 수정 전후에 같다. 각 쌍에서 두 번째 막대가 수정 후의 개수이다.
수정 후 남는 사람 값 55개는 수정기가 요청 텍스트에서 미치지 못하는 범위가 얼마인지를 보여 준다. 이는 수정기가 미치는 범위를 센 값이지 누군가의 기록을 센 값이 아니므로, 독자는 이를 기록의 수로 받아들여서는 안 된다.
작업 규칙: 수정기가 제거하도록 만들어진 종류에 대해서만 0을 단언하고, 나머지 모든 종류는 측정값으로 출력한다. 수정기가 미치지 못하는 개수는 보고해야 할 사실이며, 통과한 검사에 불리하게 계산하지 않는다.
남은 데이터를 누가 읽을 수 있는가
비식별화한 트레이스에도 데이터는 남아 있으며, 비식별화 도구가 무엇을 제거했는가만큼 누가 그것을 읽을 수 있는가도 중요하다. 남은 행에는 사용자 ID 대신 가명이, 비식별화 도구가 찾지 못한 슬롯 값이, 서비스가 기록한 뒤 이후 어떤 단계에서도 제거되지 않은 스택 트레이스가 들어 있다. 콘텐츠 저장소는 사용자의 텍스트를 그대로 보관한다. 따라서 스팬에 이름이 없더라도 스팬을 읽는 일은 개인 데이터를 읽는 일의 한 종류이다.
각 독자에게 목적에 필요한 행만 주기를 권장한다. 경보에 대응하는 사람은 가명, 경로, 타이밍을 담은 비식별화된 행을 읽으며, 콘텐츠는 필요하지 않다. 특정 경로를 디버깅하는 사람은 캡처를 켤 때 명시한 목적을 위해, 그 목적이 지속되는 동안에 한해 콘텐츠를 읽을 수 있다. 연락처 팀은 자신이 소유한 서버의 스팬을 읽는다. 누가 어떤 행을 읽는가는 백엔드의 접근 제어가 강제하며 이 책의 수신기에는 접근 제어가 없으므로, 이 규칙은 백엔드가 콘텐츠 속성이나 콘텐츠 저장소를 역할별로 제한할 수 있는 경우에만 유효하다. 그렇게 할 수 있는 백엔드를 권장한다.
개인 데이터가 모델 자체의 컨텍스트에 들어가지 않게 하는 일은 별개의 작업이다. Securing LLM Applications and Agents에서 숨겨진 컨텍스트는 시스템 프롬프트가 사용자에게 보이지 않게 담아 두는 내용, 예를 들어 비밀 값을 말한다. 이 장은 모델이 실행된 뒤에 텔레메트리가 담고 있는 내용을 다룬다.
작업 규칙: 캡처를 켜기 전에 원본 콘텐츠를 누가, 어떤 목적으로, 언제까지 읽을 수 있는지 적어 두어라. 그 외의 모든 독자에게는 비식별화된 행을 주고, 콘텐츠 저장소에도 같은 규칙을 적용하라.
운영 환경에서 개인 정보 걸러 내기
이 장의 비식별화는 이 책이 다루는 사례에서 동작하며, 운영 환경은 여러 면에서 다르다. 이 비식별화 도구는 사례에 나오는 이름을 알고 있으며 대소문자를 구분해 일치시킨다. 주소 규칙은 .example 도메인과 일치한다. 실제 이름이나 실제 주소는 그대로 통과한다. 이 도구는 스팬의 이름, 리소스, 링크, 배열 값도 건드리지 않는다. 운영 팀에는 자신이 보유한 데이터에 맞는 탐지기가 필요하다. 개인 정보용으로 학습된 PII 모델이 그 예이다. 또한 탐지기가 놓치는 항목은 레이블이 붙은 데이터로 측정해야 하는데, 이 책에는 그런 데이터가 없다.
스택 트레이스 규칙은 속성 이름 하나, 곧 exception.stacktrace만 기준으로 삼는다. 다른 이름으로 기록된 트레이스백은 통과하며, 메시지 본문에 나타나는 경로도 통과한다. 스캐너는 스택 트레이스를 별도의 종류로 집계하므로, 팀은 배포할 때마다 그 수를 세어 새 서비스가 스택 트레이스를 쓰기 시작했는지 확인할 수 있다.
원본 스팬은 수신기가 비식별화하기 전에 네트워크도 거친다. 전송 구간과 수신기 자체의 로그에는 그동안 원본 내용이 남아 있으므로, 경로의 다른 부분과 같은 수준으로 관리해야 한다. 비식별화하는 수신기는 경로의 다른 어느 곳도 수신한 내용을 보관하지 않을 때만 안전하다.
가명은 키만큼만 비공개이다. 이 책처럼 키를 코드에 두면 코드를 읽는 누구나 후보 ID를 대조해 볼 수 있으며, 키가 유출되어도 결과는 같다. 운영 환경에서는 시크릿 저장소에서 무작위 32바이트로 키를 만든다. RFC 2104는 해시 출력보다 짧은 HMAC 키를 쓰지 말 것을 권고한다. 16진수 12자리는 사례의 사용자 200명에는 충분하지만, 사용자 기반이 크면 더 많은 자릿수가 필요하다. 사용자가 천만 명이면 서로 다른 사용자가 같은 가명을 공유할 가능성이 더는 낮지 않기 때문이다. 키를 교체하면 모든 사용자의 가명이 새로 시작되므로, 교체에는 계획이 있어야 한다.
콘텐츠 저장소는 사용자의 텍스트를 온전히 보관하며, 보존 기간은 저장소 자체의 사안이다. 11장은 그 기간을 백엔드를 운영하는 팀에 맡겼고, 이 저장소의 기간도 그 팀에 속한다. 기간이 없는 저장소는 존재하는 한 계속 텍스트를 보관한다.
작업 규칙: 배포할 때마다 하루치 트래픽에 스캔을 실행하고, 비식별화 후에도 집계가 0을 넘는 종류는 남아 있어도 되는 이유를 누군가 설명할 수 있을 때까지 발견 사항으로 취급한다. 새로운 출처가 하나의 보고서에 드러나도록, 스택 트레이스와 항목은 같은 스캔에서 함께 센다.
이 장이 내린 결정
프로세스는 자신이 기록하는 것만 제거할 수 있다. 따라서 아래의 각 결정은 모든 프로세스의 출력이 모이는 지점에 점검을 둔다.
- 모든 서비스에서 콘텐츠 캡처를 끈다. 캡처를 꺼도 모든 메시지의 루트 스팬에는 사용자 ID가 남으므로, 키를 사용한 가명은 추가 사항이 아니라 기본 구성의 일부다.
- 모든 서비스의 스팬이 통과하는 지점에서 스택 트레이스를 제거한다. 이 책에서는 그 지점이 수신기(receiver)이며, 프로덕션 Collector에서도 같은 단계를 권장한다. 연락처 팀은 조회 스팬에
record_exception=False을 설정해야 하지만, 데이터를 보호하는 데 그 변경에 의존하지는 않는다. - 각 프로세스가 기록하는 내용에 대해 그 프로세스 안에서 비식별화를 수행하고, 모든 서비스의 스팬이 통과하는 지점에서 다시 수행한다. 스택 트레이스는 이 한계가 어떤 비용을 치르는지 보여 준다.
- 텔레메트리를 읽는 쪽이 갖지 않는 비밀 값으로 사용자 가명에 키를 적용한다. 코드에 있는 시연용 키는 구성 방식만 보여 준다.
- 콘텐츠는 자체 접근 규칙과 보존 규칙이 있는 저장소에만 보관한다. 업로드 훅은 켜져 있는 동안에는 샘플링이 버리는 스팬을 포함해 항상 기록하기 때문이다.
- 비식별화가 제거하는 합성 유형에 대해서는 0건임을 단언하고, 비식별화 도구가 미치지 못하는 범위의 척도로서 데이터셋 값의 잔여분을 출력한다.
- 모든 릴리스의 출력에 스캔을 실행하여, 스택 트레이스나 항목의 새로운 출처가 보고서 하나에서 드러나게 한다.
이 판의 이 장
2026.11.2판예제 통과 2026년 11월 237 of 7개 예제 in this chapter pass
영어판 2026.11.2판을 번역한 것이다.