Skip to content

fix: restore decrease max_fragment_id in manifest - #5554

Merged
majin1102 merged 5 commits into
lance-format:mainfrom
majin1102:fragment_id_travel
Dec 22, 2025
Merged

majin1102 merged 5 commits into
lance-format:mainfrom
majin1102:fragment_id_travel

Conversation

@majin1102

Copy link
Copy Markdown
Contributor

Related: #5540

@github-actions github-actions Bot added the bug Something isn't working label Dec 19, 2025
@lance-format lance-format deleted a comment from github-actions Bot Dec 19, 2025
@github-actions

Copy link
Copy Markdown
Contributor

Code Review

Summary

This PR fixes a bug where max_fragment_id can decrease when restoring an older dataset version. The fix ensures that after a restore, the max_fragment_id is the maximum of the restored manifest's value and the current manifest's value.

Analysis

The fix is correct and important. The max_fragment_id is used as a monotonically increasing counter to assign unique fragment IDs. When it decreases, newly created fragments could get IDs that were previously used, causing conflicts with:

  • Index fragment bitmaps (see index/prefilter.rs:64)
  • Fragment-based filtering logic (see index/append.rs:542)
  • Deletion masks

The fix approach is sound: Taking the max of the restored and current manifest's max_fragment_id preserves the monotonicity invariant.

P1 Issues

  1. Test assertion may be flaky: The test calls restore() but then checks dataset_v1.manifest.max_fragment_id(). However, restore() doesn't update the in-memory manifest of the dataset object being used. You should reload the dataset after restore:
// Instead of:
dataset_v1.restore().await.unwrap();
let restored_max = dataset_v1.manifest.max_fragment_id().unwrap_or(0);

// Consider:
dataset_v1.restore().await.unwrap();
let restored_dataset = Dataset::open(test_uri).await.unwrap();
let restored_max = restored_dataset.manifest.max_fragment_id().unwrap_or(0);

Otherwise the test may pass even if the fix doesn't work correctly, since you're checking the old version 1 manifest, not the newly created restored manifest.


Overall this is a good bug fix for an important invariant. Please verify the test is checking the correct manifest.

@github-actions

Copy link
Copy Markdown
Contributor

Code Review

Summary

This PR fixes a bug where restoring an older version of a dataset could decrease max_fragment_id, which could lead to fragment ID collisions when new fragments are created after a restore operation.

P0 Issue - next_row_id has the same vulnerability

The fix for max_fragment_id is correct, but next_row_id has the same issue. When restoring an older version, next_row_id from the old manifest will also be restored, which could cause row ID collisions if the dataset uses stable row IDs.

The fix should also include:

manifest.next_row_id = manifest.next_row_id.max(current_manifest.next_row_id);

This is a critical bug for datasets with stable row IDs enabled, as it could cause duplicate row IDs after a restore operation.

Minor: Test should verify newly restored manifest from disk

The test checks dataset_v1.manifest after calling restore(). While this works because apply_commit updates the in-memory manifest, it would be more robust to also re-open the dataset from disk and verify the persisted max_fragment_id:

// Also verify persisted value
let reopened = Dataset::open(test_uri).await.unwrap();
assert!(reopened.manifest.max_fragment_id().unwrap_or(0) >= latest_max);

@codecov

codecov Bot commented Dec 19, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.29630% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
rust/lance/src/io/commit.rs 95.65% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@wjones127 wjones127 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.

Thanks for doing this. Since we ruled out issues with branches, I agree we just need to fix restore. This solution looks good to me.

Just have some minor suggestions for the tests.

Comment thread rust/lance/src/io/commit.rs Resolved
Comment thread rust/lance/src/io/commit.rs Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Code Review

Summary: This PR fixes a bug where restore() could decrease max_fragment_id, potentially causing fragment ID collisions when new fragments are created after restoring to an earlier version.

Assessment: LGTM ✓

The fix is correct and minimal. The approach of taking the max of the restored manifest's max_fragment_id and the current manifest's max_fragment_id ensures monotonicity.

Minor suggestions (non-blocking):

  1. Test assertion could be stronger: The test verifies restored_max >= latest_max, but since max_fragment_id should be strictly monotonic and version 1 had a lower value, you could assert restored_max == latest_max to be more precise about the expected behavior.

  2. Consider edge case: When current_manifest.max_fragment_id is None (legacy datasets without this field), the .max() will work correctly because None is compared as less than Some(_). This is fine, just noting for documentation.

The test coverage is appropriate for this bug fix.

@github-actions

Copy link
Copy Markdown
Contributor

Code Review

Summary: This PR fixes a bug where restoring an older version could decrease max_fragment_id, which would cause fragment ID collisions on subsequent writes.

Assessment

The fix is correct and well-tested. The approach ensures that when restoring from an old manifest, the max_fragment_id from the current manifest is preserved if it is higher than the restored version.

No P0 or P1 issues found.

Minor observation (not blocking):

  • The test uses memory:// as recommended in CLAUDE.md - good practice.
  • Both call sites (do_commit_detached_transaction and commit_transaction) are updated consistently.

@github-actions

Copy link
Copy Markdown
Contributor

Code Review

P0: Bug - Type mismatch between Option<u32> and Option<u32>.max()

The fix at transaction.rs:1541-1543 has a type issue:

manifest.max_fragment_id = manifest
    .max_fragment_id
    .max(current_manifest.max_fragment_id);

Here max_fragment_id is Option<u32> (see manifest.rs:74). The Option::max() method compares options where None < Some(_), so this mostly works. However, this creates a subtle behavior issue:

  • If manifest.max_fragment_id = None and current_manifest.max_fragment_id = Some(5), result is Some(5) ✓
  • If manifest.max_fragment_id = Some(3) and current_manifest.max_fragment_id = None, result is Some(3) ✓
  • If both are Some, takes the max ✓

The logic is actually correct due to how Option::max() works (None is considered less than Some). After further analysis, this is not a bug - the implementation is correct.

Suggestion: Consider using the accessor method

For consistency with the rest of the codebase, consider using the max_fragment_id() accessor method instead of directly accessing the field, though the current approach is also valid:

manifest.max_fragment_id = manifest
    .max_fragment_id
    .max(current_manifest.max_fragment_id);

The accessor max_fragment_id() returns Option<u64> and computes from fragments if not set, but directly accessing the Option<u32> field is appropriate here since we want to preserve the stored high water mark.

Test Coverage ✓

The test test_restore_does_not_decrease_max_fragment_id properly validates the fix by:

  1. Creating a dataset and appending data to advance max_fragment_id
  2. Restoring an earlier version
  3. Asserting max_fragment_id doesn't decrease

LGTM - the fix is correct and the test coverage is appropriate.

@majin1102
majin1102 merged commit 42b5938 into lance-format:main Dec 22, 2025
wjones127 added a commit to wjones127/lance that referenced this pull request Dec 30, 2025
jackye1995 pushed a commit to jackye1995/lance that referenced this pull request Jan 21, 2026
wjones127 added a commit to wjones127/lance that referenced this pull request Jul 29, 2026
Fragment ids must be globally unique across a dataset's history because
per-fragment objects are cached by id. `WriteMode::Overwrite` restarted
the counter at 0, so the fragments it wrote aliased the ones they
replaced. Restore was fixed the same way in lance-format#5554; overwrite was the
remaining hole.

Fragment ids now continue from the manifest's high water mark on
overwrite, so the first fragment an overwrite writes takes the next
unused id.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
wjones127 added a commit to wjones127/lance that referenced this pull request Aug 3, 2026
`WriteMode::Overwrite` restarted fragment id allocation at 0, so the
fragments it wrote took ids that earlier generations of the dataset had
already used. Anything keyed by fragment id — cached row id sequences,
deletion files, row addresses — can then be attributed to rows it was not
written for. lance-format#8075 was one instance of that.

Overwrite now allocates from the dataset's high water mark like every other
operation, which is the invariant discussion lance-format#5540 asks for and that lance-format#5554
established for restore. An overwrite's fragments are newly written by
definition, so every one of them takes a fresh id and the id it arrives with
is ignored — no need to guess whether an incoming id 0 means "assign me one"
or names an existing fragment.

A deletion file is the one thing that cannot follow its fragment to a new id,
because the deletion file path embeds the fragment id. A fragment carrying one
therefore belongs to the dataset being replaced, and the operation is now
rejected with an error pointing at Delete or Merge. Two in-repo tests took
that shortcut and move to the operation that models what they do.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
wjones127 added a commit to wjones127/lance that referenced this pull request Aug 3, 2026
`WriteMode::Overwrite` restarted fragment id allocation at 0, so the
fragments it wrote took ids that earlier generations of the dataset had
already used. Anything keyed by fragment id — cached row id sequences,
deletion files, row addresses — can then be attributed to rows it was not
written for. lance-format#8075 was one instance of that.

Overwrite now allocates from the dataset's high water mark like every other
operation, which is the invariant discussion lance-format#5540 asks for and that lance-format#5554
established for restore. An overwrite's fragments are newly written by
definition, so every one of them takes a fresh id and the id it arrives with
is ignored — no need to guess whether an incoming id 0 means "assign me one"
or names an existing fragment.

A deletion file is the one thing that cannot follow its fragment to a new id,
because the deletion file path embeds the fragment id. A fragment carrying one
therefore belongs to the dataset being replaced, and the operation is now
rejected with an error pointing at Delete or Merge. Two in-repo tests took
that shortcut and move to the operation that models what they do.

Commits are also now rejected outright when they would leave two fragments
sharing an id, which nothing checked before. This runs after the legacy
manifest fixups so that a dataset needing a rollback for some other reason
still gets that diagnosis first.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
wjones127 added a commit that referenced this pull request Aug 5, 2026
Independent of #8078, which fixes the same #8075 symptom at the cache
layer; whichever lands second will hit a one-line conflict on the
fragment id assertion in `test_row_ids_overwrite`.

Overwriting a dataset restarted fragment id allocation at 0, so the
fragments an overwrite wrote took ids that earlier generations of the
dataset had already used. Anything keyed by fragment id — cached row id
sequences, deletion files, row addresses — can then be attributed to
rows it was never written for. #8075 was one instance: readers sharing a
`Session` across an overwrite were served the previous generation's row
id sequence for the reused id.

Overwrite now allocates ids from the dataset's high water mark, like
every other operation. This is the invariant discussion #5540 asks for —
a fragment id must never name two different sets of rows over a
dataset's history — and #5554 already established it for restore.

An overwrite's fragments are newly written by definition, so every one
of them takes a fresh id and the id it arrives with is ignored. That
sidesteps the ambiguity that makes this change awkward otherwise: id 0
doubles as "no id assigned yet", so for a payload that mixed new and
carried-over fragments there would be no way to tell which is which.

A deletion file is the one thing that cannot follow its fragment to a
new id, because its path embeds the fragment id
(`_deletions/{fragment_id}-{read_version}-{id}`). A fragment carrying
one therefore belongs to the dataset being replaced, and such an
operation is now rejected with an error pointing at `Delete` (to commit
deletions against existing fragments) or `Merge` (to change their
schema). Everything else survives renumbering: data files and overlays
carry explicit paths, and row id sequences are resolved through the
fragment's current id.

Two in-repo tests took that shortcut and move to the operation that
models what they do: the Rust `test_append_new_columns` now commits with
`Merge` (which is what `add_columns` uses in production), and Python's
`test_deletion_file` with `Delete`.

Commits that would leave two fragments sharing an id are also rejected
now, which nothing checked before. `Append` still honors an id a
fragment arrives with, so a caller can hand in one that is already taken
— that is how the checked-in
`test_data/v0.16.0/wrong_data_version_no_fix.lance` fixture ended up
with fragment ids `[0, 1, 1, 2]`: its creating transaction passed `[0,
1, 2, 0]` and the counter handed the last one the 1 that was already in
use. The check runs after the legacy manifest fixups, so a dataset that
needs a rollback for some other reason still gets that diagnosis first
(that fixture reports its mixture of file versions, as before).

## Not included

`lance-namespace-impls` has its own copy of this id assignment for the
internal manifest dataset
(`ManifestNamespace::manifest_from_overwrite_transaction`), which builds
a manifest directly rather than going through
`Transaction::build_manifest`. It still restarts at 0 and is left alone
here.

The ambiguity around id 0 goes away for good once a transaction type
distinguishes existing fragments from newly minted ones; the rejection
above is the interim guard rather than the end state.

## Breaking changes

Fragment ids no longer restart at 0 after an overwrite — the first
fragment an overwrite writes takes the next id after the dataset's
highest ever used. Code that assumes a specific id afterwards (e.g.
`dataset.get_fragment(0)`) needs to read the ids from the manifest
instead.

Committing an `Overwrite` whose fragments carry a deletion file now
fails instead of silently reusing ids. Use `Delete` or `Merge` instead.

Datasets that already contain duplicate fragment ids — Lance 0.16 and
earlier could write them — can still be read, but can no longer be
committed to. They have to be rewritten, or rolled back to a version
without the duplicate.

Addresses discussion #5540.

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
wjones127 added a commit that referenced this pull request Aug 6, 2026
`RowIdSequenceKey` was keyed on `fragment_id` alone, while the metadata
cache is namespaced by dataset URI only. Fragment ids restart at 0 after
`WriteMode::Overwrite`, so with a `Session` shared between the writer
and the reader, every read after an overwrite was served the previous
generation's `RowIdSequence` for the reused id.

That silently corrupts stable row ids: row ids are reported for rows
that no longer exist, row counts disagree with the manifest, compaction
rechunks more ids than the fragments physically hold, and the same id
can look live in two fragments at once.

The key now also carries the fragment's `row_id_meta`, which identifies
where the sequence bytes live. Identical metadata implies identical
sequence bytes, so a hit is always a valid hit, while a rewritten
fragment misses. Operations that leave row ids alone (deletes, added
columns) keep hitting the cache. This matches the sibling
`DeletionFileKey`, which already keys on the deletion file's identity
rather than the fragment id alone.

## Why not make fragment ids unique instead

Discussion #5540 asks for `fragment_id` and `row_id` to be globally
unique across a table's history, and #5508 was closed in favour of that
over a version-scoped cache key. Seeding the id counter from
`max_fragment_id` on overwrite (the restore half shipped as #5554) is
*not* a drop-in: `Fragment::id == 0` doubles as the "unassigned"
sentinel in `Transaction::fragments_with_ids`, and today's overwrite
masks that by starting the counter at 0, so a real fragment 0 is
"reassigned" 0. With a high-water-mark counter, a pre-existing fragment
passed through `Operation::Overwrite` — a supported public pattern, e.g.
`LanceOperation.Overwrite(schema, fragments)` with fragments from
`get_fragments()` — is renumbered, orphaning its deletion vector at
`_deletions/{old_id}-…`. `test_append_new_columns` catches exactly this.

So #5540 needs the sentinel made explicit first, and is left to a
follow-up. Content-keying is correct independently of it, and also
covers ids reused by paths that never consult a previous manifest: drop
a dataset and create a new one at the same URI (#7645), or datasets
written before any id-allocation change that already hold duplicate ids
in their history.

This does not fully close #7645. A dataset recreated at the same URI
restarts at version 1, and the version-scoped keys that do not carry the
manifest e-tag — `TransactionKey`, `RowIdIndexKey`, `RowAddrMaskKey`,
and `IndexMetadataKey` in the index cache — still collide with the
previous generation. `ManifestKey` already carries the e-tag; extending
that to the rest is a follow-up.

Fixes #8075

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
mmatczuk pushed a commit to rerun-io/lance that referenced this pull request Nov 2, 2026
…at#8078)

`RowIdSequenceKey` was keyed on `fragment_id` alone, while the metadata
cache is namespaced by dataset URI only. Fragment ids restart at 0 after
`WriteMode::Overwrite`, so with a `Session` shared between the writer
and the reader, every read after an overwrite was served the previous
generation's `RowIdSequence` for the reused id.

That silently corrupts stable row ids: row ids are reported for rows
that no longer exist, row counts disagree with the manifest, compaction
rechunks more ids than the fragments physically hold, and the same id
can look live in two fragments at once.

The key now also carries the fragment's `row_id_meta`, which identifies
where the sequence bytes live. Identical metadata implies identical
sequence bytes, so a hit is always a valid hit, while a rewritten
fragment misses. Operations that leave row ids alone (deletes, added
columns) keep hitting the cache. This matches the sibling
`DeletionFileKey`, which already keys on the deletion file's identity
rather than the fragment id alone.

Discussion lance-format#5540 asks for `fragment_id` and `row_id` to be globally
unique across a table's history, and lance-format#5508 was closed in favour of that
over a version-scoped cache key. Seeding the id counter from
`max_fragment_id` on overwrite (the restore half shipped as lance-format#5554) is
*not* a drop-in: `Fragment::id == 0` doubles as the "unassigned"
sentinel in `Transaction::fragments_with_ids`, and today's overwrite
masks that by starting the counter at 0, so a real fragment 0 is
"reassigned" 0. With a high-water-mark counter, a pre-existing fragment
passed through `Operation::Overwrite` — a supported public pattern, e.g.
`LanceOperation.Overwrite(schema, fragments)` with fragments from
`get_fragments()` — is renumbered, orphaning its deletion vector at
`_deletions/{old_id}-…`. `test_append_new_columns` catches exactly this.

So lance-format#5540 needs the sentinel made explicit first, and is left to a
follow-up. Content-keying is correct independently of it, and also
covers ids reused by paths that never consult a previous manifest: drop
a dataset and create a new one at the same URI (lance-format#7645), or datasets
written before any id-allocation change that already hold duplicate ids
in their history.

This does not fully close lance-format#7645. A dataset recreated at the same URI
restarts at version 1, and the version-scoped keys that do not carry the
manifest e-tag — `TransactionKey`, `RowIdIndexKey`, `RowAddrMaskKey`,
and `IndexMetadataKey` in the index cache — still collide with the
previous generation. `ManifestKey` already carries the e-tag; extending
that to the rest is a follow-up.

Fixes lance-format#8075

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
(cherry picked from commit 4d63a12)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants