保持、同意、消去

読了まで約81 分分、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 はデータファイルには手を加えず、その隣に削除ファイルを書き込む。仕様には削除ファイルが二種類ある。一つは位置削除で、行をデータファイルとその中の位置で示す(バージョン 3 以上のテーブルでは削除ベクタ)。もう一つは等価削除で、行を一つ以上の列の値で示す(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 個が期限切れになる。保持期間ジョブは、古いスナップショットが期限切れになり、どのスナップショットからも参照されないファイルが削除されるまで完了しない。これは消去要求への対応に必要な後始末と同じである。

実践ルール: 保持期間は Iceberg の行削除として、ルールを一つずつ適用し、ルールと日付を各コミットのスナップショットサマリーに記録する。ジョブは、ある日付に対して冪等にする。大きなテーブルは、ルールが起算に使う列でパーティション分割し、削除でファイルを書き直さずにファイルごと破棄できるようにする。PyIceberg でそれを書き込むには、エクストラの pyiceberg-core をインストールする。ジョブが完了したとみなすのは、古いスナップショットが期限切れになり、そのファイルが削除された後だけである。

最終変更:版2026.11.27

データ保持は、行を経過期間に基づいて削除する。同意は、その行を誰が利用してよいかを変える。同意の撤回は消去の要求と同じ出来事ではないため、プラットフォームのコードはこの二つを別の経路として扱う。EU の一般データ保護規則(GDPR)の第 7 条第 3 項は次のように定めている。「データ主体は、いつでも同意を撤回する権利を有する。同意の撤回は、撤回前に同意に基づいて行われた処理の適法性に影響を及ぼさない。」(GDPR)。同規則の第 17 条第 1 項(b)は、同意の撤回を消去の根拠の一つとしているが、それは処理の他の法的根拠が残っていない場合に限られる。コードの上では、撤回は一つの属性を変更し、消去は行を削除する。

このプラットフォームでは、同意はアクセスポリシーが読むデータの属性である。これは第 5 章で設定したとおりであり、マーケティングの行フィルタは marketing_consent が true の学習者だけを残し、コースアシスタントの行フィルタは、投稿者の ai_training_consent が true であるレビューだけを残す。したがって、撤回のためにポリシーを変更する必要はない。学習者がアカウントを管理するアプリケーションである CRM が新しい値を crm.learners に同期し、マーケティングが次に実行するクエリは、第 6 章で構築したすべてのクエリを書き換える適用層を通って、学習者を一人少なく返す。

学習者 3590 のマーケティング同意を撤回し、撤回前、撤回後、およびマーケティングのパイプラインが再実行された後のそれぞれについて、マーケティングから見える内容とテーブルの保持内容を読む。

撤回は次のクエリで有効になり、何も削除しなかった。マーケティングから見える学習者は、撤回前は 1,861 人で学習者 3590 を含み、撤回後は 1,860 人で学習者 3590 を含まない。マーケティングの行フィルタは [{"column": "marketing_consent", "equals": true}, {"column": "status", "equals": "active"}] のままであり、crm.learners は引き続き 5,000 行を保持している。削除されたものはなく、学習者のアカウント、受講登録、履歴は以前のままである。

問題はコピーにある。marketing.audience は、マーケティングのパイプラインが毎晩作成するリストであり、作成時に同意フィルタを適用する。ポリシーはマーケティングに、このテーブルを独自の同意フィルタなしで与えている。撤回後も、このテーブルには学習者 3590 の行が 1 行残っている。誰かがテーブルの列を分類するまでは、ポリシーはその列をすべての読み手に対して秘匿しており、そのため問題は表に出ない。第 4 章が提案するように分類が行われると、次の作成より前にこのテーブルから送られたキャンペーンは、拒否した人に届いてしまう。パイプラインが再び実行されて初めて、件数は 0 に減る。学習用コーパスも同意フィルタを使って作られるため、第 9 章では、学習に使う前に、各ビルドを現時点の同意に照らして確認する。

真偽値の列は、伝える情報も少なすぎる。ai_training_consent は、プラットフォームが尋ねる前に登録したすべての人について null であり、false は拒否と撤回のどちらも意味しうる。W3C コミュニティグループの報告書であり標準ではない Data Privacy Vocabulary は、同意がとりうる状態に名前を付けており、付与、拒否、撤回、期限切れ、不明などがある(DPV 2.3)。

実践ルール: 同意はクエリが実行される場所に置く。つまり、学習者が使うシステムが最新に保つ一つのテーブルに置き、ポリシーが行フィルタとして読む。こうすれば、撤回は次のクエリを変え、何も削除しない。プラットフォームの法務担当者が、撤回も消去の根拠になると判断した場合は、消去の経路にも送る。同意フィルタを使って作成したテーブルは、同意が変わるたびに再作成するか、その読み手に同じフィルタを適用する。各同意は状態と変更時刻として記録し、ポリシーが読む真偽値の属性はそこから導出する。その際、不明は付与されていないものとして数える。

リネージから消去を計画する

最終変更:版2026.11.27

同意の撤回が変更するのは属性一つだけであるが、消去は本人のデータをあらゆる場所から見つけ出さなければならない。GDPR 第17条第1項は、列挙された根拠のいずれかに該当する場合に、本人が不当な遅滞なく自己のデータを消去させる権利を認めている(GDPR)。プラットフォームは、請求がすべてのコピーに及ぶものとして扱う。そのため最初の仕事は、本人のデータがどこにあるかを二つの部分に分けて一覧にすることであり、これは工学上の問いである。学習者の ID を持つ元のテーブルはカタログから得られる。第2章は、learner_id を持つテーブルは分類にかかわらずすべて、あらゆる消去の対象に含めると決めた。それらから作られたテーブルはリネージから得られる。第4章で述べた列グラフの探索を各元テーブルから実行すれば、その行が形作ったすべてのテーブルに到達できる。

一部のデータは残る。同じ規則の第17条第3項は、処理が必要である限りにおいて消去が適用されない場合を定めている。5つの号のうちには、管理者が服する EU 法または加盟国法上の法的義務を遵守するための処理がある(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 に挙げられた列は直ちに消去される。ここではカード番号の全桁がそれにあたり、プラットフォームのメタデータは、これを「まったく保存すべきでない」としている。lib.retention.exceptions は、理由のない例外と、どの規則にも終了されないテーブルについての例外を拒否する。

派生テーブルを見つけることと、その中の学習者の行を見つけることは同じではない。lib.retention.plan は、探索が到達した各テーブルに入るリネージのエッジを調べる。調べるのは、学習者の ID、またはレビューなど学習者の行の ID から、そのまま複製された列、すなわち OpenLineage の用語でいう IDENTITY エッジである。それがあれば、計画はその列で削除する。なければ、学習者の行はそのテーブルを形作っただけであり、計画は元データを消去した後にそのテーブルのジョブを再実行する。計画は、撤回から数週間後に請求が見いだすままのプラットフォームを読む。crm.learners には学習者 3590 の撤回された同意が記録されており、分析用、マーケティング用、AI 用のテーブルを作る第4章の4本のパイプラインは、その後に実行され、リネージも記録されている。

学習者 3590 の計画は、手順ごとに1行を出力する。各行には、テーブルと、そこで行う処理が示される。

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 件の支払いを保持する。手順は行ではなく列とリネージで決まるため、計画には学習者の行を一つも持たないテーブルが2つ載る。support.tickets は、学習者 3590 がチケットを一度も開いていないためであり、marketing.audience は、撤回の後にパイプラインが再構築したため、学習者の行が 0 件である。ai.review_corpus には learner_id がまったくないが、リネージによれば、その review_id は learning.reviews.review_id の IDENTITY コピーである。そのため計画は、その ID で学習者のレビューを削除する。analytics.course_performance にはコースごとの件数と平均しかないので、計画は消去後の元データからこれを再構築する。再構築のコストはパイプライン1回分の実行であるから、かつて学習者を数えた平均が今も本人のデータにあたるかどうかを、コードが判断する必要はない。

テキストが、計画の削除しない行の中で人物を名指しすることがある。別の学習者のチケットなどがその例である。この例は、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.

どのスナップショットからも参照されないファイルを削除する

最終変更:版2026.11.31

古いスナップショットを失効させると、それらだけが参照していたファイルは参照されないファイルになる。参照されないファイルは、Iceberg では孤立ファイル(orphan)と呼ばれ、テーブルの場所の下にあるが、どのスナップショットのメタデータにも含まれていない。Iceberg の Java ライブラリは、これらを別のアクションで削除する。そして、書き込みの完了に要すると見込まれる時間より短い保持間隔で孤立ファイルを削除するのは危険であると警告しており、既定の間隔は 3 日である(Iceberg maintenance)。PyIceberg 0.12.0 には、そのようなアクションはない。リリースノートにも載っていない(release notes)。追加を求めた issue は、プロジェクトの stale bot によって、計画なし(not planned)として閉じられた(issue 1200)。追加を試みた 2 件のプルリクエストも、マージされないまま閉じられた(1958、3358)。PyIceberg でデータファイルを削除する呼び出しは purge_table だけであり、これはテーブル全体を削除する(source)。

そこで lib.retention は、PyIceberg が table.inspect として公開するメタデータテーブルから、テーブルが何を参照しているかを求め、自前で孤立ファイルを削除する。lib.retention.referenced は、次のものを集める。現行およびログに残るメタデータファイル、すべてのスナップショットのマニフェストリスト、すべてのマニフェスト(マニフェストはデータファイルを列挙し、各ファイルの列統計を持つ)、いずれかのスナップショットで有効なすべてのデータファイルと削除ファイル、そして統計ファイルである。テーブルの場所の下にあるそれ以外のファイルはすべて参照されないファイルであり、lib.retention.sweep は、呼び出し側が渡す最小経過時間より古いものを削除する。governance/retention.toml はこの時間を Java の既定値と同じ 72 時間に設定し、lib.retention.min_file_age がそれを読み込む。消去の後、計画の対象テーブルを失効させ、その時間を指定して孤立ファイルを削除し、続けて時間を指定せずに削除し、すべてのファイルについて学習者の値が残っていないかを確認する。

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

失効が取り除くのはスナップショットであり、ファイルではない。計画の対象テーブルの下にあるファイルのうち、28 個はどこからも参照されておらず、9 個に学習者の値が含まれている。設定された 72 時間での削除では、参照されないファイルが 0 個削除される。すべてのファイルが数秒前に書かれたためである。例では経過時間に 0 を渡している。例のカタログには 1 つのプロセスしか書き込まないからである。最小経過時間を指定しない削除では、参照されないファイルがすべて削除されるが、それでも 1 個のファイルに学習者の値が残る。crm.learners の現行スナップショットが参照するマニフェストである。

その理由は仕様に書かれている。ファイルが置き換えられるか削除されると、そのマニフェストエントリには、ファイルが削除されたスナップショットとステータス 2(deleted)が記録され(Iceberg table spec)、このエントリは削除されたファイルの列統計を保持し続ける。既定のメトリクスモード truncate(16) では(Iceberg configuration)、この統計には、各文字列列の最小値(16 文字に切り詰めたもの)と最大値(16 文字に切り詰め、最後の文字を 1 つ繰り上げたもの)が含まれる。繰り上げるのは、その値がファイル内のどの値に対しても上限であり続けるようにするためである(source)。crm.learners の削除済みエントリは、メールアドレスの上下限 ALEXA590@POST.EX to zofia.haase@exan を保持している。前者は学習者 3590 のメールアドレスを大文字で入力したもので、プラットフォーム上の他のどのメールアドレスよりも前に整列される。後者は学習者 4998 のもので、プラットフォームで最大の値であり、その 16 文字目の m が n に繰り上げられている。この問題を免れる学習者はいない。各データファイルのエントリはすべての列の最小値と最大値を保持するため、小さなファイルが多数あるテーブルでは、多数の学習者の値が現れる。

実践ルール: 失効のたびに、参照されないファイルを削除する。PyIceberg にはその機能がないため、inspect テーブルに基づく自前の削除処理を用意する。本番環境では日単位の最小経過時間を保ち、書き込み中のファイルが残るようにする。経過時間 0 を使うのは、書き込むプロセスが 1 つだけの場所に限る。どのデータファイルにも含まれていないからといって、ある人物が消去されたと数えてはならない。マニフェストにその値がまだ残っている可能性がある。

この部分はまだ翻訳されていないため、英語で表示している。

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 では、期限切れ処理の後もファイルが残る。期限切れ処理とスイープを同じジョブで実行し、その後にスキャンを行う。
  • 別のエンジンがマージオンリードで削除する。 PyIceberg は、他のエンジンが書き込む削除ベクトルを読み取る(リリースノート)。この方法で削除された行は、コンパクションがデータファイルを書き換えるまでそのデータファイルに残る。さらに、2種類の削除ファイルはどちらも削除した行の値を符号化できるため、削除ファイルに値が残ることがある(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. どのスナップショットからも参照されないファイルを削除する
  8. Keep personal values out of manifests
  9. Prove the erasure by reading every file
  10. 本番環境で何が問題になるか
  11. 消去した学習者が戻ってくる
  12. その他の失敗
  13. この章で決めたこと

ページの先頭に戻るすべての章