Skip to content

fix(index): translate only the rows a segment still owns through a tagged fragment-reuse history - #11399

Merged
LuQQiu merged 1 commit into
mainfrom
lu/fri-source-row-admission
Dec 1, 2026
Merged

LuQQiu merged 1 commit into
mainfrom
lu/fri-source-row-admission

Conversation

@LuQQiu

@LuQQiu LuQQiu commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

This PR fixes stale matches and duplicate rows after compaction when index row addresses are translated through a tagged fragment-reuse history.

An index segment has both an index file and a list of fragments it is allowed to serve (its fragment bitmap, stored in the manifest). These can differ: rewriting an indexed column removes the affected fragment from the bitmap, but leaves its old entries in the index file.

For example:

  1. Segment A indexes fragments 0 and 1.
  2. Values in fragment 0 are updated, such as i = 0 becoming i = 100. A now covers only fragment 1, but its file still contains the old entry for i = 0.
  3. optimize_indices adds segment B with the current values of fragment 0.
  4. Compaction combines fragments 0 and 1 into one new fragment, deferring index remapping. The reader translates the old row addresses to their new locations when the index is read.

Previously, the reader checked where an entry ended up, but did not check whether its starting fragment still belonged to that segment. A's obsolete entry and B's current entry could both reach the same new fragment and be returned.

As a result, i = 0 could match a row whose value is now 100, and a range query could return a row twice. Full-text searches could likewise match words removed from the text. A later index merge could copy those stale entries into the merged index.

The reproduction uses a custom compaction planner: the default planner does not combine fragments covered by different scalar index segments into one task.

Fix

Carry each committed segment's manifest bitmap into the row-address translation plan, and use it to filter entries as well as checking their destination.

  • Reject an entry if its starting fragment is directly covered by another segment of the same index.
  • Otherwise, require the entry to start in a fragment the segment owns, start in a descendant of an owned fragment, or pass through an owned fragment during translation.
  • Keep the existing checks for deleted rows, excluded intermediate fragments, and final coverage.

The descendant and intermediate checks preserve older layouts where the bitmap and stored row addresses refer to different stages of compaction.

Queries and index merges use the same ownership rules, preventing obsolete entries from being returned or copied into a new merged index in this scenario. The cache fingerprint also includes ownership, so cached translations cannot be reused under different ownership rules. Uncommitted (staged) segments keep their existing behavior.

Limitation

This does not repair an index that an earlier version already merged with stale entries. Once those entries have been stored at the new row addresses, fragment-level metadata cannot distinguish them from valid entries. Such an index needs to be rebuilt.

Tests

  • BTree regression tests compare indexed results with scans after compaction, after an optimize merge, and after an explicit segment merge. The explicit merge test also checks the entries written to the merged file.
  • An inverted-index regression test checks that removed words no longer match and rows are not returned twice.
  • Unit tests cover ownership across compaction chains and splits, compatibility with older layouts, deleted rows, cache fingerprints, and the known limitation.
  • A planning test verifies that both planning entry points use the committed segment's manifest bitmap while leaving staged segments unchanged.

@github-actions github-actions Bot added the bug Something isn't working label Nov 23, 2026
@LuQQiu

LuQQiu commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I reviewed this PR and didn't find any bugs. It changes which stored rows a committed segment is allowed to translate through a tagged fragment-reuse history, and it changes the translation fingerprint. A wrong rule here silently drops rows from or adds rows to index results, so a human who knows the deferred-remap design should still check the admission rule.

What was reviewed:

  • The new SegmentOwnership and reachable walk in frag_reuse_reader.rs, and how remap_row_ids_excluding applies ownership next to the existing exclusion and coverage checks.
  • How ownership is passed through both planning entry points (fri_query_plan, and plan_staged_segments, which looks up manifest bitmaps by UUID; staged segments get None), then into QueryRowIdRemapper and the DeepSizeOf accounting.
  • The fingerprint: a segment without ownership still hashes under the old /1 tag, so its cache keys are unchanged.
Extended reasoning...

The change adds about 1,500 lines across the fragment-reuse reader, query planning and the remapper, plus a new 705-line integration test module. It changes which index entries queries and optimize merges return after a deferred-remap compaction. It touches no auth, crypto or data-exposure surface, and CODEOWNERS does not cover these files. I deferred because the admission rule (excluded starts, descendants, hops landing in the stored bitmap) is subtle correctness logic. The PR also documents a known limitation for segments that were already merged. Both are judgments a maintainer should make, and passing tests alone don't settle them.

@LuQQiu

LuQQiu commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@LuQQiu
LuQQiu force-pushed the lu/fri-source-row-admission branch from c9d9a1d to 78c8558 Compare November 23, 2026 07:44

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code review found no issues

No high-confidence issues detected in this change.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.

Tip: disable this comment in your organization's Code Review settings.

lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Nov 30, 2026
@LuQQiu
LuQQiu force-pushed the lu/fri-source-row-admission branch from 78c8558 to 84b9f30 Compare December 1, 2026 00:40
@LuQQiu

LuQQiu commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Dec 1, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Dec 1, 2026

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Comment on lines 646 to +652
} else {
let fingerprint =
mapping.translation_fingerprint(&parts.coverage, &parts.excluded, &parts.path);
// A committed source owns what its manifest bitmap says, whichever
// bitmap the caller holds. A staged source keeps admitting every
// resolved row: its admission is not decided here.
let ownership = manifest_bitmaps
.get(&segment.uuid)
.map(|stored| mapping.segment_ownership(stored));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟣 pre-existing, not blocking: Pre-existing, left open by this fix: merging staged segments can still copy withdrawn entries into the merged index, giving stale matches and rows answered twice. Staged sources get ownership: None here, so a row starting in a fragment the replay withdrew is still translated and kept. Fix: give staged sources ownership built from their replayed segment.fragment_bitmap, via mapping.segment_ownership, so withdrawn starts are dropped on both planning paths. That bitmap is already narrowed by replay_staged_segments, and the hop rule still admits rows whose bitmap was projected to live fragments.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

Trigger: s1 is staged over F0 and F1 at version v. F0's indexed column is then rewritten in place, s2 is staged over F0 with the new values, and a deferred-remap compaction joins F0 and F1 into F2. Then merge_existing_index_segments([s1, s2]) runs. replay_staged_segments (provenance.rs:927) narrows s1 to {1}, but s1's file still holds the old F0 entry. plan_staged_segments (frag_reuse.rs:650) finds neither uuid in the manifest, so both plans get ownership: None. remap_row_ids_excluding (frag_reuse_reader.rs:623) applies start exclusion only when ownership.is_some(), so s1's stale F0 row translates to F2. F2 is not in s1's excluded set, and s1's coverage includes F2 because {s1:{1}, s2:{0}} fully covers the transition. The merged segment therefore stores both the old and the new entry for that row. This is the duplicate and stale-match bug the PR fixes for committed segments, still present on the staged path exactly as on the base branch.

Verification: Pre-existing (this PR leaves the staged path unchanged and the base behaves the same way). plan_staged_segments (frag_reuse.rs:650-652) gives both staged segments ownership: None. In remap_row_ids_excluding, the start-fragment drop is gated on ownership.is_some() && excluded_fragments.contains(...) (frag_reuse_reader.rs:623). s1's withdrawn F0 entry is translated to F2 and kept.

…gged fragment-reuse history

A committed index segment's stored bitmap can be narrower than its file:
a fragment whose indexed column is rewritten in place is withdrawn from the
bitmap while the file keeps the old entries. When a later compaction with
deferred index remap joined such a fragment with one the segment still
owned, the reader translated every stored row and filtered only by the
derived coverage, so the withdrawn entries were served again (stale values
and rows answered by two segments), and an optimize merge copied them into
the merged segment.

The reader now checks the start of each stored row against the segment's
manifest bitmap: a row is translated only if it starts in the stored
bitmap or a descendant of it, or passes through the stored bitmap on its
way, and a row starting in a fragment another segment covers directly is
dropped. The rule applies to committed segments wherever they are planned,
for queries and for index maintenance. Segments that are not in the
manifest yet keep the previous behavior.

Co-Authored-By: Claude <[email protected]>
@LuQQiu
LuQQiu force-pushed the lu/fri-source-row-admission branch from 84b9f30 to d97a192 Compare December 1, 2026 01:52
@LuQQiu

LuQQiu commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Dec 1, 2026

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Still open from earlier reviews (1):

  • Unresolved: 1 minor or pre-existing.

Comment on lines +2761 to +2814
async fn reachable_follows_every_transition_on_the_path() {
let cases: [Shape<'_>; 4] = [
(
"chain",
&[
(&[(0, 1)], &[(1, 1)], &[(0, 0)]),
(&[(1, 1)], &[(2, 1)], &[(1, 0)]),
],
&[2],
&[
(&[0], true, &[1, 2]),
(&[0, 1], true, &[1, 2]),
(&[2], true, &[]),
(&[2], false, &[0, 1]),
(&[0], false, &[]),
],
),
(
"split",
&[(&[(0, 2)], &[(1, 1), (2, 1)], &[(0, 0), (0, 1)])],
&[1, 2],
&[
(&[0], true, &[1, 2]),
(&[1], false, &[0]),
(&[1, 2], false, &[0]),
],
),
(
"join",
&[(&[(0, 1), (1, 1)], &[(2, 2)], &[(0, 0), (1, 0)])],
&[2],
&[
(&[0], true, &[2]),
(&[0, 1], true, &[2]),
(&[2], false, &[0, 1]),
],
),
(
"diamond",
&[
(&[(0, 2)], &[(1, 1), (2, 1)], &[(0, 0), (0, 1)]),
(&[(1, 1), (2, 1)], &[(3, 2)], &[(1, 0), (2, 0)]),
],
&[3],
&[
(&[0], true, &[1, 2, 3]),
(&[1], true, &[3]),
(&[1, 2], true, &[3]),
(&[3], false, &[0, 1, 2]),
(&[1], false, &[0]),
],
),
];
for (shape, steps, live, walks) in cases {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 nit (optional): Four ledger shapes run inside one test loop, so a failing shape hides the others and cannot be run alone. reachable_follows_every_transition_on_the_path loops over the cases array (chain, split, join, diamond), and the cases differ only in inputs. AGENTS.md:84 asks for rstest with #[case::{name}(...)] for this. Fix: make it an #[rstest] #[tokio::test] with #[case::chain], #[case::split], #[case::join] and #[case::diamond], each passing its history, live fragments and walks.

Why this was flagged

The new test at frag_reuse_reader.rs:2761 builds a cases: [Shape<'_>; 4] array and loops over it with for (shape, steps, live, walks) in cases at :2814. The four entries differ only in their inputs. When the "split" shape fails, the panic stops the loop, so "join" and "diamond" never run, and no single shape can be selected by name. The root AGENTS.md:84 requires rstest with #[case::{name}(...)] for tests that differ only in inputs, and this file already uses rstest elsewhere. On the base branch this test does not exist.

Verification: nit. reachable_follows_every_transition_on_the_path is new in this diff (frag_reuse_reader.rs:2761). It runs four cases with for (shape, steps, live, walks) in cases { at line 2814, and the cases differ only in inputs. Root AGENTS.md:84 asks for rstest with #[case::{name}(...)] here. The first failing assert panics and the later shapes do not run.

@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 projected-bitmap row-loss finding is fixed. Ownership filtering now preserves those rows while retaining sibling precedence for owned starts.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Dec 1, 2026
@LuQQiu
LuQQiu merged commit 47f14ab into main Dec 1, 2026
43 checks passed
@LuQQiu
LuQQiu deleted the lu/fri-source-row-admission branch December 1, 2026 18:15
LuQQiu added a commit that referenced this pull request Dec 1, 2026
…gged fragment-reuse history (#11426)

## Problem

After compaction moves rows into new fragments, an index can keep its
old row addresses and translate them when read. This PR fixes how
`optimize_indices` records coverage when merging scalar or inverted
index segments on tables with a tagged fragment-reuse history.

The merge already reads translated entries, so its output file contains
**current row addresses**. But its manifest bitmap—the list of fragments
the segment covers—still recorded the **historical fragment IDs** from
the input segments.

That mismatch makes the merged index depend on old compaction history
even though its entries have already been translated. Simply replacing
the bitmap with current fragment IDs is not enough: several segments may
each supply part of the same current fragment, so merging only some of
them must not claim the whole fragment.

## Example

Suppose segment S indexes fragment 0 and segment T indexes fragment 1. A
rewrite redistributes their rows into fragments 10 and 11, so **both S
and T are needed to serve each destination**. New data is then appended
as fragment 12.

With this change:

| Optimize selection | Result |
| --- | --- |
| Default optimize selects T only | Skip the merge. Keep S and T
unchanged and create a separate segment for fragment 12. |
| `merge(2)` selects S and T | Merge both with the new data. The
resulting file and bitmap cover `{10, 11, 12}`. |

T alone contains only part of the rows in fragments 10 and 11. S and T
together contain all of them, so their merged segment can safely claim
those fragments directly.

## Change

Before merging, use the snapshot's query plan to check the selected
segments' current coverage:

- Every selected segment must be accounted for. Segments that no longer
contribute coverage can still be removed by the merge.
- No segment left out of the merge may contribute to a fragment the
merged segment would claim.
- The selected coverage must not overlap the fragments being newly
indexed.

If these checks fail, or coverage cannot be verified, keep the existing
segments and index only the unindexed fragments, as append mode does. If
there are no unindexed fragments, do nothing. The check accepts or
declines the whole selection; it does not expand or shrink the merge
window.

An accepted merge records the selected segments' current coverage plus
the newly indexed fragments. This makes its metadata agree with its file
and lets cleanup remove old mapping history when no remaining index
needs it.

## Compatibility and limits

- Existing segments written with historical bitmaps remain readable;
this PR does not migrate them or change the reader rules from #11399.
- Default optimize may leave more segments than before. Combining them
requires a merge window that includes every contributor to the affected
fragments.
- Tables without tagged history, including v0 histories, keep their
previous behavior.
- Staged segments, vector merges, the explicit segment-merge API, and
inverted-index corpus statistics are outside this change.

## Tests

Regression tests cover accepted and declined merges for BTree and
inverted indexes, shared destinations, independently covered
destinations, superseded segments, and tables without tagged history.
They check manifest bitmaps and compare indexed results with scans after
reopening.

Additional checks verify that cleanup removes history after a complete
merge but retains it after a declined merge, and that overlay updates
remain visible across both paths and cleanup. The overlay cases use
manifest fixtures because normal overlay commits on tagged tables are
currently blocked.

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working K-approved Latest Gatekeeper recommendation permits acceptance.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants