讓快照過期並移除未被參照的檔案
閱讀約需 40 分鐘 分鐘,8 節 中共有 3 個範例。
讀完本章後,你將能在三種格式中各自讓舊快照過期,移除只有這些快照仍列出的資料檔,並證明讀取已過期的快照會失敗。
壓實(Compaction)也會留下同類的舊檔案:重寫後被取代的檔案仍留在磁碟上,因為較舊的快照仍列出它們。本章會讓 wiki.pageviews_hourly 的舊快照過期,接著刪除不再被任何快照列出的檔案。本章所有範例都使用更正章節中第 02 小時的更正,並以覆寫該小時的方式寫入,而不是採用該章後面一節的 upsert,因為覆寫在每種格式中恰好只會留下一個舊檔案。這些舊檔案會一直保留,直到它們的快照過期且檔案被移除為止。這兩個步驟都會在每種格式中執行,而且每個步驟都以計數來檢查,不必倚賴一份需要你自行信任的清單。
快照讓檔案保持有效
每個快照都會記錄該次提交時,資料表由哪些資料檔案組成。快照指向什麼說明各種格式如何儲存這份清單。本章要掌握的重點是:取代資料列的提交並不會刪除被取代的檔案。它會為取代用的資料列寫入檔案,而提交之前的快照仍然列出舊檔案,因此時間旅行(time travel)得以持續運作。只有在你保留的所有快照都不再列出某個資料檔案時,該檔案才會成為孤立檔案。
在每一種格式中,移除檔案都分為兩個步驟:先過期(expiry),再清理(cleanup)。Iceberg 的維護頁面給出相同的順序:過期會從中繼資料中移除快照,因此時間旅行無法再存取這些快照,而「在資料檔案不再被任何可能用於時間旅行或回復的快照參照之前,不會被刪除」(Apache Iceberg, maintenance)。過期之後,清理會刪除所有剩餘快照都未列出的檔案。
wiki.pageviews_hourly先進行三次每小時附加(append),接著以覆寫該小時的方式更正 02 時的資料。每次附加寫入一個檔案。覆寫則寫入一個包含更正後 02 時資料列的檔案,並把舊檔案從目前的快照中移除。當初附加舊檔案的那個快照仍然列出它。在該快照過期之前,舊檔案不能被刪除,否則會破壞對該快照的時間旅行。以 upsert 更正某個小時展示了寫入同一項更正的另一種方式,它同樣會留下這類舊檔案。
每種格式各有自己的過期呼叫與清理呼叫。下表列出這些呼叫,本章其餘部分對每種格式都依相同順序說明。
| 格式 | 過期呼叫 | 過期會刪除檔案嗎? | 清理呼叫 |
|---|---|---|---|
| Iceberg (pyiceberg) | expire_snapshots().by_ids(...) |
否 | 函式庫中沒有:自行計數並移除檔案 |
| Delta Lake (deltalake) | vacuum 中的版本保留設定 |
會,由 vacuum 執行 |
vacuum |
| DuckLake | ducklake_expire_snapshots |
否 | ducklake_cleanup_old_files,接著 ducklake_delete_orphaned_files |
實用原則: 先決定讀取者可能仍需要哪些快照或版本,並在移除任何檔案之前讓其餘的過期。絕不移除仍被你保留的快照列出的檔案,並且在刪除之前先以計數確認這一點。
使用 pyiceberg 讓快照過期
在 pyiceberg 0.12.0 中,table.maintenance.expire_snapshots() 接受快照 ID:以 by_ids 傳入清單,或以 by_id 傳入單一 ID;也可以使用 older_than 時間戳記。它沒有「保留最後 N 個快照」的參數。本章依提交順序挑選 ID,如同該案例的做法:三次每小時的附加寫入就是前三個快照。ID 本身是隨機的 64 位元數字,因此範例改以「snapshot 1」、「snapshot 2」等標籤依相同順序輸出。
覆寫會新增兩個快照,而不是一個。pyiceberg 先寫入一個刪除快照,移除舊檔案,再寫入一個附加快照,加入修正後的資料列。快照 4 是刪除,快照 5 是附加。因此讓這三個附加快照過期後,覆寫仍會保留,而這正是範例所檢查的狀態。
過期的呼叫不會刪除任何資料檔案,所以範例自行在前後計數:快照所列出的不重複檔案數,以及磁碟上沒有任何快照列出的檔案數。請留意最後一項計數,被取代的檔案會在這裡出現:
1"""Expire the three append snapshots by ID, then count what the snapshots still reference. The point rests on the2line that counts unreferenced data files on disk: expiry removes metadata, and the file the overwrite replaced stays."""34from lib.lakehouse import (5 ICEBERG_ID,6 create_iceberg_table,7 hour_corrections,8 hour_filter,9 new_warehouse,10 orphan_data_files,11 read_cut_hour,12 scan_arrow,13 snapshot_labels,14)151617def referenced_files(table):18 """Distinct data files that some retained snapshot lists. Count them; do not print them."""19 # all_files() can list one file from several manifests, so the set counts each file once20 return len(set(table.inspect.all_files()["file_path"].to_pylist()))212223with new_warehouse() as wh:24 table = create_iceberg_table(wh)25 for hour in (0, 1, 2):26 table.append(read_cut_hour(hour))27 # hour_filter(2) matches only hour 02's rows, so the overwrite replaces that hour and leaves hours 00 and 01 alone28 table.overwrite(hour_corrections(read_cut_hour(2)), overwrite_filter=hour_filter(2))2930 ids = [snapshot.snapshot_id for snapshot in table.metadata.snapshots] # metadata lists snapshots in commit order31 labels = snapshot_labels(ids)32 print("snapshots before expiry:", len(ids))33 print("data files referenced before expiry:", referenced_files(table))34 print("data files in the current snapshot:", len(table.inspect.files())) # files() reads the current snapshot only3536 expired = ids[:3] # the three hourly appends, by commit order37 table.maintenance.expire_snapshots().by_ids(expired).commit()38 table = wh.catalog.load_table(ICEBERG_ID)3940 print("remaining snapshots:", ", ".join(labels[s.snapshot_id] for s in table.metadata.snapshots))41 print("data files referenced after expiry:", referenced_files(table))42 # files under the table location that no remaining snapshot lists; a file a writer has not committed counts too43 print("unreferenced data files left on disk:", len(orphan_data_files(table)))44 print("rows in the current snapshot:", scan_arrow(table).num_rows)45 try:46 scan_arrow(table, snapshot_id=expired[-1])47 except ValueError as exc:48 print(f"read {labels[expired[-1]]}: {type(exc).__name__}")
python expire-iceberg-snapshots.pysnapshots before expiry: 5
data files referenced before expiry: 4
data files in the current snapshot: 3
remaining snapshots: snapshot 4, snapshot 5
data files referenced after expiry: 3
unreferenced data files left on disk: 1
rows in the current snapshot: 1499
read snapshot 3: ValueError
過期之前,資料表有 5 個快照,且至少有一個快照列出的資料檔案共 4 個。目前快照只列出其中的 3 個檔案。剩下的一個是舊的 02 時檔案,快照 3 仍列出它。這樣讀取計數,就能看出覆寫做了什麼:目前的資料表是完整的,而歷史記錄中仍保有被覆寫取代的檔案。
接著範例讓快照 1 到 3,也就是三個附加快照過期。剩下的快照是 snapshot 4, snapshot 5,即覆寫的刪除快照及其附加快照。之後列出的資料檔案有 3 個,舊的 02 時檔案已不再被任何快照列出。它仍在磁碟上:範例回報有 1 個未被參照的檔案。目前的資料表仍回傳 1499 列資料,所以過期並未改變讀取目前資料表的讀者所看到的資料。
最後一次讀取會失敗。過期後掃描快照 3 會引發 ValueError,輸出顯示為「read snapshot 3: ValueError」。在過期之前就固定使用快照 3 的讀取端會得到錯誤,而不是舊的資料列。錯誤訊息 Snapshot not found 指出了快照的 ID,但沒有說明是過期作業移除了該快照。你必須在自己的日誌中記錄執行了哪一次過期,以及報表使用了哪個快照。
實用原則: 依提交順序挑選 ID,以 ID 讓 Iceberg 快照過期,並在前後計算每個剩餘快照所列出的檔案數。不要預期過期會釋出磁碟空間。pyiceberg 只移除中繼資料,所遺留的檔案會一直留在磁碟上,直到你自行移除。
在快照過期後找出孤立檔案
沒有任何快照列出的檔案,就是孤立檔案(orphan file)。Spark 與 Java 提供 deleteOrphanFiles 動作:它會列出資料表位置下的檔案,將這些檔案與中繼資料比對,並刪除其差集,預設的檔案存留時間間隔為 3 天(Apache Iceberg, maintenance)。pyiceberg 的 API 頁面沒有列出任何處理孤立檔案的步驟,0.12.0 套件也沒有。它的維護方法只有讓快照過期(PyIceberg API)。
本書共用模組中的一個輔助函式 examples/lib/lakehouse.py,也就是 orphan_data_files,可以手動進行這項比對。它會列出資料表位置下的 Parquet 檔案,扣除任何剩餘快照所列出的檔案,並回傳其餘的檔案。輸出只顯示數量,因為檔案名稱含有 UUID。這個數量那一行,就顯示出已過期的檔案仍留在磁碟上。
僅憑列出檔案,無法區分孤立檔案與寫入端已寫入但尚未提交的檔案。提交動作才會把檔案連結到資料表,在此之前,該檔案看起來並未被參照。這就是存留時間防護很重要的原因。DuckLake 的 ducklake_delete_orphaned_files 預設會保留較新的檔案,Spark 動作也基於相同的理由接受存留時間間隔。pyiceberg 沒有這個間隔,因此必須由你自行檢查。刪除孤立檔案是另一項獨立的決定,應在可能提交這些檔案的寫入端都已停止之後再進行。
實用原則: 以列出檔案的方式計算孤立檔案,並且只有在確認沒有寫入端還能提交這些檔案、也沒有讀取端仍在使用列出這些檔案的快照之後,才加以移除。在 pyiceberg 中,函式庫不會替你進行這項檢查。
此部分尚未翻譯,因此以英文呈現。
Vacuum a table with deltalake
Delta Lake does not delete a file when a commit replaces it. A Delta commit that replaces a file adds a remove action to the log, a tombstone that says the file is no longer part of the table, and the file stays on disk. The protocol states that such files "can be lazily deleted by the vacuum command after a user-specified retention period (default 7 days)" (Delta transaction log protocol, v4.4.1). The output in this section uses Delta's own version numbers, which start at 0.
Vacuum deletes the files whose tombstones are older than the retention. Until then, every version can be read, because every file it lists still exists. The Delta utility page states the cost: "The ability to time travel back to a version older than the retention period is lost after running vacuum" (Delta Lake, VACUUM).
The case has three appends, which make versions 0 to 2, and then the hour-02 correction. The correction is a delete of that hour, which is version 3, followed by an append of the corrected rows, which is version 4. Version 2 still lists the old hour-02 file, and version 3 does not. Nothing has been removed yet, and that is the state the next section starts from.
The default retention in deltalake is 168 hours, seven days. A table can set its own in the delta.deletedFileRetentionDuration property, and vacuum uses that property when you pass no retention_hours. That property is the production setting. The library refuses a retention shorter than the property's value unless you turn off enforce_retention_duration. A longer retention needs no flag. The retention you choose is a promise about how far back history reaches. Every reader that opens an older version depends on it, and the next section shows the refusal and why this chapter's teaching run turns the check off.
Working rule: Keep vacuum's default retention, or set a longer one in delta.deletedFileRetentionDuration, so that every version a reader may request is still readable for that long after it stops being current. Go shorter only after you have checked the longest read and the longest write in your system, and only by turning enforce_retention_duration off as a deliberate, recorded decision.
先執行試跑
試跑(dry run)會列出真正的 vacuum 將會刪除的檔案,但不會刪除其中任何一個。每次執行 vacuum 之前都先試跑一次,並將其計數與資料表的歷史紀錄比對。這個案例包含三次附加、版本 3 的一次刪除,以及版本 4 的一次附加。較短的清單可以手動檢查:在這裡,清單中的每個檔案都是被刪除操作移除的檔案,而關鍵在於版本 3 的刪除。在這段歷史上執行兩次試跑,等於以兩種保留期限詢問 vacuum 它會刪除什麼:
1"""Show that vacuum's default retention keeps a file that a delete has just removed, and that a read of an older version2fails once a teaching-only run removes that file. The point rests on the default-retention line and the read of version 2."""34import pyarrow as pa5from deltalake import DeltaTable, write_deltalake6from deltalake.exceptions import DeltaError78from lib.lakehouse import new_warehouse, read_cut_hour, read_delta, hour_corrections910with new_warehouse() as wh:11 path = str(wh.root / "delta" / "pageviews_hourly")12 for hour in (0, 1, 2):13 write_deltalake(path, read_cut_hour(hour), mode="append")14 dt = DeltaTable(path)15 dt.delete("hour_utc = '2024-06-03T02:00:00'") # hour 02, matched by its exact timestamp16 # hour_corrections halves the views of some page titles in hour 02, so this append holds the corrected rows17 write_deltalake(path, hour_corrections(read_cut_hour(2)), mode="append")1819 dt = DeltaTable(path)20 print("current version:", dt.version())21 # the delete was seconds ago, so the default retention still keeps its file22 print("default retention, dry run lists:", len(dt.vacuum(dry_run=True)))23 try:24 dt.vacuum(retention_hours=0, dry_run=True) # a retention below the table's minimum: refused without the flag25 except DeltaError as exc:26 print("zero retention without the flag:", type(exc).__name__)27 # Teaching run only: a zero-hour retention removes files at once. Production keeps the 168-hour default.28 print("zero retention, dry run lists:", len(dt.vacuum(retention_hours=0, dry_run=True, enforce_retention_duration=False)))29 print("zero retention, removed:", len(dt.vacuum(retention_hours=0, dry_run=False, enforce_retention_duration=False)))30 print("rows in version 0:", read_delta(path, version=0).num_rows) # version 0 reads files the vacuum left alone31 try:32 read_delta(path, version=2) # version 2 still lists the hour-02 file that the vacuum removed33 except pa.ArrowInvalid as exc:34 print("read version 2:", type(exc).__name__)
python vacuum-delta-dry-run.pycurrent version: 4
default retention, dry run lists: 0
zero retention without the flag: DeltaError
zero retention, dry run lists: 1
zero retention, removed: 1
rows in version 0: 499
read version 2: ArrowInvalid
資料表目前的版本是 4。使用預設保留期限時,試跑列出 0 個檔案。版本 3 所移除的檔案還太新,不會被列出,vacuum 會保留它。
下一次呼叫把保留期限設為零,deltalake 以 DeltaError 拒絕了這個設定。函式庫本身的訊息指出最短保留期限為 168 小時,因此這項檢查保護的是預設值。
教學用的執行以 enforce_retention_duration=False 關閉這項檢查。程式碼將它標示為僅供教學之用,正式環境不會使用。關閉檢查後,試跑列出 1 個檔案,而真正的 vacuum 移除 1 個檔案,也就是舊的 hour-02 檔案。保留期限為零,對示範而言是合適的設定,因為它會立即刪除檔案。在正式環境中這是錯誤的:任何在 vacuum 之前就已開始的讀取者,或是固定在較舊版本的讀取者,會在查詢進行到一半時失去它所讀取的檔案。過短的保留期限也會刪除寫入者的檔案,這些檔案已寫入但尚未提交。Delta 工具頁面警告,「當 VACUUM 刪除尚未提交的檔案時,資料表可能損毀」(Delta Lake, VACUUM)。受損的是資料表本身,而不只是一次讀取。
最後的讀取顯示 vacuum 造成的代價。版本 0 仍然可以讀取,有 499 列,因為它所列出的每個檔案都仍然存在。版本 2 則以 ArrowInvalid 失敗,顯示為「read version 2: ArrowInvalid」。這個類別是查詢引擎在 Parquet 讀取失敗時所引發的,訊息中會指出遺失的物件。這次讀取只印出類別。在判定資料表已損毀之前,請先在自己的記錄中閱讀該訊息:它會說明哪個物件遺失,因此也能判斷是否為 vacuum 所移除。
試跑並不是對真正執行結果的保證。若有寫入者在兩次呼叫之間提交,資料表就會改變,而真正的執行是依它所見的資料表狀態進行。請把試跑的計數當作對預期結果的檢查,並在旁邊對照真正執行的計數。
實用原則: 先以試跑方式執行 vacuum,並閱讀其計數。只有在計數與你根據資料表歷史紀錄所預期的相符時,才用真正的執行移除檔案;除非已檢查過系統中最長的讀取作業,否則請維持預設的保留期限。
在 DuckLake 中使快照過期並清理檔案
DuckLake 會保留快照的實體檔案,直到該快照過期為止。DuckLake 文件的說法是:「只有讓參照舊資料的快照過期,才能從 DuckLake 實體移除資料」(DuckLake, expire snapshots)。同一頁也指出,快照過期並不會立即刪除因此不再被參照的檔案,而清理頁面則給出第二個呼叫(DuckLake, cleanup of files)。
因此 DuckLake 的維護分為兩個步驟,下方的範例兩者都會執行。ducklake_expire_snapshots 可接受 versions 中的快照編號清單,或一個 older_than 時間戳記,但兩者不能同時使用。ducklake_cleanup_old_files 會移除快照過期時排入排程的檔案。搭配 older_than 時,只會移除在指定時間之前排入排程的檔案。搭配 cleanup_all => true 時,則會移除所有已排程的檔案,不檢查檔案的存在時間。兩個步驟都支援 dry_run。
第三個呼叫 ducklake_delete_orphaned_files 處理沒有任何快照列出、且清理也從未排程的檔案,例如寫入端在提交失敗後遺留的檔案。它的預設行為會保留仍然很新的檔案,因為寫入端可能即將提交該檔案。它的 cleanup_all 選項則不論檔案存在時間,一律移除這類檔案。當第二個目錄共用同一個資料資料夾時,該選項會造成什麼結果,請見目錄一章。
透過輔助函式掛載目錄並建立綱要與資料表後,在寫入任何資料列之前就會產生三個快照:掛載產生快照 1,兩個 CREATE 陳述式產生快照 2 與快照 3,編號從 1 開始並把設定步驟算在內,做法與第 2 章相同。接著,載入用的輔助函式插入 00 至 02 時的資料,刪除 02 時的資料,再插入修正後的 02 時資料。這樣共產生 8 個快照,範例將它們標為「快照 1」直到最後一個。最後一個是修正後的插入。其前一個是刪除,它會丟棄舊的 02 時檔案。再前一個插入,即快照 6,是最後一個列出該檔案的快照。
1"""Expire every snapshot before the correction, clean up what expiry released, and run the orphan check as a dry run. The2point rests on the cleanup lines and on the orphan line, which shows that the default age check spares the stray copy."""34import shutil5from pathlib import Path67import duckdb89from lib.lakehouse import (10 DUCKLAKE_ALIAS, NAMESPACE, TABLE, connect_ducklake, create_ducklake_table,11 ducklake_file_count, ducklake_file_paths, load_ducklake_with_correction, new_warehouse,12 version_labels,13)1415LAKE = f"{DUCKLAKE_ALIAS}.{NAMESPACE}.{TABLE}"161718def listed(con, call):19 """Run a DuckLake procedure and return how many rows it lists."""20 return con.sql(f"CALL {call}").to_arrow_table().num_rows212223with new_warehouse() as wh:24 con = connect_ducklake(wh.con)25 create_ducklake_table(con, wh.root)26 load_ducklake_with_correction(con) # lib inserts hours 00 to 02, deletes hour 02, then inserts the corrected hour 022728 # ORDER BY 1 sorts by snapshot_id, which grows with each commit, so the labels number the snapshots in commit order29 ids = [r[0] for r in con.execute(f"SELECT snapshot_id FROM ducklake_snapshots('{DUCKLAKE_ALIAS}') ORDER BY 1").fetchall()]30 labels = version_labels(ids, word="snapshot")31 print("snapshots before expiry:", len(ids))32 print("data files in the current snapshot:", ducklake_file_count(con, DUCKLAKE_ALIAS, TABLE))33 stray = Path(sorted(ducklake_file_paths(con, DUCKLAKE_ALIAS, TABLE))[0]) # sorted, so every run copies the same file34 shutil.copy(stray, stray.with_name("stray.parquet")) # written, but no snapshot lists it3536 expired = ids[:-1] # all but the last snapshot, which is the corrected insert and stays37 # versions takes DuckLake's snapshot numbers, not the labels38 expire = f"ducklake_expire_snapshots('{DUCKLAKE_ALIAS}', versions => {expired}"39 print("expiry dry run lists:", listed(con, f"{expire}, dry_run => true)"))40 con.execute(f"CALL {expire})")41 print("remaining snapshots:", labels[ids[-1]])42 # no age check, so this is safe only because one catalog owns the folder and no reader is running43 cleanup = f"ducklake_cleanup_old_files('{DUCKLAKE_ALIAS}', cleanup_all => true"44 print("cleanup dry run lists:", listed(con, f"{cleanup}, dry_run => true)"))45 print("cleanup removed:", listed(con, f"{cleanup})"))46 # no cleanup_all, so the default age check spares the stray copy, which was written seconds ago47 orphans = f"ducklake_delete_orphaned_files('{DUCKLAKE_ALIAS}', dry_run => true)"48 print("orphans listed without cleanup_all:", listed(con, orphans))49 print("rows in the current snapshot:", con.sql(f"SELECT count(*) FROM {LAKE}").fetchall()[0][0])50 try:51 # the newest expired snapshot, the delete; reading it now fails52 con.sql(f"SELECT count(*) FROM {LAKE} AT (VERSION => {expired[-1]})").fetchall()53 except duckdb.InvalidInputException as exc:54 print(f"read {labels[expired[-1]]}: {type(exc).__name__}")
python ducklake-expire-cleanup.pysnapshots before expiry: 8
data files in the current snapshot: 3
expiry dry run lists: 7
remaining snapshots: snapshot 8
cleanup dry run lists: 1
cleanup removed: 1
orphans listed without cleanup_all: 0
rows in the current snapshot: 1499
read snapshot 7: InvalidInputException
目前的快照列出 3 個資料檔案,其中一個被複製成同一資料夾內的另一個名稱,用來代表寫入端已寫出但尚未提交的檔案,如〈尋找孤立檔案〉(Find orphan files)所述。接著依序執行各個步驟。
過期的模擬執行(dry run)列出 7 個快照,也就是除了修正後的插入之外的全部快照。由於該插入予以保留,資料表目前的狀態不受影響。實際執行過期後,剩下 snapshot 8。舊的 02 時檔案在這個步驟被釋放,因為最後一個列出它的快照,即快照 6,已經過期。
清理的試運行列出 1 個檔案,即舊的 02 時檔案。DELETE 比對到該檔案中的每一個資料列,而且沒有刪除檔案與它一起排程,所以舊檔案是唯一剩下要移除的檔案。實際執行清理時移除了 1 個檔案。
孤立檔案檢查列出 0 個孤立檔案。那個多餘的副本仍在資料夾中,因為預設的存在時間檢查保留了它:該檔案只存在了幾秒鐘。資料表仍然傳回 1499 個資料列。
最後,讀取刪除操作所在的快照 7 失敗,訊息為「read snapshot 7: InvalidInputException」。這個錯誤類別就是 DuckLake 在版本已不存在時所引發的類別。
此處出現 cleanup_all => true,是因為只有一個目錄,也沒有讀取端。正式環境改用 older_than,並設定比最長讀取時間更長的存在時間,使清理只移除已排程足夠久的檔案。
實用原則: 先讓 DuckLake 快照過期,再依序對每個清理呼叫先做試運行、再實際執行。保留預設的孤立檔案檢查。只有在單一目錄擁有該資料資料夾,且沒有任何讀取端仍在使用將被移除的檔案時,才使用 cleanup_all;否則請使用 older_than。
正式環境中會出什麼問題
**移除仍有讀取者在使用的檔案。**在 vacuum 或清理之前就已開始的查詢,會讀取一個隨後消失的檔案,讀取因而在中途失敗。你會看到一則指出物件遺失的讀取錯誤,發生在維護時段內執行的作業中。請把維護排在長時間讀取之外,並讓保留期限長於其中最長的一次讀取。過短的保留期限也可能刪除寫入者已寫入但尚未提交的檔案,這會損毀資料表,而不只是讓一次讀取失敗,因此保留期限也要長於執行時間最長的寫入。
**保留期限短於最長的查詢。**Delta Lake 預設的七天是一段緩衝,而不是實際量測的結果。若儀表板讀取的是一個月前的版本,就超出了這段緩衝。如果讀取者必須看到較舊的版本,保留期限就得涵蓋該版本,否則讀取者必須先複製資料。
**維護之後時間旅行失敗。**已到期的快照與已被 vacuum 的版本,會依格式不同而以 ValueError、ArrowInvalid 或 InvalidInputException 失敗。Iceberg 會引發 ValueError,Delta 會引發 ArrowInvalid,DuckLake 會引發 InvalidInputException。任何記錄快照 ID 或版本號以便日後讀取的作業,在該快照到期後都會以同樣方式失敗。請自行記錄每份報表使用了哪個快照,讓重建從資料開始,而不必依賴讀取舊快照。
**試運行與實際執行不一致。**若有寫入者在兩次呼叫之間提交,兩次呼叫的結果可能不同。試運行的數量是你預期的數量,不是實際執行會移除的數量。請把實際執行的數量與試運行的數量並列檢視,若兩者的差異超出你能解釋的範圍,就應停止。
**稽核需要較舊的快照。**有些報表必須重現數月前的數字。到期會永久移除這項能力,因此請在到期之前決定稽核期間,並保留稽核所需的快照或已複製的資料。到期不能取代複本。
清理刪除了另一個目錄所需的檔案。cleanup_all 以及搭配 cleanup_all 的孤立檔案檢查,都是依路徑刪除檔案。若第二個目錄指向同一個資料夾,它的有效檔案在第一個目錄看來就像孤立檔案。目錄章在暫存目錄中示範了這種失敗。
**實用原則:**在讓快照到期或進行清理之前,先列出可能開啟較舊快照或版本的讀取者、報表與稽核,並把保留期限設為涵蓋其中最長者。每次呼叫都先以試運行執行,把其數量與預期比較,只有在兩者一致時才執行實際呼叫。
本章的決定
- Iceberg 快照依 ID 過期,ID 從提交順序中挑選。本章不依存留時間讓快照過期,因此結果不取決於機器的時鐘,而且 pyiceberg 0.12.0 也沒有保留最後 N 個快照的參數。
- pyiceberg 不會移除任何檔案,所以
expire-iceberg-snapshots只計算可達與不可達的檔案數量,移除的工作留給讀者。 vacuum-delta-dry-run中的零保留期執行僅供教學用途。程式碼中已加上標記,正式環境則沿用預設的保留期。- DuckLake 的過期與清理是兩個各自獨立的呼叫,每個呼叫都先以試執行(dry run)跑過,再進行實際呼叫。
cleanup_all只出現在單一目錄(catalog)的範例中。它會移除仍在使用中檔案的情況,留待目錄一章說明。- 每個範例只輸出數量、穩定的標籤與錯誤類別名稱,不輸出 ID、時間戳記、檔名或路徑(原因見第 1 章),而且文中的每個數字,都來自已繫結的輸出行,或來自該範例本身的建構方式。
- 每個範例都沿用前幾章建立的資料表,因此每個數量都能對照讀者已經看過的歷史來檢查。
- 每個範例都會建立自己的暫時性倉儲(warehouse),所以沒有任何輸出會依賴先前的範例,或執行範例的機器。
ducklake-expire-cleanup中的多餘副本,用來代表寫入者尚未提交的檔案,如尋找孤立檔案所述。由於執行只需數秒,這樣就能展示孤立檔案的判定規則,而不必等待檔案變舊。
本章,於本版次中
版次 2026.11.10範例於 2026年11 月 20 通過測試本章 3 個範例 個範例中有 3 個通過
譯自英文書,版次 2026.11.10。