보존, 동의, 삭제

읽는 데 약 70분분 걸린다, 13절에 11개 예제이(가) 있음.

2026.11.31판 예제 통과 2026년 11월 19 108개 예제 중 108개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.31판을 번역한 것이다. 원문 읽기

이 장을 마치면 보존 규칙을 검토를 거친 설정으로 관리할 수 있다. 동의 철회가 다음 쿼리에 반영되도록 만들 수 있고, 한 사람의 데이터가 도달한 모든 테이블에서 그 사람을 삭제할 수 있다. 전달받은 날짜를 기준으로 규칙을 적용하고, 리니지로 해당 테이블을 찾으며, 법무팀이 예외로 기록해 둔 데이터만 남긴다. 또한 Iceberg 테이블에서 행 삭제 후에 남는 것, 즉 오래된 스냅샷, 참조되지 않는 파일, 열 통계를 제거한다. 마지막으로 남은 모든 파일을 읽어 그중 어느 것에도 그 사람의 데이터가 없음을 보여 주는 스캔으로 마무리한다.

이 책에서 다루는 온라인 학습 플랫폼은 2024년 1월의 첫 가입 이후 모든 데이터를 하나의 Iceberg 카탈로그에 보관해 왔다. 모든 지원 티켓과, 접속 IP 주소가 함께 담긴 모든 학습 이벤트가 그 대상이다. 둘 중 어느 것도 얼마나 오래 보관해야 하는지 정해진 바가 없다. 학습자 3590은 마케팅 이메일에 대한 동의를 철회했고, 몇 주 뒤 플랫폼에 자신의 데이터를 삭제해 달라고 요청한다. 첫 번째 요청은 다음 쿼리부터 마케팅 부서가 보는 데이터를 바꿔야 한다. 두 번째 요청은 학습자의 사본을 어디에도 남기지 않아야 한다. 그 학습자의 테이블에서 만들어진 테이블에도, Iceberg가 의도적으로 보관하는 각 테이블의 이전 버전에도 남아서는 안 된다.

세 가지 용어가 이 장의 주제를 가리킨다. 보존은 플랫폼이 각 종류의 데이터를 얼마나 오래 보관하는지를 뜻한다. 동의는 마케팅 이메일처럼 데이터의 특정 사용에 대한 개인의 승낙이며, 철회할 수 있다. 삭제는 요청에 따라 한 사람의 데이터를 제거하는 일이다. 이 장은 책의 공용 코드에 두 가지를 추가한다. 하나는 플랫폼의 보존 규칙을 담은 governance/retention.toml이고, 다른 하나는 모듈 lib.retention이다. 이 모듈은 규칙을 적용하고, 삭제를 계획하고 수행하며, 이후 파일을 정리하고 검사하고, 삭제 대장을 관리한다. 학습자의 데이터가 어디로 갔는지 찾을 때는 4장의 lib.lineage를 사용하고, 2장의 lib.metadata에 있는 분류를 사용한다. 모든 예제는 로컬 카탈로그에서 PyIceberg 0.12.0을 실행한다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Keep retention rules in a reviewed file

마지막으로 변경된 판: 2026.11.27판

A retention rule says how long one kind of data is kept, from which date the time counts, and which rows it applies to. The EU's General Data Protection Regulation (GDPR) states the principle as storage limitation: personal data are to be "kept in a form which permits identification of data subjects for no longer than is necessary for the purposes for which the personal data are processed" (Article 5(1)(e)). Its Recital 39 asks the controller to set time limits for erasure or for a periodic review (GDPR). NIST's catalog of security and privacy controls describes the same job, asking that information be disposed of, destroyed or erased once its retention period ends (control SI-12(3)) (NIST SP 800-53 Rev. 5). The platform's owners and lawyers decide how long is necessary; the code applies what they decide, every time.

That argues for rules as config, reviewed like the access policies, and for code that applies them to a day it is given, not the clock. A job that reads the clock deletes different rows depending on when it runs: a test can't pin its result, and a rerun after a failure can delete more than the run it replaces.

The platform's rules are in governance/retention.toml. The periods are the platform's own choices for this book's case, not legal advice:

[tables."support.tickets"]
keep_days = 730
counted_from = "opened_at"        # tickets record when they were opened, not when they were closed
only_when = { column = "status", equals = "closed" }

[tables."learning.events"]
keep_days = 365
counted_from = "occurred_at"

[tables."billing.payments"]
keep_days = 3650                  # a placeholder for the period the platform's legal team sets for payment records
counted_from = "paid_at"

Closed tickets are kept two years, events one year, and payments 3,650 days, a placeholder that the erasure plan relies on. The tickets rule should count from when a ticket was closed, but the table records only opened_at, so a ticket opened 25 months ago and closed last week goes at once. The platform lives with that because adding a closed_at column is the support team's change, not the platform team's; until they make it, the rule errs toward deleting early. lib.retention.due turns a rule and a day into an Iceberg filter. Counted on the book's "today", Oct 1, 2026, and 90 days later, the rows each rule selects come out like this:

retention-rules-due.py Python 3.12.15 · duckdb 2.0.0 · openlineage-python 1.55.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · pyyaml 6.0.3 · sqlglot 30.33.0 통과
"""The rows each retention rule makes due on the book's today and 90 days later, counted against the day the job is given.The `rows due` lines are the counts the prose gives."""from datetime import timedeltafrom lib import retentionfrom lib.catalog import open_catalogfrom lib.platform import TODAYrules = retention.rules()["tables"]catalog = open_catalog(sorted(rules))for name, rule in sorted(rules.items()):    state = rule.get("only_when")    print(f"{name}: kept {rule['keep_days']} days from {rule['counted_from']}"          + (f", once {state['column']} is {state['equals']}" if state else ""))# the book's today, then 90 days later: the day is passed in, never read from the clockfor day in (TODAY, TODAY + timedelta(days=90)):    for name, rule in sorted(rules.items()):        table = catalog.load_table(name)        # the earliest date kept: keep_days before the day        print(f"{name} on {day}, kept from:", retention.cutoff(rule, day))        print(f"{name} on {day}, rows due:", f"{retention.count(table, retention.due(rule, day)):,}")        print(f"{name} on {day}, rows in the table:", f"{retention.count(table):,}")
출력python retention-rules-due.py
billing.payments: kept 3650 days from paid_at
learning.events: kept 365 days from occurred_at
support.tickets: kept 730 days from opened_at, once status is closed
billing.payments on 2026-10-01, kept from: 2016-10-03
billing.payments on 2026-10-01, rows due: 0
billing.payments on 2026-10-01, rows in the table: 17,562
learning.events on 2026-10-01, kept from: 2025-10-01
learning.events on 2026-10-01, rows due: 9,060
learning.events on 2026-10-01, rows in the table: 100,000
support.tickets on 2026-10-01, kept from: 2024-10-01
support.tickets on 2026-10-01, rows due: 58
support.tickets on 2026-10-01, rows in the table: 2,000
billing.payments on 2026-12-30, kept from: 2017-01-01
billing.payments on 2026-12-30, rows due: 0
billing.payments on 2026-12-30, rows in the table: 17,562
learning.events on 2026-12-30, kept from: 2025-12-30
learning.events on 2026-12-30, rows due: 15,545
learning.events on 2026-12-30, rows in the table: 100,000
support.tickets on 2026-12-30, kept from: 2024-12-30
support.tickets on 2026-12-30, rows due: 111
support.tickets on 2026-12-30, rows in the table: 2,000

The rows due depend on the day passed in and the data, and on nothing else. On Oct 1, 2026, the events rule keeps events from 2025-10-01 on, so 9,060 of the 100,000 events are due, and on Dec 30, 90 days later, 15,545 are. The tickets rule makes 58 of the 2,000 tickets due on Oct 1, all closed and opened over two years ago. On Dec 30 it makes 111 due. The payments rule makes 0 of the 17,562 payments due on Oct 1 and 0 on Dec 30.

Working rule: Keep each table's retention period, the column it counts from and the state a row must be in, in a reviewed file, and apply it against a day the scheduler passes in, never the clock. Count from the date the rule means. When the table doesn't record that date, as the platform's tickets don't record when they closed, ask the table's owner to add the column rather than let the rule count from another date for good, and say in the rule's file which way it errs until then.

행 삭제로 만료된 행 지우기

마지막으로 변경된 판: 2026.11.27판

파일에 담긴 규칙을 갖추었으니, 보존 작업은 그 규칙이 말하는 대로 행을 삭제한다. Iceberg 기록기는 두 가지 방식 중 하나로 행을 삭제하며, 방식은 테이블 속성 write.delete.mode가 정한다. 기본값은 copy-on-write이다(Iceberg configuration). Copy-on-write는 영향받는 데이터 파일마다 삭제된 행을 뺀 채로 다시 쓴다. Merge-on-read는 데이터 파일은 그대로 두고 그 옆에 삭제 파일을 쓴다. 명세에는 두 종류의 삭제 파일이 있다. 위치 삭제(position delete)는 행을 데이터 파일과 그 안의 위치로 표시하며(버전 3 이상의 테이블에서는 삭제 벡터), 동등 삭제(equality delete)는 하나 이상의 열 값으로 행을 표시한다(Iceberg table spec). PyIceberg 0.12.0의 Table.delete는 항상 copy-on-write로 동작한다. merge-on-read를 설정해도 merge-on-read는 아직 지원되지 않는다고 경고한 뒤 어차피 파일을 다시 쓴다(source). 어느 쪽이든 삭제는 하나의 커밋, 곧 새 스냅숏이며, 그 이전의 스냅숏은 그대로 남아 있다.

lib.retention.apply는 규칙마다, 주어진 날짜에 대해 due가 반환하는 행을 삭제하고, 규칙의 테이블과 날짜를 커밋의 스냅숏 요약에 기록한다. 그래서 행이 사라진 이유를 테이블 자체의 이력이 말해 준다. 2026년 10월 1일에 대한 두 번의 실행을, 현재 시점의 읽기와 타임 트래블 읽기로 살펴보면 삭제 뒤에 무엇이 남는지 알 수 있다. 마지막으로 오래된 스냅숏을 기간 기준으로 만료시킨다.

apply-retention.py Python 3.12.15 · duckdb 2.0.0 · openlineage-python 1.55.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · pyyaml 6.0.3 · sqlglot 30.33.0 통과
"""Applies the retention rules for the book's today as Iceberg row deletes, which leave the old rows in older snapshots.The rerun line is zero, and the time-travel lines show the rows the snapshot before each delete still returns."""from datetime import datetime, timedelta, timezonefrom lib import retentionfrom lib.catalog import open_catalogfrom lib.platform import TODAYrules = retention.rules()["tables"]catalog = open_catalog(sorted(rules))# each table's snapshot from before the deletes, which the time-travel lines readbefore = {name: catalog.load_table(name).current_snapshot().snapshot_id for name in rules}deleted = retention.apply(catalog, TODAY)for name, rows in deleted.items():    print(f"{name}, rows deleted:", f"{rows:,}")print("rows deleted by running again for the same day:", sum(retention.apply(catalog, TODAY).values()))for name in (name for name, rows in deleted.items() if rows):    rule, table = rules[name], catalog.load_table(name)    summary = table.current_snapshot().summary    print(f"{name}, snapshots:", " then ".join(s.summary.operation.value for s in table.snapshots()))    # copy-on-write writes the rows it keeps again as new records, which is what this line counts    print(f"{name}, rows written again to delete the others:", f"{int(summary['added-records']):,}")    print(f"{name}, the commit records:", summary["retention-rule"], "on", summary["retention-day"])    rows_due = retention.due(rule, TODAY)    print(f"{name}, rows due, read now:", f"{retention.count(table, rows_due):,}")    print(f"{name}, rows due, read by time travel:", f"{retention.count(table, rows_due, before[name]):,}")    # Snapshots carry real commit times, so their age is measured on the clock, by the table's own setting.    print(f"{name}, snapshots expired by age today:", retention.expire_by_age(table))    # six days on, the snapshot from before the delete is older than the table's five-day setting    later = datetime.now(timezone.utc) + timedelta(days=6)    print(f"{name}, snapshots expired by age six days later:", retention.expire_by_age(table, later))
출력python apply-retention.py
billing.payments, rows deleted: 0
learning.events, rows deleted: 9,060
support.tickets, rows deleted: 58
rows deleted by running again for the same day: 0
learning.events, snapshots: append then overwrite
learning.events, rows written again to delete the others: 90,940
learning.events, the commit records: learning.events on 2026-10-01
learning.events, rows due, read now: 0
learning.events, rows due, read by time travel: 9,060
learning.events, snapshots expired by age today: 0
learning.events, snapshots expired by age six days later: 1
support.tickets, snapshots: append then overwrite
support.tickets, rows written again to delete the others: 1,942
support.tickets, the commit records: support.tickets on 2026-10-01
support.tickets, rows due, read now: 0
support.tickets, rows due, read by time travel: 58
support.tickets, snapshots expired by age today: 0
support.tickets, snapshots expired by age six days later: 1

재시도된 실행은 해가 없다. 같은 날짜에 대한 두 번째 실행은 0개 행을 삭제했고 커밋을 만들지 않았다. 첫 번째 실행은 이벤트 9,060개, 티켓 58개, 결제 0개를 삭제했다. 변경된 각 테이블은 append 스냅숏에서 overwrite 스냅숏으로 바뀌었고, 요약은 copy-on-write의 비용을 보여 준다. 오래된 이벤트를 삭제하려고 PyIceberg는 나머지 90,940개 행을 다시 썼다. 이 테이블이 파티션되지 않은 하나의 파일이기 때문이다. occurred_at의 월 단위로 파티션했다면 같은 삭제가 파일 전체를 버리는 방식으로 처리될 수 있으며, Table.delete는 파일의 모든 행이 일치할 때 그렇게 한다. PyIceberg 0.12.0에서 월 단위로 파티션된 테이블을 쓰려면 추가 항목 pyiceberg-core가 필요하며, 이 책의 예제에는 설치되어 있지 않다.

삭제는 테이블의 이전 스냅숏에서 행을 제거하지 않는다. 현재 상태로 읽으면 learning.events에는 보존 기간이 지난 행이 0개 있지만, 타임 트래블로 읽으면 삭제 이전의 스냅숏은 IP 주소를 포함한 9,060개 행을 모두 여전히 반환하고, 그 행을 담은 Parquet 파일도 여전히 디스크에 있다. lib.retention.expire_by_age는 테이블 자체의 history.expire.max-snapshot-age-ms보다 오래된 스냅숏을 만료시키며, 여기서는 5일이고 시계를 기준으로 측정한다. 이 함수는 삭제 직후에는 learning.events의 스냅숏 0개를 만료시키고, 6일 뒤에는 1개를 만료시킨다. 보존 작업은 오래된 스냅숏을 만료시키고 어떤 스냅숏도 참조하지 않는 파일을 제거해야 끝난다. 삭제(erasure)에 필요한 정리도 이와 같다.

작업 규칙: 보존은 Iceberg 행 삭제로 한 번에 규칙 하나씩 적용하고, 규칙과 날짜를 각 커밋의 스냅숏 요약에 기록한다. 작업은 주어진 날짜에 대해 멱등하게 만든다. 큰 테이블은 규칙이 기준으로 삼아 세는 열로 파티션하여, 삭제가 파일을 다시 쓰는 대신 파일 전체를 버리게 한다. PyIceberg에서 그렇게 쓰려면 pyiceberg-core 추가 항목을 설치한다. 오래된 스냅숏이 만료되고 그 파일이 제거된 뒤에야 작업이 끝난 것으로 본다.

마지막으로 변경된 판: 2026.11.27판

보존은 행을 기간에 따라 제거한다. 동의는 누가 그 행을 사용할 수 있는지를 바꾸며, 동의 철회는 삭제 요청과 같은 사건이 아니므로 플랫폼의 코드는 이 둘을 별개의 경로로 다룬다. EU 일반 개인정보 보호법(GDPR) 제7(3)조는 다음과 같이 규정한다. "정보주체는 언제든지 동의를 철회할 권리를 가진다. 동의의 철회는 철회 이전에 동의에 근거하여 이루어진 처리의 적법성에 영향을 미치지 않는다." (GDPR). 같은 법 제17(1)(b)조는 동의 철회를 삭제 사유의 하나로 규정하지만, 처리를 뒷받침하는 다른 법적 근거가 남아 있지 않은 경우에 한한다. 코드에서 철회는 속성 하나를 바꾸고, 삭제는 행을 지운다.

플랫폼에서 동의는 접근 정책이 읽는 데이터의 속성이다. 이는 5장에서 설정한 대로이다. 마케팅의 행 필터는 marketing_consent가 참인 학습자만 남기고, 코스 어시스턴트의 행 필터는 작성자의 ai_training_consent가 참인 리뷰만 남긴다. 따라서 철회에는 정책을 바꿀 필요가 없다. 학습자가 계정을 관리하는 애플리케이션인 CRM이 새 값을 crm.learners에 동기화하면, 모든 쿼리를 다시 쓰도록 6장에서 구축한 적용 계층을 거쳐 마케팅이 다음에 실행하는 쿼리는 학습자를 한 명 적게 반환한다.

학습자 3590의 마케팅 동의를 철회한 다음, 철회 전, 철회 후, 그리고 마케팅 파이프라인이 다시 실행된 뒤에 마케팅이 보는 것과 테이블에 들어 있는 것을 읽어 보자.

