使快照过期并删除未被引用的文件

阅读约需 39分钟 分钟,8节中含3个示例。

版次 2026.11.10 示例于 2026年11月20日 通过 39个示例中有39个通过 变化内容

AI 翻译。由人工以英文核验。 我们如何制作图书

译自英文版图书,版次 2026.11.10。 阅读原文

学完本章后,你可以在三种格式中分别使旧快照过期,删除只有这些快照还列出的数据文件,并证明读取已过期的快照会失败。

压缩会留下同样的旧文件:重写之后,被替换的文件仍留在磁盘上,因为较早的快照仍然列出它们。本章先使 wiki.pageviews_hourly 的旧快照过期,再删除已不被任何快照列出的文件。本章的每个示例都使用更正一章中第 02 小时的更正,并把它写成对该小时的覆盖写入,而不是该章后面一节中的 upsert,因为覆盖写入在每种格式中恰好留下一个旧文件。这些旧文件会一直保留,直到它们的快照过期、文件被删除为止。这两个步骤在每种格式中都会执行,并且每一步都用计数来核对,而不是依赖一份你只能相信的清单。

快照让文件保持存活

最近一次修改见于版次 2026.11.10

每个快照都记录了该次提交时由哪些数据文件构成这张表。快照指向什么说明了各种格式如何存储这份清单。对本章而言,要点在于:替换行的提交并不会删除被替换的文件。它会为替换后的行写入新文件,而提交之前的快照仍然列着旧文件,因此时间旅行依然可用。只有当你保留的所有快照都不再列出某个数据文件时,它才成为孤儿文件。

在每种格式中,删除文件都分两步:先过期,后清理。Iceberg 的维护页面给出了同样的顺序:过期会把快照从元数据中移除,使时间旅行无法再访问它们,而且“数据文件不会被删除,直到它们不再被任何可能用于时间旅行或回滚的快照所引用”(Apache Iceberg,维护)。过期之后,清理会删除所有剩余快照都不再列出的文件。

wiki.pageviews_hourly 先经历三次按小时的追加,随后 02 时被一次覆盖该小时的操作更正。每次追加写入一个文件。覆盖操作写入一个包含更正后 02 时各行的文件,并把旧文件从当前快照中移除。当初追加该旧文件的那个快照仍然列着它。在该快照过期之前,旧文件不能被删除,否则会破坏对它的时间旅行。更新插入一个被更正的小时展示了写入同一更正的另一种方式,它同样会留下同类的旧文件。

每种格式都有各自的过期调用和各自的清理调用。下表列出了它们,本章其余部分对每种格式都按同样的顺序展开。

格式 过期调用 过期是否删除文件? 清理调用
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 使快照过期

最近一次修改见于版次 2026.11.7

在 pyiceberg 0.12.0 中,table.maintenance.expire_snapshots() 接受快照 ID:列表用 by_ids,单个 ID 用 by_id,也可以使用 older_than 时间戳。它没有“保留最近 N 个快照”的参数。本章按提交顺序选取 ID,示例也是如此:三次按小时的追加就是前三个快照。ID 本身是随机的 64 位数字,因此示例按相同顺序打印“snapshot 1”“snapshot 2”等标签。

覆盖写入会增加两个快照,而不是一个。pyiceberg 先写入一个删除快照,用来移除旧文件,再写入一个追加快照,用来添加修正后的行。快照 4 是删除快照,快照 5 是追加快照。因此,使三次追加过期后,覆盖写入仍然保留,示例检查的正是这一状态。

过期调用不会删除任何数据文件,所以示例自行在过期前后计数:一是各快照所列出的不同文件,二是磁盘上没有任何快照列出的文件。请留意最后一个计数,被替换的文件会在那里出现:

expire-iceberg-snapshots.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 通过
"""Expire the three append snapshots by ID, then count what the snapshots still reference. The point rests on theline that counts unreferenced data files on disk: expiry removes metadata, and the file the overwrite replaced stays."""from lib.lakehouse import (    ICEBERG_ID,    create_iceberg_table,    hour_corrections,    hour_filter,    new_warehouse,    orphan_data_files,    read_cut_hour,    scan_arrow,    snapshot_labels,)def referenced_files(table):    """Distinct data files that some retained snapshot lists. Count them; do not print them."""    # all_files() can list one file from several manifests, so the set counts each file once    return len(set(table.inspect.all_files()["file_path"].to_pylist()))with new_warehouse() as wh:    table = create_iceberg_table(wh)    for hour in (0, 1, 2):        table.append(read_cut_hour(hour))    # hour_filter(2) matches only hour 02's rows, so the overwrite replaces that hour and leaves hours 00 and 01 alone    table.overwrite(hour_corrections(read_cut_hour(2)), overwrite_filter=hour_filter(2))    ids = [snapshot.snapshot_id for snapshot in table.metadata.snapshots]  # metadata lists snapshots in commit order    labels = snapshot_labels(ids)    print("snapshots before expiry:", len(ids))    print("data files referenced before expiry:", referenced_files(table))    print("data files in the current snapshot:", len(table.inspect.files()))  # files() reads the current snapshot only    expired = ids[:3]  # the three hourly appends, by commit order    table.maintenance.expire_snapshots().by_ids(expired).commit()    table = wh.catalog.load_table(ICEBERG_ID)    print("remaining snapshots:", ", ".join(labels[s.snapshot_id] for s in table.metadata.snapshots))    print("data files referenced after expiry:", referenced_files(table))    # files under the table location that no remaining snapshot lists; a file a writer has not committed counts too    print("unreferenced data files left on disk:", len(orphan_data_files(table)))    print("rows in the current snapshot:", scan_arrow(table).num_rows)    try:        scan_arrow(table, snapshot_id=expired[-1])    except ValueError as exc:        print(f"read {labels[expired[-1]]}: {type(exc).__name__}")
输出python expire-iceberg-snapshots.py
snapshots 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 使 Iceberg 快照过期,ID 从提交顺序中选取,并在过期前后统计每个剩余快照所列出的文件数。不要指望过期能腾出磁盘空间。pyiceberg 只移除元数据,它留下的文件会一直保留在磁盘上,直到你自己将其删除。

在快照过期后查找孤立文件

最近一次修改见于版次 2026.11.8

任何快照都未列出的文件即为孤立文件。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

最近一次修改见于版次 2026.11.10

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.

先做试运行

最近一次修改见于版次 2026.11.7

试运行会列出真正的 vacuum 将要删除的文件,但不会删除其中任何一个。每次执行 vacuum 之前都应先做一次试运行,并把它给出的文件数与表的历史记录对照。本例中的历史是三次追加,版本 3 中的一次删除,以及版本 4 中的一次追加。文件列表较短时可以逐个核对:这里列表中的每个文件,都是被某次删除操作移除的文件,而关键的是版本 3 中的那次删除。在这段历史上做两次试运行,就是以两种保留期询问 vacuum 它会删除什么:

vacuum-delta-dry-run.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 通过
"""Show that vacuum's default retention keeps a file that a delete has just removed, and that a read of an older versionfails once a teaching-only run removes that file. The point rests on the default-retention line and the read of version 2."""import pyarrow as pafrom deltalake import DeltaTable, write_deltalakefrom deltalake.exceptions import DeltaErrorfrom lib.lakehouse import new_warehouse, read_cut_hour, read_delta, hour_correctionswith new_warehouse() as wh:    path = str(wh.root / "delta" / "pageviews_hourly")    for hour in (0, 1, 2):        write_deltalake(path, read_cut_hour(hour), mode="append")    dt = DeltaTable(path)    dt.delete("hour_utc = '2024-06-03T02:00:00'")  # hour 02, matched by its exact timestamp    # hour_corrections halves the views of some page titles in hour 02, so this append holds the corrected rows    write_deltalake(path, hour_corrections(read_cut_hour(2)), mode="append")    dt = DeltaTable(path)    print("current version:", dt.version())    # the delete was seconds ago, so the default retention still keeps its file    print("default retention, dry run lists:", len(dt.vacuum(dry_run=True)))    try:        dt.vacuum(retention_hours=0, dry_run=True)  # a retention below the table's minimum: refused without the flag    except DeltaError as exc:        print("zero retention without the flag:", type(exc).__name__)    # Teaching run only: a zero-hour retention removes files at once. Production keeps the 168-hour default.    print("zero retention, dry run lists:", len(dt.vacuum(retention_hours=0, dry_run=True, enforce_retention_duration=False)))    print("zero retention, removed:", len(dt.vacuum(retention_hours=0, dry_run=False, enforce_retention_duration=False)))    print("rows in version 0:", read_delta(path, version=0).num_rows)  # version 0 reads files the vacuum left alone    try:        read_delta(path, version=2)  # version 2 still lists the hour-02 file that the vacuum removed    except pa.ArrowInvalid as exc:        print("read version 2:", type(exc).__name__)
输出python vacuum-delta-dry-run.py
current 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 中的过期与清理

最近一次修改见于版次 2026.11.7

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,是最后一个列出该文件的快照。

ducklake-expire-cleanup.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 通过
"""Expire every snapshot before the correction, clean up what expiry released, and run the orphan check as a dry run. Thepoint rests on the cleanup lines and on the orphan line, which shows that the default age check spares the stray copy."""import shutilfrom pathlib import Pathimport duckdbfrom lib.lakehouse import (    DUCKLAKE_ALIAS, NAMESPACE, TABLE, connect_ducklake, create_ducklake_table,    ducklake_file_count, ducklake_file_paths, load_ducklake_with_correction, new_warehouse,    version_labels,)LAKE = f"{DUCKLAKE_ALIAS}.{NAMESPACE}.{TABLE}"def listed(con, call):    """Run a DuckLake procedure and return how many rows it lists."""    return con.sql(f"CALL {call}").to_arrow_table().num_rowswith new_warehouse() as wh:    con = connect_ducklake(wh.con)    create_ducklake_table(con, wh.root)    load_ducklake_with_correction(con)  # lib inserts hours 00 to 02, deletes hour 02, then inserts the corrected hour 02    # ORDER BY 1 sorts by snapshot_id, which grows with each commit, so the labels number the snapshots in commit order    ids = [r[0] for r in con.execute(f"SELECT snapshot_id FROM ducklake_snapshots('{DUCKLAKE_ALIAS}') ORDER BY 1").fetchall()]    labels = version_labels(ids, word="snapshot")    print("snapshots before expiry:", len(ids))    print("data files in the current snapshot:", ducklake_file_count(con, DUCKLAKE_ALIAS, TABLE))    stray = Path(sorted(ducklake_file_paths(con, DUCKLAKE_ALIAS, TABLE))[0])  # sorted, so every run copies the same file    shutil.copy(stray, stray.with_name("stray.parquet"))  # written, but no snapshot lists it    expired = ids[:-1]  # all but the last snapshot, which is the corrected insert and stays    # versions takes DuckLake's snapshot numbers, not the labels    expire = f"ducklake_expire_snapshots('{DUCKLAKE_ALIAS}', versions => {expired}"    print("expiry dry run lists:", listed(con, f"{expire}, dry_run => true)"))    con.execute(f"CALL {expire})")    print("remaining snapshots:", labels[ids[-1]])    # no age check, so this is safe only because one catalog owns the folder and no reader is running    cleanup = f"ducklake_cleanup_old_files('{DUCKLAKE_ALIAS}', cleanup_all => true"    print("cleanup dry run lists:", listed(con, f"{cleanup}, dry_run => true)"))    print("cleanup removed:", listed(con, f"{cleanup})"))    # no cleanup_all, so the default age check spares the stray copy, which was written seconds ago    orphans = f"ducklake_delete_orphaned_files('{DUCKLAKE_ALIAS}', dry_run => true)"    print("orphans listed without cleanup_all:", listed(con, orphans))    print("rows in the current snapshot:", con.sql(f"SELECT count(*) FROM {LAKE}").fetchall()[0][0])    try:        # the newest expired snapshot, the delete; reading it now fails        con.sql(f"SELECT count(*) FROM {LAKE} AT (VERSION => {expired[-1]})").fetchall()    except duckdb.InvalidInputException as exc:        print(f"read {labels[expired[-1]]}: {type(exc).__name__}")
输出python ducklake-expire-cleanup.py
snapshots 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 个数据文件,其中一个被复制为同一文件夹中的另一个名称,用来代表写入方已写入但未提交的文件,如查找孤立文件所述。然后各步骤按顺序运行。

过期的试运行列出 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。

生产环境中会出什么问题

最近一次修改见于版次 2026.11.7

删除仍被读取方使用的文件。 在清理(vacuum 或 cleanup)之前启动的查询,会读取一个随后已被删除的文件,读取在中途失败。你会看到一条指出对象缺失的读取错误,它出现在维护窗口期间运行的作业中。应把维护安排在长时间读取之外,并让保留期长于其中最长的一次读取。过短的保留期还可能删除写入方已写入但尚未提交的文件,这会损坏整张表,而不只是让一次读取失败,因此保留期也要长于运行时间最长的写入。

保留期短于最长的查询。 Delta Lake 默认的七天只是一个余量,而不是实测值。读取一个月前某个版本的仪表盘就超出了这个余量。如果读取方必须看到较旧的版本,保留期就必须覆盖该版本,否则读取方要先复制数据。

维护之后时间旅行失败。 已过期的快照和已被清理的版本会失败,并抛出 ValueError、ArrowInvalid 或 InvalidInputException,具体取决于格式。Iceberg 抛出 ValueError,Delta 抛出 ArrowInvalid,DuckLake 抛出 InvalidInputException。任何记录了快照 ID 或版本号、以便日后读取的作业,一旦该快照过期,都会以同样的方式失败。请自行记录每份报告使用了哪个快照,这样重建时可以从数据本身开始,而不依赖读取旧快照。

试运行与实际运行不一致。 当写入方在两次调用之间提交时,两次调用的结果可能不一致。试运行得到的数量是你的预期,而不是实际运行将要删除的数量。请把实际运行的数量与试运行的数量对照着读,如果两者的差异超出你能解释的范围,就停止。

审计需要较旧的快照。 有些报告必须复现数月之前的某个数字。过期会永久地使这种能力丧失,因此请在过期之前确定审计窗口,并保留审计所需的快照或复制出来的数据。过期不能代替复制。

清理删除了另一个目录需要的文件。 cleanup_all 以及使用 cleanup_all 的孤立文件检查都是按路径删除文件。如果第二个目录指向同一个数据文件夹,那么它的有效文件在第一个目录看来就像孤立文件。目录一章在一个临时目录中演示了这种故障。

工作准则: 在使快照过期或执行清理之前,列出可能打开较旧快照或版本的读取方、报告和审计,并把保留期设为能覆盖其中最长的一个。每次调用都先作为试运行,把它的数量与你的预期对照,只有两者一致时才执行实际调用。

本章做出的决定

最近一次修改见于版次 2026.11.7
  • Iceberg 快照按 ID 过期,ID 依提交顺序选取。本章不按保留时长(快照年龄)过期,因此结果不依赖机器的时钟,而且 pyiceberg 0.12.0 没有“保留最近 N 个”的参数。
  • pyiceberg 不会删除任何文件,所以 expire-iceberg-snapshots 只统计可达文件和不可达文件的数量,删除工作留给读者。
  • vacuum-delta-dry-run 中的零保留期运行仅用于教学。代码中对此有标注,生产环境沿用默认的保留期。
  • DuckLake 的过期与清理是两次独立的调用,每一次都先以试运行方式执行,再进行真正的调用。
  • cleanup_all 只出现在单目录(catalog)示例中。关于目录(catalog)的章会讨论它删除在用文件的情形。
  • 每个示例只打印数量、稳定的标签和错误类名,不打印 ID、时间戳、文件名或路径(原因见第 1 章),正文中的每个数字都来自某一行绑定的输出,或来自示例自身的构造。
  • 每个示例都沿用前几章建立的表,因此每个数量都可以对照读者已经见过的历史记录来核对。
  • 每个示例都构建自己的临时仓库(warehouse),所以任何输出都不依赖之前的示例,也不依赖运行它的机器。
  • ducklake-expire-cleanup 中的游离副本,代表写入方尚未提交的文件,如查找孤立文件所述。这样无需等待文件变旧,就能演示孤立文件规则,因为运行只需几秒。

本章,在本版次中

版次 2026.11.10示例于 2026年11月20日 通过本章 3个示例 个示例中有 3 个通过

译自英文版图书,版次 2026.11.10。

引用本节

格式

每种格式均引用英文原书,本译本以其为准。

每种格式都会注明该版次。其链接会打开当前版次,节标题处会说明该节文本最后一次修改的时间。访问日期和检索日期即为您打开此页的当天。

本页内容

第 7 章,共 10 章: 使快照过期并删除未被引用的文件

  1. 快照让文件保持存活
  2. 使用 pyiceberg 使快照过期
  3. 在快照过期后查找孤立文件
  4. Vacuum a table with deltalake
  5. 先做试运行
  6. DuckLake 中的过期与清理
  7. 生产环境中会出什么问题
  8. 本章做出的决定

返回顶部全部章节