Skip to content

feat(dataset): add expire_versions to remove history without reading manifests - #9438

Merged
Xuanwo merged 16 commits into
lance-format:mainfrom
jackye1995:jack/expire-versions
Nov 3, 2026
Merged

Xuanwo merged 16 commits into
lance-format:mainfrom
jackye1995:jack/expire-versions

Conversation

@jackye1995

@jackye1995 jackye1995 commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Problem

cleanup_old_versions is the only way to drop version history, and it cannot drop only history. It computes the live set of data files first, which means reading every retained manifest before deleting anything.

On a production table taking ~2,900 commits/hour with ~10 MB manifests, that read was 3.99 TiB and ~32 hours — to remove history the caller already knew it wanted gone.

expire_versions

Removes manifests and nothing else. It reads no manifests: the version comes from the filename, and the age from the write time the listing already reports but previously discarded.

// Full history for the last 7 days, one version per hour before that.
let policy = ExpireVersionsPolicyBuilder::default()
    .before_timestamp(Utc::now() - TimeDelta::try_days(7).unwrap())
    .keep_one_per(Duration::from_secs(3600))
    .build();
let stats = expire_versions(&dataset, policy).await?;

Data files that only an expired version referenced are deliberately left behind. They become unreferenced, and the next cleanup_old_versions reclaims them — far more cheaply, having far fewer manifests to read. The intended order is expire, then clean up. Rust, Python and Java, each with a dry run.

Never removes the latest version, a tag on the current branch, a version a branch is rooted at, or anything at or above the version hint — the hint anchors an upward probe that stops at the first gap, so a hole above it would hide every version above it.

Source compatibility

lance_table::io::commit::ManifestLocation gains last_modified. Rust callers that construct it with a struct literal must initialize the field; use None when the source cannot provide a reliable object write time. This is runtime listing metadata, not a persistent format change.

@github-actions github-actions Bot added A-python Python bindings A-java Java bindings + JNI A-encoding Encoding, IO, file reader/writer enhancement New feature or request labels Sep 20, 2026
@jackye1995
jackye1995 marked this pull request as ready for review September 20, 2026 07:56

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ Gate recommendation: request changes.

Before this can safely ship, retention widths need one explicit, consistent contract across Rust and the language bindings. The viable minimum is to reject zero or unsupported fractional widths before planning and deletion; alternatively, bucket at the full supplied precision. Silent coercion is unsafe because it changes which version manifests are irreversibly removed.

@lance-gatekeeper lance-gatekeeper Bot added K-changes Latest Gatekeeper recommendation requests changes. and removed K-changes Latest Gatekeeper recommendation requests changes. labels Sep 20, 2026

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Gate recommendation: approve.

The retention-width defect is fixed: exact sub-second bucketing is preserved across Rust, Python, and Java, and zero is rejected before deletion. No blocking items remain.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 20, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 21, 2026

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Gate recommendation: approve.

The rebased patch preserves the previously reviewed retention behavior. The added cleanup race handling treats only a manifest that vanished between listing and size lookup as the desired zero-byte outcome while propagating other storage errors, and the new Python stubs match the runtime result types. No blocking items remain.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 21, 2026
`list_manifests` reads `ObjectMeta`, which carries `last_modified`, then drops it
converting to `ManifestLocation`. A caller that only needs a version's age has no
choice but to read the whole manifest for `Manifest::timestamp`, which on a table
with millions of versions means reading terabytes to answer a question the
listing already answered.

The field is the object write time, not the logical commit time, and the doc
comment says so: rewriting an object by copy or migration moves one and not the
other. It is `None` when the location came from somewhere that never saw an
`ObjectMeta`, such as probing a known version or a namespace response.

Same shape as carrying the manifest size instead of issuing a HEAD per manifest.
… data

`cleanup_old_versions` is the only way to drop version history, and it cannot be
used to drop only history: it computes the live set of data files first, which
means reading every retained manifest. On a table taking thousands of commits an
hour with large manifests, that read is terabytes and hours before anything is
deleted, even when the caller only wants the history gone.