철회는 다음 쿼리부터 효력이 생겼고 아무것도 제거하지 않았다. 마케팅이 보는 학습자는 철회 전에는 학습자 3590을 포함해 1,861명이고, 철회 후에는 학습자 3590을 제외한 1,860명이다. 마케팅의 행 필터는 계속 [{"column": "marketing_consent", "equals": true}, {"column": "status", "equals": "active"}]이며, crm.learners에는 여전히 5,000개의 행이 저장되어 있다. 삭제된 것은 없다. 학습자의 계정, 수강 등록, 이력은 그대로이다.

문제는 복사본이다. 마케팅 파이프라인이 매일 밤 만드는 목록인 marketing.audience은 만들어질 때 동의 필터를 적용하며, 정책은 마케팅에 이 테이블을 자체 동의 필터 없이 제공한다. 철회 후에도 이 테이블에는 학습자 3590의 행이 1개 남아 있다. 누군가 테이블의 열을 분류하기 전까지는 정책이 모든 사용자에게 그 열을 가리지만, 4장의 제안대로 분류가 이루어지면 다음 빌드 전에 이 테이블로 발송한 캠페인이 거부 의사를 밝힌 사람에게 도달한다. 파이프라인이 다시 실행되고 나서야 그 수가 0으로 줄어든다. 학습 코퍼스 역시 동의 필터로 만들어지며, 9장은 학습에 사용하기 전에 매 빌드를 오늘의 동의와 대조해 확인한다.

참 또는 거짓만 담는 열은 전하는 정보도 너무 적다. ai_training_consent는 플랫폼이 동의를 묻기 전에 가입한 모든 사람에게서 null이며, 거짓은 거부와 철회 중 어느 쪽도 의미할 수 있다. 표준이 아니라 W3C 커뮤니티 그룹 보고서인 Data Privacy Vocabulary는 동의가 놓일 수 있는 상태를 명명하며, 부여됨, 거부됨, 철회됨, 만료됨, 알 수 없음이 그 안에 들어 있다(DPV 2.3).

작업 규칙: 동의는 쿼리가 실행되는 곳에 둔다. 즉 학습자가 사용하는 시스템이 최신 상태로 유지하는 하나의 테이블에 두고, 정책이 이를 행 필터로 읽게 하여 철회가 다음 쿼리를 바꾸되 아무것도 삭제하지 않게 한다. 플랫폼의 법률 담당자가 철회도 삭제 사유라고 판단하면 삭제 경로로도 보낸다. 동의 필터로 만든 모든 테이블은 동의가 바뀔 때마다 다시 빌드하거나, 그 테이블의 읽는 이에게 같은 필터를 적용한다. 각 동의는 상태와 그 상태가 바뀐 시각으로 기록하고, 정책이 읽는 참 또는 거짓 속성은 이로부터 도출하되 알 수 없음은 부여되지 않음으로 센다.

계보에서 삭제 계획 세우기

마지막으로 변경된 판: 2026.11.27판

동의 철회는 속성 하나를 바꾸지만, 삭제는 그 사람을 모든 곳에서 찾아내야 한다. GDPR의 Article 17(1)은 열거된 사유에 해당하면 정보주체가 부당한 지체 없이 자신의 데이터를 삭제할 권리를 갖는다고 규정한다(GDPR). 플랫폼은 요청이 모든 사본에 미치는 것으로 취급하므로, 첫 번째 일은 그 사람의 데이터가 어디에 있는지를 두 부분으로 나눈 목록으로 만드는 것이며, 이는 엔지니어링의 문제다. 학습자의 ID를 가진 원본 테이블은 카탈로그에서 얻는다. 2장에서 learner_id가 있는 모든 테이블은 분류와 상관없이 모든 삭제에 포함된다고 정했다. 그 테이블들로 만들어진 테이블은 계보에서 얻는다. 4장에서 다룬 컬럼 그래프 탐색을 각 원본 테이블에서 실행하면, 그 행들이 영향을 준 모든 테이블에 닿는다.

일부 데이터는 남는다. 같은 규정의 Article 17(3)은 처리가 필요한 범위에서 삭제가 적용되지 않는 경우를 정하며, 다섯 가지 항목 중에는 컨트롤러가 따라야 하는 연합 또는 회원국 법에 따른 법적 의무를 준수하기 위한 경우가 있다(GDPR). 예외가 적용되는지, 어느 테이블에 적용되는지, 얼마나 오래 적용되는지는 법무팀이 결정할 일이지 코드가 결정할 일이 아니다. 코드는 그 결정을 담을 자리로 governance/retention.toml를 하나 두고, 법무팀이 여기에 각 예외를 그 사유와 함께 적는다. 이 책에서는 어떤 법적 문제도 판단하지 않으므로 사유는 자리 표시자다.

[erasure.exceptions."billing.payments"]
reason = "PLACEHOLDER: a legal obligation to keep payment records, such as tax records. The legal team replaces this with the obligation and the law it comes from."
decided_by = "legal team"         # a role, never a person's name
erase_columns = ["card_number"]   # what the obligation doesn't need; an empty list keeps the whole row

삭제는 예외 테이블의 행을 그 테이블의 보존 규칙이 삭제할 때까지 유지하고, erase_columns가 나열한 컬럼은 즉시 지운다. 여기서는 전체 카드 번호가 해당하며, 플랫폼의 메타데이터는 이를 "Should not be stored at all"이라고 적고 있다. lib.retention.exceptions는 사유가 없는 예외나, 어떤 규칙도 끝내지 않는 테이블에 대한 예외를 거부한다.

파생 테이블을 찾는 것과 그 안에서 학습자의 행을 찾는 것은 같지 않다. lib.retention.plan는 탐색이 닿은 각 테이블로 들어오는 계보 에지를 살펴, 학습자의 ID나 그 행의 ID(예를 들어 리뷰의 ID)에서 변경 없이 복사된 컬럼, 즉 OpenLineage 용어로 IDENTITY 에지가 있는지 확인한다. 있으면 계획은 그 컬럼으로 삭제한다. 없으면 학습자의 행은 그 테이블에 영향을 주었을 뿐이므로, 계획은 원본을 삭제한 뒤 그 테이블의 작업을 다시 실행한다. 계획은 철회 몇 주 뒤에 요청이 들어온 시점의 플랫폼을 있는 그대로 읽는다. crm.learners에는 학습자 3590의 철회된 동의가 남아 있고, 분석, 마케팅, AI 테이블을 만드는 4장의 파이프라인 네 개는 그 뒤로 실행되었으며 그 계보가 기록되어 있다.

학습자 3590의 계획은 단계마다 한 줄씩, 각 테이블과 그 테이블에서 하는 일을 출력한다.

erasure-plan.py Python 3.12.15 · duckdb 2.0.0 · openlineage-python 1.55.0 · phonenumbers 9.0.43 · presidio-analyzer 2.2.366 · pyarrow 26.0.1 · pyiceberg 0.12.0 · pyyaml 6.0.3 · sqlglot 30.33.0 · tldextract 5.4.0 통과
"""The steps that erase one learner: the tables with their learner_id column, then the tables lineage says their rows reach,with the exception the legal team recorded. The counts show how many steps each route found; the last two lines are the text the scan searches for and the rows that name the learner."""from lib import pii, retentionLEARNER = 3590catalog, graph = retention.open_platform()           # weeks after the learner withdrew marketing consentsteps = retention.plan(catalog, graph, LEARNER)for step in steps:    # no column is copied from the learner here: the table's own job runs again once its sources are erased    if step.column is None:        print(f"{step.table}: run {retention.job_for(step.table)} again")    elif step.kept:        print(f"{step.table}: keep, under an exception, and erase {', '.join(step.cleared)}")    else:        print(f"{step.table}: delete where {step.column} in {list(step.values)}"              + (f", a copy of {step.via}" if step.via else ""))print("tables in the plan:", len(steps))# a step with a column and no lineage edge came from the table's own learner_id columnprint("tables found by their learner_id column:", sum(1 for step in steps if step.column and not step.via))# found by lineage: a copy of another table's ID, or a rebuild, because the learner's rows only shaped the tableprint("tables found by lineage:", sum(1 for step in steps if step.via or step.column is None))for step in (step for step in steps if step.kept):    print(f"the reason recorded for {step.table}:", step.kept)theirs = retention.rows_of([LEARNER])for name in ("billing.payments", "marketing.audience"):    print(f"the learner's rows in {name}:", retention.count(catalog.load_table(name), theirs))# the values the scan will search for, noted before any row is deletedfound = retention.traces(catalog, steps, LEARNER)# The phone number is printed through lib.pii.masked, which keeps its shape and its last four digits.print("the learner's identifying values, as the scan searches for them:", pii.masked(", ".join(found.texts)))# rows the plan keeps, in any string column, whose text holds one of those valuesnamed = retention.mentions(catalog, steps, found)print("rows the plan doesn't delete whose text names the learner:", sum(named.values()))
출력python erasure-plan.py
billing.payments: keep, under an exception, and erase card_number
crm.learners: delete where learner_id in [3590]
learning.enrollments: delete where learner_id in [3590]
learning.events: delete where learner_id in [3590]
learning.reviews: delete where learner_id in [3590]
support.tickets: delete where learner_id in [3590]
analytics.course_performance: run course_performance again
analytics.learner_activity: delete where learner_id in [3590], a copy of crm.learners.learner_id
marketing.audience: delete where learner_id in [3590], a copy of crm.learners.learner_id
ai.review_corpus: delete where review_id in [1199], a copy of learning.reviews.review_id
tables in the plan: 10
tables found by their learner_id column: 6
tables found by lineage: 4
the reason recorded for billing.payments: PLACEHOLDER: a legal obligation to keep payment records, such as tax records. The legal team replaces this with the obligation and the law it comes from.
the learner's rows in billing.payments: 2
the learner's rows in marketing.audience: 0
the learner's identifying values, as the scan searches for them: •••-•••-5880 x•, 87199 jacob rad, alexa reed, alexa590@post.e
rows the plan doesn't delete whose text names the learner: 0

계획이 방문하는 테이블은 10개다. learner_id 컬럼이 있는 원본 테이블이 6개이고, 계보가 더하는 테이블이 4개다. 계획은 학습자의 2건의 결제를 예외에 따라 유지한다. 단계는 행이 아니라 컬럼과 계보로 정해지므로, 계획에는 학습자의 행이 없는 테이블 두 개가 나온다. 하나는 학습자 3590이 티켓을 연 적이 없어서 행이 없는 support.tickets이고, 다른 하나는 철회 이후 파이프라인이 다시 만들었기 때문에 행이 0개인 marketing.audience이다. ai.review_corpus에는 learner_id가 전혀 없지만, 계보는 그 review_id가 learning.reviews.review_id의 IDENTITY 복사본이라고 알려 주므로 계획은 그 ID로 학습자의 리뷰를 삭제한다. analytics.course_performance에는 강의별 건수와 평균만 있으므로 계획은 삭제된 원본으로 이를 다시 만든다. 다시 만드는 데는 파이프라인 실행 한 번이 들기 때문에, 한때 학습자를 포함해 계산한 평균이 여전히 그 사람의 데이터인지를 코드가 판단할 필요는 없다.

텍스트는 다른 학습자의 티켓처럼 계획이 삭제하지 않는 행에서도 어떤 사람을 지칭할 수 있다. 예제는 governance/retention.toml가 나열한 식별 값을 모든 문자열 컬럼에서 검색하고, 그런 행 0개를 찾는다. 검색은 각 값의 앞 15자를 소문자로 바꾼 뒤 텍스트의 어디에서든 일치하는지 본다. 여기서는 전화번호를 가린 채 출력한 •••-•••-5880 x•, 87199 jacob rad, alexa reed, alexa590@post.e이며, 15자로 자르는 이유는 마지막 스캔이 설명한다. 다르게 입력된 이름이나 구분 기호 없는 전화번호를 찾으려면 3장의 탐지기가 필요하다.

작업 규칙: 모든 삭제는 사람이 관리하는 목록이 아니라 카탈로그와 계보 그래프에서 계획한다. 그 사람의 ID 컬럼이 있는 모든 테이블을 먼저 보고, 이어서 계보상 그 사람의 행이 닿는 모든 테이블을 본다. 파생 테이블에서는 계보가 ID의 변경 없는 복사본임을 보여 주는 컬럼으로 삭제하고, 그 사람의 행이 영향을 주었을 뿐인 파생 테이블은 다시 만든다. 예외는 법무팀이 사유와 함께 작성하는 설정에 두고, 계획이 이를 읽어서 보여 주게 하며, 코드가 예외를 결정하게 해서는 안 된다. 계보가 보여 주지 않는 사본에는 계획이 닿을 수 없으므로, 먼저 4장의 어떤 작업의 계보에도 설명되지 않는 테이블 점검을 실행한다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Erase the rows the plan lists

마지막으로 변경된 판: 2026.11.27판

The plan says where learner 3590's data is, and lib.retention.erase carries it out in the plan's order. It deletes each step's rows with Table.delete, sources first, writes the rows an exception keeps again with the exception's columns empty, and runs the job of each table the plan rebuilds once the sources are done. Every commit records the request's ID, erasure-0001, in its snapshot summary. Iceberg keeps a summary in the table's metadata files after its snapshot expires, in all of them by default, or only the last write.metadata.previous-versions-max (100 by default) once write.metadata.delete-after-commit.enabled is set (Iceberg maintenance, Iceberg configuration). So the summary holds only the request's ID, which the erasure register pairs with a keyed hash of the learner's ID, and never the learner's email.

The erasure runs on learner 3590's plan under one request ID; reading crm.learners and learning.events now and by time travel shows what it leaves:

erase-learner.py Python 3.12.15 · duckdb 2.0.0 · openlineage-python 1.55.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · pyyaml 6.0.3 · sqlglot 30.33.0 통과
"""Carries out the erasure plan with Iceberg row deletes. The current snapshots no longer hold the learner, but the snapshotsbefore them still do, and the `read by time travel` lines show it."""from lib import retentionLEARNER = 3590catalog, graph = retention.open_platform()steps = retention.plan(catalog, graph, LEARNER)# each table's snapshot from before the erasure, which the time-travel lines readbefore = {step.table: catalog.load_table(step.table).current_snapshot().snapshot_id for step in steps}done = retention.erase(catalog, steps, "erasure-0001")       # the request's ID goes into every commit's summaryfor table, rows in done.items():    # a rebuilt table reports 'rebuilt' rather than a count of rows    print(f"{table}, rows deleted:" if rows != "rebuilt" else f"{table}:", rows)print("tables one row was deleted from:", ", ".join(table for table, rows in done.items() if rows == 1))theirs = retention.rows_of([LEARNER])payments = catalog.load_table("billing.payments").scan(row_filter=theirs).to_arrow()print("billing.payments, the learner's rows kept:", payments.num_rows)# the exception erases card_number to null, so the values that are not null are the card numbers leftprint("billing.payments, card numbers left in them:", payments.num_rows - payments["card_number"].null_count)for name in ("crm.learners", "learning.events"):    table = catalog.load_table(name)    print(f"the learner's rows in {name}, read now:", retention.count(table, theirs))    print(f"the learner's rows in {name}, read by time travel:", retention.count(table, theirs, before[name]))summary = catalog.load_table("crm.learners").current_snapshot().summary# copy-on-write writes the rows it keeps again as new records, so this counts every other row of the fileprint("crm.learners, rows written again to delete one:", f"{int(summary['added-records']):,}")print("crm.learners, the commit records:", summary["erasure-request"])# snapshots of tables the plan deleted from (not rebuilt, not kept) that still return a row the erasure deletedholding = [(table, snapshot) for step in steps if step.column is not None           for table in [catalog.load_table(step.table)] for snapshot in table.snapshots()           if not step.kept and retention.count(table, retention.rows(step), snapshot.snapshot_id)]print("snapshots that still hold the rows the erasure deleted:", len(holding))print("of them current:", sum(snapshot == table.current_snapshot() for table, snapshot in holding))
출력python erase-learner.py
billing.payments, rows deleted: 0
crm.learners, rows deleted: 1
learning.enrollments, rows deleted: 2
learning.events, rows deleted: 19
learning.reviews, rows deleted: 1
support.tickets, rows deleted: 0
analytics.course_performance: rebuilt
analytics.learner_activity, rows deleted: 1
marketing.audience, rows deleted: 0
ai.review_corpus, rows deleted: 1
tables one row was deleted from: crm.learners, learning.reviews, analytics.learner_activity, ai.review_corpus
billing.payments, the learner's rows kept: 2
billing.payments, card numbers left in them: 0
the learner's rows in crm.learners, read now: 0
the learner's rows in crm.learners, read by time travel: 1
the learner's rows in learning.events, read now: 0
the learner's rows in learning.events, read by time travel: 19
crm.learners, rows written again to delete one: 4,999
crm.learners, the commit records: erasure-0001
snapshots that still hold the rows the erasure deleted: 6
of them current: 0

The erasure took the learner out of every table in the plan holding any. It deleted 19 of the learner's events, 2 enrollments, and one row each from crm.learners, learning.reviews, analytics.learner_activity, ai.review_corpus. It deleted nothing from support.tickets and marketing.audience, which held none, and it rebuilt analytics.course_performance.

billing.payments keeps the learner's 2 payments, with 0 card numbers left in them. Read now, crm.learners holds 0 rows for the learner. Read by time travel to the snapshot before the erasure, it returns 1, with name, email, phone and address, and learning.events returns all 19 of the learner's events the same way.

To delete one row of crm.learners, PyIceberg wrote the other 4,999 into a new file, as copy-on-write does, and the old file, with the learner in it, belongs to the snapshot before.

Across the plan's tables, 6 snapshots still hold the rows the erasure deleted, and 0 of them are current. That is what snapshots are for: a reader can go back to any of them. For an erasure, it means the delete took the learner out of the table but not out of storage.

Working rule: Carry out an erasure as row deletes in the plan's order, and record only a request ID in each commit, never a value of the person's. Treat the delete as the first of three steps: the snapshots before it still hold the person, and anyone allowed to time travel can read them until they're expired.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Expire snapshots by the table's own settings

마지막으로 변경된 판: 2026.11.27판

After the erasure's deletes, learner 3590's rows live on in the snapshots before them. The Iceberg spec says snapshots expire so that the data files they removed or replaced can be physically deleted (Iceberg table spec). Each table sets how in its properties (Iceberg configuration): gc.enabled allows garbage collection, such as expiring snapshots and removing orphan files; history.expire.min-snapshots-to-keep is how many snapshots to keep however old they are; and history.expire.max-snapshot-age-ms is the age at which the rest may go. In Iceberg's Java library, regularly expiring snapshots deletes unused data files (Iceberg maintenance).

PyIceberg 0.12.0 does less. Its table.maintenance.expire_snapshots() commits one change, which removes the snapshots from the table's metadata and deletes no file (source), though its documentation offers it to "clean up table metadata and reduce storage costs" (PyIceberg API). Nothing in it reads gc.enabled, and only its command-line tool reads the history.expire settings. An issue asks for expiry to delete files too (issue 2604). Two copies of crm.learners each have 3 snapshots, the load and two deletes. One copy has gc.enabled=false, the other history.expire.min-snapshots-to-keep=3, and each is expired two ways: by age with PyIceberg, older_than the current time, and with lib.retention.expire, which reads the two settings first.

expiry-ignores-table-settings.py Python 3.12.15 · duckdb 2.0.0 · openlineage-python 1.55.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · pyyaml 6.0.3 · sqlglot 30.33.0 통과
"""PyIceberg's snapshot expiry ignores two of the table's own settings, gc.enabled and min-snapshots-to-keep, so it expiressnapshots they would keep. The book's expiry reads both first, and the `left by PyIceberg's expiry` lines show the difference."""from datetime import datetime, timezonefrom pyiceberg.expressions import EqualTofrom lib import retentionfrom lib.catalog import open_catalogdef learners_with(settings: dict):    """crm.learners with three snapshots: the load, then two deletes."""    table = open_catalog(["crm.learners"]).load_table("crm.learners")    with table.transaction() as transaction:        transaction.set_properties(settings)    # two deletes, so there are snapshots from before them for the expiry to consider    for learner in (3590, 3591):        table.delete(EqualTo("learner_id", learner))    return tablefor settings in ({"gc.enabled": "false"}, {"history.expire.min-snapshots-to-keep": "3"}):    setting = ", ".join(f"{key}={value}" for key, value in settings.items())    table = learners_with(settings)    print(f"{setting}, snapshots:", len(table.snapshots()))    try:        print(f"{setting}, the book's expiry expires:", retention.expire(table))    except retention.RetentionError as error:        print(f"{setting}, the book's expiry refuses:", error)    # PyIceberg's expiry by age, as of now: it reads neither setting    table.maintenance.expire_snapshots().older_than(datetime.now(timezone.utc)).commit()    print(f"{setting}, snapshots left by PyIceberg's expiry:", len(table.snapshots()))
출력python expiry-ignores-table-settings.py
gc.enabled=false, snapshots: 3
gc.enabled=false, the book's expiry refuses: crm.learners has gc.enabled=false, which turns off garbage collection for the table
gc.enabled=false, snapshots left by PyIceberg's expiry: 1
history.expire.min-snapshots-to-keep=3, snapshots: 3
history.expire.min-snapshots-to-keep=3, the book's expiry expires: 0
history.expire.min-snapshots-to-keep=3, snapshots left by PyIceberg's expiry: 1

PyIceberg's expiry ignores both settings. It left 1 of the first table's 3 snapshots, and 1 of the second's. older_than expires every snapshot older than the time it's given except those a branch or tag points at, here only the current one.

The book's expiry refused the first table, crm.learners has gc.enabled=false, which turns off garbage collection for the table, and expired 0 snapshots of the second. An owner sets these properties for reasons the expiring code can't see, and in PyIceberg they are only advice.

For an erasure, both settings mean the job can't finish: a table that keeps a snapshot from before the delete still holds the person. A job that stopped at that table would already have deleted rows from the tables before it and left the rest unexpired, so the check belongs before the first delete. lib.retention.erase_everywhere runs lib.retention.blocked on every table in the plan first: garbage collection off, more than one snapshot to keep, or a branch or tag besides main. If any table fails, the job refuses to start and names every such table.

Here crm.learners has garbage collection off, and learning.events keeps three snapshots. Then the job and the scan run:

erasure-refuses-to-start.py Python 3.12.15 · duckdb 2.0.0 · openlineage-python 1.55.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · pyyaml 6.0.3 · sqlglot 30.33.0 통과
"""The erasure job checks every table in its plan before it changes any, and refuses to start when a table's own settingswould keep the learner. The scan still runs, from the traces the refusal carries, and finds the learner in the files."""from datetime import timedeltafrom lib import retentionLEARNER = 3590catalog, graph = retention.open_platform()# each setting stops expiry from removing the snapshot from before the delete: garbage collection off, or three snapshots keptfor name, settings in (("crm.learners", {"gc.enabled": "false"}),                       ("learning.events", {"history.expire.min-snapshots-to-keep": "3"})):    with catalog.load_table(name).transaction() as transaction:        transaction.set_properties(settings)# every table's current snapshot, to count the tables the job changesbefore = {name: catalog.load_table(name).current_snapshot().snapshot_id for name in retention.tables(catalog)}try:    # min_age of zero: one writer and nothing in flight, so no file needs a minimum age to be safe to sweep    steps, found, done = retention.erase_everywhere(catalog, graph, LEARNER, "erasure-0001", min_age=timedelta(0))except retention.ErasureRefused as refusal:    for name, why in refusal.tables.items():        print(f"the job refuses, because of {name}:", why)    found = refusal.found# a table the job changed has a new current snapshotprint("tables the job changed:", sum(catalog.load_table(name).current_snapshot().snapshot_id != snapshot                                     for name, snapshot in before.items()))report = retention.scan(catalog, found)print("tables whose files hold the learner:", sum(1 for _, holding in report.values() if holding))print("files holding the learner:", sum(holding for _, holding in report.values()))
출력python erasure-refuses-to-start.py
the job refuses, because of crm.learners: gc.enabled=false turns off garbage collection for the table
the job refuses, because of learning.events: history.expire.min-snapshots-to-keep=3 keeps the snapshot from before the delete
tables the job changed: 0
tables whose files hold the learner: 7
files holding the learner: 8

The job refuses. It names both tables, crm.learners because gc.enabled=false turns off garbage collection for the table, and learning.events because history.expire.min-snapshots-to-keep=3 keeps the snapshot from before the delete, and 0 tables changed.

The scan runs either way, from the traces the refusal carries, and finds the learner in 8 files across 7 tables. A person then decides with the tables' owners, rather than code overriding an owner's setting.

Working rule: Expire snapshots through one function of your own that reads gc.enabled and the history.expire settings before it expires anything, and refuses when garbage collection is off, because PyIceberg's expiry reads neither; check again at every PyIceberg release. Before an erasure deletes anything, check every table in its plan the same way, and refuse the whole erasure when one would keep the person. For an erasure, expire every snapshot older than the delete. For retention, expire by age, as history.expire.max-snapshot-age-ms says, measured on the clock, since snapshots carry real commit times.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Remove the files no snapshot references

마지막으로 변경된 판: 2026.11.31판

Once the old snapshots are expired, the files only they referenced are unreferenced. An unreferenced file, which Iceberg calls an orphan, is under the table's location but in no snapshot's metadata. Its Java library removes them in a separate action, and warns that removing orphan files with a retention interval shorter than the time expected for any write to complete is dangerous; its default interval is 3 days (Iceberg maintenance). PyIceberg 0.12.0 has no such action. Its release notes list none (release notes). The issue that asked for one was closed by the project's stale bot, marked not planned (issue 1200). Two pull requests that added one were closed without being merged (1958, 3358). Its only call that deletes data files is purge_table, which deletes the whole table (source).

So lib.retention removes them itself, from what the metadata tables PyIceberg exposes as table.inspect say a table references. lib.retention.referenced collects the metadata files, current and logged, every snapshot's manifest list, every manifest (a manifest lists data files, with each file's column statistics), every data and delete file live in any snapshot, and any statistics files. Every other file under the table's location is unreferenced, and lib.retention.sweep deletes the ones older than the minimum age its caller passes. governance/retention.toml sets that age to 72 hours, Java's default, and lib.retention.min_file_age reads it. After the erasure, the plan's tables are expired, swept with that age and then with none, and every file is checked for the learner:

sweep-unreferenced-files.py Python 3.12.15 · duckdb 2.0.0 · openlineage-python 1.55.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · pyyaml 6.0.3 · sqlglot 30.33.0 통과
"""After the erasure, expire the old snapshots, then remove the files no snapshot references. PyIceberg's expiry deletes nofile and has no orphan-file removal, so lib.retention.sweep does it with the inspect tables; the last lines show the manifest entries still holding the learner's email."""from datetime import timedeltafrom lib import retentionLEARNER = 3590catalog, graph = retention.open_platform()steps = retention.plan(catalog, graph, LEARNER)found = retention.traces(catalog, steps, LEARNER)retention.erase(catalog, steps, "erasure-0001")tables = [catalog.load_table(step.table) for step in steps]print("snapshots expired:", sum(retention.expire(table) for table in tables))print("files under the plan's tables:", sum(len(retention.files_under(table.location())) for table in tables))print("files no metadata references:", sum(len(retention.unreferenced(table)) for table in tables))print("files holding the learner, after expiry:", sum(held for _, held in retention.scan(catalog, found).values()))# the configured minimum age, 72 hours, from governance/retention.tomlprint("files swept with the configured minimum age:", sum(retention.sweep(t, retention.min_file_age()) for t in tables))# One writer, nothing in flight: no file is too young to remove, so the examples sweep with no minimum age.print("files swept with no minimum age:", sum(retention.sweep(table, timedelta(0)) for table in tables))print("files holding the learner, after the sweep:", sum(held for _, held in retention.scan(catalog, found).values()))for table in tables:    # every manifest entry, including those of deleted files, with the bounds it keeps for the email column    entries = table.inspect.entries()    for status, metrics in zip(entries["status"].to_pylist(), entries["readable_metrics"].to_pylist()):        bounds = metrics.get("email") or {}        # bounds are compared lowercased: the learner's email is typed in capitals in the manifest        kept = (bounds.get("lower_bound"), bounds.get("upper_bound"))        if any(text in bound.lower() for bound in kept if bound for text in found.texts):            print(f"{'.'.join(table.name()[-2:])}, manifest entry with status {status}, email bounds:",                  bounds["lower_bound"], "to", bounds["upper_bound"])
출력python sweep-unreferenced-files.py
snapshots expired: 8
files under the plan's tables: 100
files no metadata references: 28
files holding the learner, after expiry: 9
files swept with the configured minimum age: 0
files swept with no minimum age: 28
files holding the learner, after the sweep: 1
crm.learners, manifest entry with status 2, email bounds: ALEXA590@POST.EX to zofia.haase@exan

Expiry removes snapshots, not files. Of the files under the plan's tables, 28 are referenced by nothing, and 9 hold the learner. The sweep at the configured 72 hours deletes 0 unreferenced files, since every file was written seconds before. The examples pass an age of zero because one process writes their catalog. The sweep with no minimum age deletes all the unreferenced files, and 1 file still holds the learner: a manifest that the current snapshot of crm.learners references.

The spec says why: when a file is replaced or deleted, its manifest entry stores the snapshot in which the file was deleted and status 2 (deleted) (Iceberg table spec), and that entry keeps the deleted file's column statistics. By default, under the metrics mode truncate(16) (Iceberg configuration), those include each string column's smallest value, cut to 16 characters, and its largest, cut to 16 with the last character raised by one, so that it still bounds every value in the file (source). The deleted entry in crm.learners keeps the email bounds ALEXA590@POST.EX to zofia.haase@exan. The first is learner 3590's email, typed in capitals, which sorts before every other email on the platform. The second is learner 4998's, the platform's largest, whose 16th character, an m, became an n. No learner is safe from this: each data file's entry keeps the smallest and largest value of every column, so a table of many small files names many learners.

Working rule: Remove unreferenced files after every expiry, with a sweep of your own built on the inspect tables, since PyIceberg has none, and keep a minimum age of days in production so that a write in progress keeps its files. Use an age of zero only where a single process writes. Don't count a person erased because no data file holds them: the manifests may still hold their values.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Keep personal values out of manifests

마지막으로 변경된 판: 2026.11.27판

The sweep left the learner's email in a manifest, as a column bound. Iceberg lets a table choose, per column, what its manifests keep, with the property write.metadata.metrics.column.<name>: none keeps nothing, counts keeps value and null counts, truncate(n) adds bounds cut to n characters, and full adds whole bounds (Iceberg configuration). PyIceberg 0.12.0 looks the property up by the column's name when it writes a file (source).

Typed by hand, those properties would drift from the classifications. lib.retention.properties generates them from governance/metadata.toml and the [statistics] section of governance/retention.toml: none for every column classified personal or sensitive, and for every column nobody has classified, the same fail-closed default the access policy uses. It adds the history.expire settings from the rules' [snapshots] section. lib.retention.apply_properties sets them on every table and rewrites each table's data once, because a metrics mode applies only to the files written after it's set; expiry and a sweep then remove the files from before. Learner 4998, whose email is the largest bound in crm.learners' manifest, is the test case, erased on two platforms, one with default statistics and one with the generated properties:

statistics-off-for-personal-columns.py Python 3.12.15 · duckdb 2.0.0 · openlineage-python 1.55.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · pyyaml 6.0.3 · sqlglot 30.33.0 통과
"""Generates each table's properties from the classifications, so manifests keep no bounds on personal columns, then erasesthe learner whose email is the platform's largest, on a platform with the properties and on one without. The `files holding` lines are the proof."""from datetime import timedeltafrom lib import retentionLEARNER = 4998for statistics_off in (False, True):    catalog, graph = retention.open_platform(statistics_off)    label = "statistics off for protected columns" if statistics_off else "default statistics"    if statistics_off:        generated = retention.properties(catalog)        # the per-column metrics settings; the history.expire settings are not counted here        turned_off = [key for wanted in generated.values() for key in wanted if key.startswith(retention.METRICS)]        print("columns with statistics turned off:", len(turned_off))        # tables with no entry in governance/metadata.toml, which the generated properties still cover        unclassified = [name for name in generated if name not in retention.metadata.load()]        print("of them in tables nobody has classified:",              sum(key.startswith(retention.METRICS) for name in unclassified for key in generated[name]))        print("crm.learners, properties set:", len(generated["crm.learners"]))        for key, value in sorted(generated["crm.learners"].items()):            print(f"  {key} = {value}")    # crm.learners has one data file, so its one manifest entry keeps the table's email bounds    entry = catalog.load_table("crm.learners").inspect.entries()["readable_metrics"].to_pylist()[0]    print(f"{label}, crm.learners email bounds:", entry["email"]["lower_bound"], "to", entry["email"]["upper_bound"])    columns = retention.metadata.load()["crm.learners"].columns.values()    personal = [column.name for column in columns if column.classification == "personal"]    print(f"{label}, crm.learners personal columns:", len(personal))    with_bounds = sum(entry[name]["lower_bound"] is not None for name in personal)    print(f"{label}, of them with bounds in the manifest:", with_bounds)    steps, found, _ = retention.erase_everywhere(catalog, graph, LEARNER, "erasure-0002", min_age=timedelta(0))    print(f"{label}, files holding learner {LEARNER} after erasure, expiry and sweep:",          sum(held for _, held in retention.scan(catalog, found).values()))
출력python statistics-off-for-personal-columns.py
default statistics, crm.learners email bounds: ALEXA590@POST.EX to zofia.haase@exan
default statistics, crm.learners personal columns: 7
default statistics, of them with bounds in the manifest: 7
default statistics, files holding learner 4998 after erasure, expiry and sweep: 1
columns with statistics turned off: 24
of them in tables nobody has classified: 10
crm.learners, properties set: 9
  history.expire.max-snapshot-age-ms = 432000000
  history.expire.min-snapshots-to-keep = 1
  write.metadata.metrics.column.city = none
  write.metadata.metrics.column.date_of_birth = none
  write.metadata.metrics.column.email = none
  write.metadata.metrics.column.full_name = none
  write.metadata.metrics.column.notes = none
  write.metadata.metrics.column.phone = none
  write.metadata.metrics.column.street_address = none
statistics off for protected columns, crm.learners email bounds: None to None
statistics off for protected columns, crm.learners personal columns: 7
statistics off for protected columns, of them with bounds in the manifest: 0
statistics off for protected columns, files holding learner 4998 after erasure, expiry and sweep: 0

With default statistics, 1 file still holds learner 4998 after the erasure, expiry and sweep, through a raised upper bound. The manifest keeps bounds for 7 of the table's personal columns, and its email bounds are ALEXA590@POST.EX to zofia.haase@exan.

Turning statistics off for personal columns is what keeps learner 4998 out of the files. The email bounds are None to None, the manifest keeps bounds for 0 of the table's 7 personal columns, and 0 files hold the learner after the erasure, expiry and sweep.

The generated properties turn statistics off for 24 columns, 10 of them in marketing.audience and ai.review_corpus, the two tables that chapter 2 found with no metadata. crm.learners gets 9 properties: the two expiry settings, and none for each personal column.

The cost is pruning. Iceberg uses the bounds in manifests to skip files a query's filter can't match (Iceberg table spec), so without them, a query that filters on email reads every file. The platform filters and erases by learner_id, which is internal and keeps its statistics. counts is the other choice: it keeps the counts that help a planner, and no values. And because PyIceberg 0.12.0 keeps the property under the column's old name on a rename, leaving the new name without it, the properties are generated again on every schema change, as chapter 2 asks of every view of the metadata keyed by name.

Working rule: Generate per-column metrics properties from your classifications, none or counts for every personal, sensitive or unclassified column, and apply them when a table is created or, for an existing table, with one rewrite followed by expiry and a sweep. Keep statistics on the ID columns you filter and erase by. Generate the properties again after every schema change.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Prove the erasure by reading every file

마지막으로 변경된 판: 2026.11.31판

Each step so far removed something the one before left behind, and left something of its own: the delete, the expiry, the sweep and the statistics settings. That is the case for checking the result rather than trusting the steps. The European Data Protection Board's report on how controllers handle erasure, adopted in February 2026, found backups, and anonymisation used in place of deletion, among the weak points, and recommends that controllers "Verify that erasure has been carried out and be able to demonstrate such erasure" (EDPB, 2026).

lib.retention.scan reads every file under the catalog's warehouse, each with its own format's reader, and looks for the learner's traces. lib.retention.traces notes the traces before the erasure: the IDs of every row the plan deletes, by column, and the first 15 characters, lowercased, of each identifying value. Fifteen, because a manifest keeps a largest value's first 15 characters unchanged and raises the 16th by one, so a search for 16 misses a person whose value is a file's largest, as learner 4998's email is. A Parquet file is read as rows. A manifest or manifest list, both Avro, is read record by record with PyIceberg's Avro reader: every string in it, bounds included, and the bounds of each ID column, decoded by the schema the manifest carries. A metadata file is read as text. In a table an exception keeps, the learner's IDs are expected, so there the scan looks only for values, including those of the columns the exception erased. lib.retention.erase_everywhere runs the whole job: plan, note the traces, check every table, erase, expire, sweep. On the platform with the generated properties, the whole job runs and ends with the scan:

verify-erasure.py Python 3.12.15 · duckdb 2.0.0 · openlineage-python 1.55.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · pyyaml 6.0.3 · sqlglot 30.33.0 통과
"""Runs the whole erasure job on the platform with statistics off for protected columns, then scans every file under thewarehouse. The `files holding the learner` line is the proof; the rest is evidence of IDs and counts, never the learner's values."""from datetime import timedeltafrom lib import retentionLEARNER, REQUEST = 3590, "erasure-0001"catalog, graph = retention.open_platform(statistics_off=True)# min_age of zero: one writer, so nothing is in flight that a sweep could takesteps, found, done = retention.erase_everywhere(catalog, graph, LEARNER, REQUEST, min_age=timedelta(0))report = retention.scan(catalog, found)for table, (files, holding) in report.items():    print(f"{table}: {files} files read, {holding} holding the learner")print("request:", REQUEST)print("tables visited:", len(steps))# each table the job deleted from has a count of rows; the one it reran has 'rebuilt' insteadprint("rows deleted:", sum(rows for rows in done.values() if rows != "rebuilt"))print("tables rebuilt:", ", ".join(table for table, rows in done.items() if rows == "rebuilt"))print("tables kept under an exception, columns erased:",      "; ".join(f"{step.table}, {', '.join(step.cleared)}" for step in steps if step.kept))# every snapshot but the current one: the ones a reader can still time travel toprint("snapshots a reader can still time travel to:",      sum(len(catalog.load_table(step.table).snapshots()) - 1 for step in steps))print("files no metadata references:",      sum(len(retention.unreferenced(catalog.load_table(name))) for name in retention.tables(catalog)))print("tables missing their generated properties:", ", ".join(retention.missing_properties(catalog)))print("files read:", sum(files for files, _ in report.values()))print("files holding the learner:", sum(holding for _, holding in report.values()))
출력python verify-erasure.py
ai.review_corpus: 11 files read, 0 holding the learner
analytics.course_performance: 5 files read, 0 holding the learner
analytics.learner_activity: 11 files read, 0 holding the learner
billing.payments: 12 files read, 0 holding the learner
crm.instructors: 8 files read, 0 holding the learner
crm.learners: 11 files read, 0 holding the learner
learning.courses: 8 files read, 0 holding the learner
learning.enrollments: 11 files read, 0 holding the learner
learning.events: 11 files read, 0 holding the learner
learning.reviews: 11 files read, 0 holding the learner
marketing.audience: 8 files read, 0 holding the learner
support.tickets: 8 files read, 0 holding the learner
request: erasure-0001
tables visited: 10
rows deleted: 25
tables rebuilt: analytics.course_performance
tables kept under an exception, columns erased: billing.payments, card_number
snapshots a reader can still time travel to: 0
files no metadata references: 0
tables missing their generated properties: analytics.course_performance
files read: 115
files holding the learner: 0

The scan finds the learner in 0 of the 115 files it reads, and no reader can time travel to the learner, since 0 older snapshots remain, and 0 files are unreferenced. The lines after the per-table counts are the evidence: the request's ID, the tables visited, the rows deleted, the table the job rebuilt, the table an exception keeps and the column erased from it, billing.payments, card_number, with the reason in governance/retention.toml, and the scan's counts. They name no value of the learner's, so keeping them puts none back, which chapter 8 relies on when it writes them to the audit log.

One line is a warning: analytics.course_performance lacks its generated properties, because lib.pipelines.run dropped the table and created it again without them. That table has no personal columns. The next table a pipeline rebuilds might have them, and the scan would then report its manifests' bounds as a failed erasure, so the check belongs after every pipeline run.

IDs can stay in a manifest too, since the ID columns keep their statistics. An erased ID that was a file's smallest or largest, such as learner 5000's, stays in the deleted entry's bounds, and the scan reports it. One more commit to the table, followed by an expiry and a sweep, removes it, because PyIceberg's next append leaves out a manifest that holds only deleted files (source).

The scan covers the warehouse only. Exports, backups, the source systems and logs outside it can hold the learner too, and the same traces can be searched for in each the platform can read.

Working rule: End every erasure with a scan of every file the platform stores, for the person's IDs and identifying values, read with each format's own reader, and keep its result, counts and IDs only, as the evidence. Search for as much of each value as every bound keeps unchanged, which is one character less than the truncation length. Treat any file that still holds the person as a failed erasure, not a warning. Search the stores outside the warehouse that you control, and list in the record the ones you can't search.

운영 환경에서 무엇이 잘못되는가

마지막으로 변경된 판: 2026.11.27판

삭제가 성공했다는 응답은 데이터가 실제로 사라졌을 때와 여전히 저장소에 남아 있을 때 모두 똑같아 보이며, 삭제가 실패하는 방식이 바로 이것이다. 여기서 다루는 첫 번째 실패는 이미 끝난 삭제를 되돌려 놓는다.

삭제된 학습자가 되돌아온다

마지막으로 변경된 판: 2026.11.27판

CRM의 동기화 외에도 웨어하우스는 매일 밤 애플리케이션의 내보내기 파일로 crm.learners 전체를 다시 적재하는데, 삭제는 웨어하우스에서만 실행되었다. 계획이 말하는 모든 곳에서 학습자 3590을 삭제한 다음, 야간 재적재와 이 테이블을 읽는 파이프라인을 실행해 보자.

erased-learner-returns.py Python 3.12.15 · duckdb 2.0.0 · openlineage-python 1.55.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · pyyaml 6.0.3 · sqlglot 30.33.0 통과
"""An erased learner comes back: the nightly reload of crm.learners from the application's export brings the rows back, andthe pipelines rebuild from them. A check against the erasure register catches the rows."""from datetime import timedeltafrom lib import pipelines, retentionLEARNER, REQUEST = 3590, "erasure-0001"catalog, graph = retention.open_platform()retention.erase_everywhere(catalog, graph, LEARNER, REQUEST, min_age=timedelta(0))register = [retention.register_entry(REQUEST, LEARNER)]      # the request's ID and a keyed hash of the learner's IDprint("the erasure register's entry:", register[0]["request"], register[0]["learner"])learners = catalog.load_table("crm.learners")print("the learner's rows in crm.learners after the erasure:", retention.count(learners, retention.rows_of([LEARNER])))# the nightly reload: the application's export still holds the learner, since nobody erased it therelearners.overwrite(retention.crm_export())# the pipelines that read crm.learners rebuild from the reloaded tablefor name in ("learner_activity", "marketing_audience"):    pipelines.run(catalog, name)for table in ("crm.learners", "analytics.learner_activity", "marketing.audience"):    print(f"the learner's rows in {table} after the nightly run:",          retention.count(catalog.load_table(table), retention.rows_of([LEARNER])))# hashes each learner_id in every table and looks it up in the register, so no learner's ID is printedfor table, rows in retention.erased_rows(catalog, register).items():    print(f"the check against the register, rows of erased learners in {table}:", rows)
출력python erased-learner-returns.py
the erasure register's entry: erasure-0001 c25d8a8b12426596f0c0b1ebfb890246b42ea535791f07256efd16fc6c2cb84b
the learner's rows in crm.learners after the erasure: 0
the learner's rows in crm.learners after the nightly run: 1
the learner's rows in analytics.learner_activity after the nightly run: 1
the learner's rows in marketing.audience after the nightly run: 0
the check against the register, rows of erased learners in analytics.learner_activity: 1
the check against the register, rows of erased learners in crm.learners: 1

웨어하우스에서만 한 삭제는 유지되지 않는다. 삭제 직후 crm.learners에는 이 학습자의 행이 0개 있고, 야간 실행 후에는 다시 1개가 있으며, 이 테이블로 다시 만든 analytics.learner_activity에는 1개가 있다. marketing.audience이 비어 있는 것은 학습자의 동의가 철회된 상태로 돌아오고, 이 테이블이 조인하는 수강 등록 정보가 삭제되었기 때문일 뿐이다.

이를 잡아내는 검사는 삭제 대장을 둔다. 대장에는 요청마다 요청 ID와 삭제된 학습자 ID의 키 해시(HMAC-SHA256)만 기록하고 다른 것은 기록하지 않는다. 키는 삭제 작업의 비밀 값이며, 6장의 시행 계층이 쓰는 가명화 키처럼 보관하되 서로 다른 키를 쓴다. 키를 가진 사람은 모든 학습자 ID를 해시하여 대장이 가리키는 사람을 찾아낼 수 있기 때문이다. 적재, 복원, 재구축을 마칠 때마다 lib.retention.erased_rows은 해당 열이 있는 모든 테이블에서 각 learner_id를 해시하여 대장에서 조회한다. 따라서 대장에 누구의 ID도 담지 않고 복원이나 백필을 검사할 수 있다. 이 검사는 analytics.learner_activity과 crm.learners에서 학습자를 찾아내고, 예외로 행을 보존하는 billing.payments은 제외한다. 8장의 감사 로그에 남는 삭제 기록에는 같은 요청 ID와 건수만 있고 학습자는 없으므로, 요청과 학습자가 만나는 곳은 해시 형태의 대장뿐이다. ID의 키 해시는 익명화된 데이터가 아니라 가명처리된 데이터로 취급한다.

작업 규칙: 원본 시스템에서 먼저, 또는 같은 요청 안에서 삭제하고, 삭제된 ID의 키 해시 대장을 두어 모든 적재가 이를 기준으로 걸러 내고 모든 실행이 이를 검사하게 하며, 키는 데이터와 분리된 비밀 값으로 보관한다. 삭제된 ID가 있는 행은 유출과 마찬가지로 사고로 취급한다.

그 밖의 실패

마지막으로 변경된 판: 2026.11.27판
  • 오래된 스냅샷과 파일에 "삭제된" 데이터가 남는다. 보존 작업이나 삭제 작업이 삭제 단계에서 멈추면 타임 트래블로 모든 데이터를 여전히 읽을 수 있고, PyIceberg에서는 만료 뒤에도 파일이 남는다. 만료와 정리를 같은 작업에서 실행한 다음 스캔한다.
  • 다른 엔진이 merge-on-read 방식으로 삭제한다. PyIceberg는 다른 엔진이 기록한 삭제 벡터를 읽는다(릴리스 노트). 이런 방식으로 삭제된 행은 컴팩션이 데이터 파일을 다시 쓸 때까지 해당 데이터 파일에 남아 있고, 삭제 파일에도 그 값이 남을 수 있다. 두 종류의 삭제 파일 모두 삭제하는 행의 값을 인코딩할 수 있기 때문이다(Iceberg 테이블 명세). 만료와 정리에 앞서 해당 파일을 컴팩션하고, 삭제 파일도 함께 스캔한다.
  • 백업에는 정리 작업이 지우는 모든 데이터가 남는다. 백업은 EDPB 보고서가 지목한 취약 지점 가운데 하나다. 백업을 책임지는 담당자와 함께 백업을 어떻게 삭제하거나 만료시킬지 정하고, 그 내용을 요청마다 기록한다.
  • 아무도 삭제하지 않은 파생 테이블. 리니지를 전송하지 않는 작업은 계획이 볼 수 없는 사본을 기록한다. 4장의 계측되지 않은 내보내기가 그러한 예다. 삭제를 수행하기 전에 매번 lib.lineage.unaccounted를 실행한다.
  • 다시 만든 테이블은 속성을 잃는다. 테이블을 삭제하고 다시 만드는 파이프라인은 생성된 통계 설정을 잃고, 다음 삭제 때 매니페스트에 값이 남는다. 실행할 때마다 속성을 적용하거나, 속성을 지정해서 테이블을 만든다.
  • 이름을 바꾼 열은 설정을 잃는다. PyIceberg에서는 메트릭 속성이 열의 이전 이름으로 남으므로, 이름을 바꾸면 새 이름에는 속성이 없다. 스키마를 바꿀 때마다 속성을 다시 생성한다.
  • 잘못된 날짜를 기준으로 센 보존 기간. "종료 후"를 뜻하는 규칙이 개시일부터 세면 너무 일찍 삭제하고, 적재일부터 세면 너무 늦게 삭제한다. 규칙이 뜻하는 날짜를 저장한다.

이 장에서 결정한 것

마지막으로 변경된 판: 2026.11.27판
  • 보존 규칙은 설정이다. 규칙은 시계가 아니라 작업에 주어진 날짜를 기준으로 적용한다. 각 기간은 플랫폼이 직접 정하며 규칙에 보관한다. 티켓 테이블에는 closed_at가 없으므로, 종료된 티켓은 생성 시점부터 기간을 센다.
  • 동의는 정책이 쿼리 시점에 읽는 속성이다. 동의를 철회해도 삭제되는 것은 없으며, 동의 필터로 만든 테이블은 다시 만든다.
  • 삭제는 카탈로그와 계보를 바탕으로 계획한다. learner_id 열이 있는 모든 테이블을 대상으로 하고, 그다음 계보가 닿는 모든 테이블을 대상으로 한다.
  • 삭제의 예외는 법무팀이 정한다. 예외는 사유와 함께 governance/retention.toml에 기록하며, 코드는 해당 테이블의 보존 규칙이 끝낼 때까지 법무팀이 정한 내용을 유지한다.
  • 커밋에는 요청 ID와 규칙 이름을 기록하며, 개인의 값은 기록하지 않는다.
  • 이 책의 만료 처리는 각 테이블의 설정을 읽는다. PyIceberg의 만료 처리는 그렇게 하지 않는다. 삭제는 계획에 포함된 모든 테이블을 확인한 뒤에야 무엇이든 지운다.
  • 이 책의 정리 작업은 참조되지 않는 파일을 제거하며, 운영 환경에서는 최소 보존 기간을 72시간으로 한다.
  • 매니페스트에는 보호 대상 열의 값을 남기지 않는다. 메트릭 모드는 none이며, 분류에서 생성한다.
  • 모든 삭제는 모든 파일에 대한 스캔으로 끝난다. 스캔은 ID와 각 식별 값의 15자를 찾으며, 그 결과 건수가 증거가 된다.
  • 삭제 대장에는 삭제된 각 ID의 키 해시를 보관하며, 적재, 복원, 재구축이 끝날 때마다 이를 확인한다. 보존과 삭제는 무엇이 남아 있는지로 검증한다. 삭제마다 수행하는 스캔, 해시 대장, 그리고 작업에 주어진 날짜부터 세는 규칙이 그 수단이다. 스캔이 살펴보지 않은 곳에 데이터가 남아 있어도 스캔은 통과할 수 있으므로, 적재, 복원, 재구축 뒤마다 대장을 다시 확인한다.

이 판의 이 장

2026.11.31판예제 통과 2026년 11월 19이 장에서 11개 예제개 중 11개가 통과한다

영어판 2026.11.31판을 번역한 것이다.

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

10장 중 7장: 보존, 동의, 삭제

  1. Keep retention rules in a reviewed file
  2. 행 삭제로 만료된 행 지우기
  3. 쿼리가 실행되는 곳에서 동의를 읽는다
  4. 계보에서 삭제 계획 세우기
  5. Erase the rows the plan lists
  6. Expire snapshots by the table's own settings
  7. Remove the files no snapshot references
  8. Keep personal values out of manifests
  9. Prove the erasure by reading every file
  10. 운영 환경에서 무엇이 잘못되는가
  11. 삭제된 학습자가 되돌아온다
  12. 그 밖의 실패
  13. 이 장에서 결정한 것

맨 위로 돌아가기전체 장