`expire_versions` deletes manifests and nothing else. It reads no manifests: the
version comes from the filename and the age from the write time the listing
already reports. Data files that only an expired version referenced are left for
the next `cleanup_old_versions`, which is then far cheaper because it has far
fewer manifests to read. Expire, then clean up.

`keep_one_per` thins beyond the cutoff instead of deleting everything there, so
"full history for 7 days, then hourly" is one policy rather than a script.
Buckets are absolute, so survivors do not shift as the table grows.

The rules for what must survive move to `version_retention`, shared with cleanup
so they cannot drift: the latest version, tags on the current branch, and the
versions branches are rooted at. Cleanup's behaviour is unchanged; its tests are
the regression guard.

Verified non-vacuous: dropping tag protection fails
expire_never_removes_a_tagged_version, and dropping latest protection fails
expire_never_removes_the_latest_version with left 3, right 2.
Java is included here rather than deferred. The last review on this stack caught
exactly this gap in reverse: a stat that reached Rust and Python but not Java,
where the caller then saw results indistinguishable from complete success.

Python takes `before` as a timedelta and converts on the Rust side against one
clock, matching cleanup_old_versions rather than inventing a second convention.
`keep_one_per` is a timedelta; Java takes plain seconds, so neither binding needs
a granularity enum.

The Java test forces a real failure instead of asserting zero on a clean run:
asserting zero proves nothing when a dropped field also reads as zero. Making
_versions read-only after the last commit fails the manifest deletes while the
writes still succeed. Root ignores the bits, so it probes first and skips rather
than failing.

Verified non-vacuous: hardcoding failed_deletes to 0 in the JNI projection fails
the test with "expected the blocked manifest deletes to be counted, got 0".
Rust and Python already had the dry run; Java only had the destructive call, so a
Java caller had no way to see what a policy would remove before running it. That
matters most for the policy that is easiest to get wrong: a `beforeVersion` typo
is unrecoverable, and the dry run is the thing that catches it.

`explainExpireVersions` takes the same policy and returns the versions that would
be deleted, the resulting stats, and any tagged versions the policy would have
expired.

The test asserts the manifests it names are still on disk afterwards, and that a
real run then removes exactly the predicted count. Verified non-vacuous: making
the explain path also delete fails it with "explainExpireVersions must not delete
anything, expected: <5> but was: <2>".
Three lints, all in test code and all fatal in CI, which builds tests with
-D warnings:

- `Path::child` is deprecated in favour of `join`
- two bindings did not need to be mutable, since `tags()` takes `&self`

I had reported clippy as clean locally. It was not: I piped cargo to `rg` and
read the pipeline's exit code, which is `rg`'s, so a failing cargo looked like a
pass. Capture cargo's own status instead.
`thin_to_one_per` bucketed by `width.as_secs().max(1)`, so any sub-second width
was silently widened to a full second. Two manifests 500ms apart landed in one
bucket and one was deleted, against a policy that asked to keep both. Version
history does not come back, so silent widening is the worst available failure.

Bucketing is now exact to the nanosecond, in i128 so neither a pre-1677 timestamp
nor a multi-year width overflows.

The bindings had two more ways to lose the width. Python truncated the timedelta
to whole seconds, and `timedelta(0)` is falsy so it was dropped as if unsupplied,
turning "keep one per zero" into "expire everything past the cutoff". Java took
whole seconds. Both now carry microseconds, which is exactly timedelta's own
resolution; Java refuses a finer width rather than truncating it.

Zero is rejected before planning, so it surfaces as an error in every binding
instead of quietly disabling thinning.

One of my own tests was misleading and is replaced: it asserted a zero width
keeps every version, but its candidates were a second apart, so it passed on the
one-second fallback rather than on the property. The new one uses candidates
inside the same second.

Reproducer from the review now passes as a test: at a 500ms width, versions at
100ms and 600ms both survive.
Same omission a reviewer caught on the parent PR for `CleanupStats`: the stub is
what type checkers and editors read, so a class missing from it exists at runtime
and is invisible to every Python caller.

`ExpireVersionsStats` and `ExpireVersionsPlan` were absent entirely. Checked all
three classes field-by-field against their pyo3 structs rather than by eye.
Resolving the latest version starts at the hint and probes upward one version at
a time, stopping at the first that is missing. A hole above the hint therefore
does not merely lose that version — it hides every version above it, and the
dataset reads as though it were rolled back.

`ProtectedVersions` now treats the hint as a floor. Deleting the hinted version
itself is survivable, since a miss there falls back to a full listing, but there
is nothing to gain by allowing it, so the floor is inclusive.

`read_version_from_hint` becomes public for this; its doc now says why a caller
that removes manifests needs it.

Verified non-vacuous: without the floor the end-to-end test expires versions
[1, 2, 3, 4] where 3 is the hint, instead of [1, 2].
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 22, 2026
Branch handling was already there — `base` follows the checkout, and branch
references resolve the same way cleanup resolves them — but nothing proved it,
so a later change could quietly break either half.

Two cases: expiring on main must keep the version a branch is rooted at, and
expiring on a branch must act on the branch's own manifests and leave the parent
untouched.

Verified non-vacuous: dropping branch-referenced versions from the protected set
expires [1, 2, 3, 4] with a branch rooted at 2, orphaning it.

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ Gate recommendation: request changes.

The version-hint floor is sampled once before deletion, but hint writes can complete out of order. Expiry can therefore create a gap above a newly lowered hint and make latest-version discovery silently return an older dataset state. Make hint publication monotonic/conditional, or otherwise bind expiry to a stable hint contract so concurrent commits cannot introduce a probed gap.

.map(|(_name, version)| version)
.collect();

let hint_floor = read_version_from_hint(&dataset.object_store, &dataset.base).await;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading latest_version_hint.json only once does not make this floor stable: each committer performs an unconditional best-effort hint write after publishing its manifest, so an older commit can finish that write after this read and lower the hint. If expiry then removes a successor that the earlier snapshot allowed—while the newly hinted version survives because of a tag, thinning, or a failed delete—the upward probe stops at that gap and silently exposes an older dataset state even though newer manifests still exist. This feature explicitly targets actively committing tables, so this is a realistic rollback path.

Please make hint publication monotonic under concurrent writers (for example, with a conditional/CAS update), or otherwise coordinate expiry with a hint value that cannot move below the protected floor.

Reproducer

I ran this addable test against cf97509f:

#[tokio::test]
async fn test_current_manifest_path_with_gap_above_hint() {
    let object_store = non_lexical_memory_store();
    let base = Path::from("base");
    let scheme = ManifestNamingScheme::V2;

    for version in 1..=5 {
        object_store
            .put(&scheme.manifest_path(&base, version), b"".as_slice())
            .await
            .unwrap();
    }
    write_version_hint(&object_store, &base, 3).await;
    object_store
        .delete(&scheme.manifest_path(&base, 4))
        .await
        .unwrap();

    let location = current_manifest_path(&object_store, &base).await.unwrap();
    assert_eq!(location.version, 5, "a gap must not hide newer versions");
}

Observed: resolved version 3; expected 5.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right about the mechanism, and the reproducer is a real rollback path: the floor is
read once, hint writes are unconditional, so a commit that started earlier can publish a
lower hint afterwards and a gap above it hides everything above it.

I'm not making the hint monotonic in this PR, and I want to be explicit that this is an
accepted risk rather than a solved one.

Why not fix it here. A conditional or CAS hint write is a change to the commit path,
which every writer takes, for the benefit of an operation almost no table runs. That trade
belongs in its own change with its own review, not smuggled in behind an expiry feature.
And it would not fully close the hole on its own: the hint is best-effort by design, so a
writer that dies between publishing its manifest and writing the hint still leaves the
floor behind the truth. Monotonic writes narrow the window; they do not make a
read-once floor authoritative.

What d102d28 does instead. keep_one_per must now be at least one hour, rejected in
Rust before planning and in the Java builder so no binding can express a finer width.
Keeping survivors an hour apart keeps deletions away from the seconds-wide window in which
a stale hint can land. That bounds the exposure; it does not remove it.

The field doc, the Java javadoc and the Python docstring now all carry the same warning,
including the part that matters most operationally: thinning is a repair for a table
that has accumulated far more versions than it can carry, not a default to leave switched
on.
Someone reaching for it should be doing so deliberately, having read why.

Worth noting the risk is not specific to thinning — any expiry that removes a version below
a concurrently-lowered hint can produce the same gap. Thinning just makes it easier to
reach by deleting more versions at finer granularity, which is why the minimum is on that
setting.

If you'd rather block on a monotonic hint write, say so and I'll open it as a separate PR
against the commit path. Otherwise I'd like to take the bounded risk here and keep the
commit path out of it.

Sub-second precision in thin_to_one_per is unchanged and still tested — only the policy
is constrained, so the bucketing itself stays exact if the minimum is ever relaxed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Understood. The accepted consequence is that concurrent expiry and hint publication can still make a non-lexical store resolve an older dataset version when expiry leaves a gap above the lowered hint. I will treat this as an accepted risk and will not pursue this finding further.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A floor on keep_one_per seems like a reasonable workaround.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. The one-hour floor reduces exposure, and the PR author has explicitly accepted the remaining hint/expiry race. I am keeping this finding addressed as an accepted risk.

The earlier branch tests only had a single branch off main, so they could not
distinguish "protection resolves against the branch being expired" from
"protection resolves against the root". A chain separates the two.

main -> b1 -> b2, where b2 is anchored to a version of b1 rather than of main:

- expiring on b1 must keep the version b2 is rooted at
- expiring on b2 must leave both b1 and main untouched

Verified non-vacuous: dropping branch-referenced versions from the protected set
expires [2, 3, 4] on b1, including b1@4 which anchors b2.

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ Gate recommendation: request changes.

The added nested-branch coverage does not change the version-hint race. The hint floor is still sampled without coordination with later best-effort hint writes, so expiry can create a gap that makes latest-version discovery silently return an older dataset state.

.map(|(_name, version)| version)
.collect();

let hint_floor = read_version_from_hint(&dataset.object_store, &dataset.base).await;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This remains the same race demonstrated in the previous discussion. An older committer can lower the hint after this snapshot; if expiry retains that hinted version but deletes its successor, probing stops at the gap and hides every newer manifest. The executed reproducer created versions 1–5, set the hint to 3, deleted version 4, and observed latest resolve to 3 instead of 5. The new branch tests do not change either side of that state transition.

Please make hint publication monotonic under concurrent writers (for example, with a conditional/CAS update), or otherwise ensure the hint cannot move below the floor used for deletion.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Sep 22, 2026
The version-hint floor is read once, and hint writes are unconditional, so a
commit that started earlier can publish a lower hint after the read. A gap above
that lowered hint hides every version above it and the table reads as an older
state while the newer manifests are still there.

`MIN_KEEP_ONE_PER` bounds the exposure rather than removing it: keeping survivors
an hour apart keeps deletions away from the seconds-wide window in which a stale
hint can land. Only a conditional hint write would make the floor monotonic, and
that is a change to the commit path, not to expiry.

Rejected in Rust before planning and in the Java builder, so no binding can
express a finer width. The Rust field doc, the Java javadoc and the Python
docstring all now carry the same warning, including that thinning is a repair for
a table carrying far more versions than it can hold rather than a default to
leave switched on.

The earlier sub-second precision tests move down to `thin_to_one_per`, which stays
exact; only the policy is constrained.

Verified non-vacuous: weakening the check back to a zero test fails with
"1ns is below the minimum and must be refused".
@jackye1995

Copy link
Copy Markdown
Contributor Author

Your read of the cost is right, and I like the approach better than mine — implemented in #9764.

I checked the premise before building on it. Reading a manifest feeds two sets:

let referenced_files = if in_working_set {
    &mut inspection.referenced_files   // live set
} else {
    &mut inspection.verified_files     // only used to honour delete_unverified
};

So the expired-manifest read exists solely for verified_files. With
delete_unverified=true that set is never consulted, and everything else cleanup wants
from an expired manifest — path, version, size, store identity — is already in the
listing. Retained manifests are still read, since the live set is what keeps cleanup from
deleting live data.

Two details that needed care:

Classifying "expired" without the manifest. should_clean takes a Manifest.
proven_expired answers from ManifestLocation and refuses to guess — false means "not
proven", never "retained", since getting that backwards deletes live data. before_version
and versions are exact from the filename. before_timestamp compares the object write
time, which is set after the commit time, so last_modified < cutoff proves
timestamp < cutoff; the converse doesn't hold, so a write time at or after the cutoff
falls back to reading. That needs last_modified carried through ManifestLocation —
the listing already received it in ObjectMeta and threw it away.

The listing cutoff. Skipping the read also loses that manifest's commit time, which
feeds read_dir_all(..., unmodified_since). With it unknown I drop the cutoff and scan the
subtree in full — missing a file orphans it permanently, an extra listing only costs time.

One scoping note. This covers the case you described, where a table accumulated versions
and nearly all are expired — on the table that motivated this, 9,786,716 of 9,787,115
manifests were past the window, so almost the entire read disappears. It does not help
the other shape I ran into: an actively committing table where the retained manifests are
themselves enormous (~10 MB each, ~364k inside a 7-day window), because those still have to
be read for the live set. That's what keep_one_per in #9438 was for, and I've left it out
of #9764 so this one stays about the read amplification. Happy to drop that idea entirely
if you think the retention knob isn't worth the version-hint exposure it carries.

@lance-gatekeeper lance-gatekeeper Bot removed K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Oct 7, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Oct 7, 2026
jackye1995 added a commit that referenced this pull request Oct 24, 2026
…is set (#9764)

When `delete_unverified=true`, cleanup skips reading expired manifests
selected by `before_version` or explicit `versions`. Retained, tagged,
and current manifests are still read to protect live files. This
addresses the expired-manifest read amplification discussed in #9438
without adding an API.

Timestamp policies always read the manifest's logical commit time.
Storage write timestamps cannot prove expiry because their clocks and
precision can differ from the writer's. Skipping any manifest read also
disables the directory-listing time cutoff so cleanup still finds all
expired files.

Rebased onto main and removed the unnecessary
`ManifestLocation.last_modified` change, resolving the Rust CI
compilation failures. Added regression coverage for timestamp precision
and clock skew, alongside read-skipping and retention coverage. Local
builds, tests, and clippy were omitted as requested; CI provides
validation. Formatting passed.
@lance-gatekeeper lance-gatekeeper Bot removed K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Nov 3, 2026

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Gate recommendation: approve with a non-blocking risk.

Merged #9764 now skips expired-manifest reads for version-filtered cleanup with delete_unverified=true, and #10306 adds cleanup retention thinning. This PR retains a distinct role when reading the history is itself unaffordable: it removes only manifests without reading them, reducing the read set for later cleanup. Thinning applies only beyond the selected full-history cutoff; snapshots inside that window still require their usual cleanup reads. Ordinary cleanup retention is the alternative when that read cost is manageable.

The author has accepted that concurrent expiry and hint publication can make a non-lexical store resolve an older dataset state when deletion leaves a gap above a lowered hint. The one-hour minimum and cross-language warnings reduce and surface exposure without eliminating the race; thinning remains a deliberate history-repair operation, not a default policy. No independent blocker remains.

Please mark this PR with the breaking-change label: lance_table::io::commit::ManifestLocation adds last_modified, so Rust callers constructing it with struct literals must initialize that field.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Nov 3, 2026
@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. and removed K-risk Latest Gatekeeper recommendation includes a non-blocking risk. K-approved Latest Gatekeeper recommendation permits acceptance. labels Nov 3, 2026

@Xuanwo Xuanwo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved after reviewing the latest-main integration and the focused safety fixes: detached expiry rejection, fail-closed version-hint reading, Python zero cutoff handling, and the no-manifest-read regression. Applicable checks on f1645b5 are complete; the remaining hint-concurrency limitation is the accepted non-blocking risk documented by Gatekeeper.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-encoding Encoding, IO, file reader/writer A-java Java bindings + JNI A-python Python bindings breaking-change enhancement New feature or request K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants