Skip to content

fix(index): keep HNSW deferred remap exact after a delete-then-rewrite history - #10846

Draft
LuQQiu wants to merge 6 commits into
mainfrom
lu/hnsw-deferred-remap-after-delete-then-rewrite
Draft

LuQQiu wants to merge 6 commits into
mainfrom
lu/hnsw-deferred-remap-after-delete-then-rewrite

Conversation

@LuQQiu

@LuQQiu LuQQiu commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Problem: deferred remapping must not renumber HNSW storage

An HNSW graph's node ids are positions in its partition's vector storage, not row addresses. FRI (Fragment Reuse Index) translates old row addresses after data is rewritten, allowing the existing index to be reused without rebuilding it.

Before this fix, the deferred-remap loader dropped rows that no longer had a mapping and compacted the remaining vectors. It did not renumber or rebuild the HNSW graph. That broke the graph-to-storage relationship.

A small example

Suppose a graph was built over these storage positions:

Position / graph node:    0    1    2    3
Vector:                  A    B    C    D

If B is deleted and a subsequent data rewrite leaves its old address unmappable, the loader used to return:

Storage position:        0    1    2
Vector:                  A    C    D
Graph node ids:           still 0, 1, 2, 3

Node 1 now addresses C instead of B, and node 3 has no vector at all. The regression reproduces this through a real tagged-FRI delete-then-rewrite history:

HNSW graph has 128 nodes but its vector storage has 123 rows, so 5 node(s) have no vector to score

A delete alone does not imply this failure: the demonstrated trigger includes a later rewrite and deferred translation that removes storage slots.

Why this matters for clustering

Clustering rewrites and redistributes data. Reusing an existing index across those rewrites relies on FRI address translation, so clustering followed by deletes and further maintenance can encounter this path.

The position-handling defect already exists in this PR's Lance base; it is not introduced by the separate coverage-withdrawal PR #10833. Clustering/FRI validation exposed it, rather than a clustering planner changing the HNSW graph incorrectly. The demonstrated case is a tagged-FRI rewrite history, not evidence that every historical Lance release or ordinary HNSW query is affected.

These are separate correctness requirements:

  • FRI/segment coverage determines which current rows an index segment covers.
  • HNSW storage layout determines which vector each graph node addresses.

Correct coverage alone cannot repair a graph whose node positions no longer match its storage.

Fix

Preserve positions when querying an existing graph

HNSW declares that its node ids bind storage positions. Its loader translates row addresses without removing slots:

Position / graph node:    0           1             2    3
Vector:                  A           B             C    D
Translated row id:       A'          TOMBSTONE     C'   D'

The deleted row's vector remains in its original slot, but its row id becomes RowAddress::TOMBSTONE_ROW. A tombstone-aware prefilter excludes it from results and live partition coverage. The graph can still use that position during search; no query-time graph rebuild or renumbering is needed.

IVF_FLAT and IVF_PQ do not have this graph-position dependency and retain their existing compact loading behavior.

Export only live rows when writing a new index

Preserved slots are a query-time representation, not rows to persist in a new index. Partition export, merge and explicit remap therefore consume a live-row view that excludes tombstones. Explicit HNSW remap uses the existing graph-rebuild fallback when removing slots requires it.

For PQ storage, live-row export uses the quantizer's own remap rather than filtering exported batch rows: PQ codes are transposed, so ordinary row filtering can associate one row with another row's code. The regression checks byte-exact row/code association and complete, duplicate-free live-row membership before and after explicit remap.

The IVF partition cache-key schema advances to version 2 to separate the changed cached-layout meaning. There is no index-file format change or HNSW search-algorithm redesign. This PR does not relax downstream HNSW maintenance guards.

Validation

  • The original delete/rewrite control fails before the layout fix with the node/storage mismatch above.
  • Maintenance controls check physical live rows and that no tombstone address is persisted.
  • The PQ export regression fails before its correction and passes with exact code association and membership assertions.
  • Native suites pass: 130 HNSW tests with one pre-existing ignored, 81 lower-level HNSW tests, 82 PQ tests, and 240 tests selected by the IVF-v2 filter. These ran on the same production code before the final test-only assertion strengthening. Published head c21fa99c2 separately passes the strengthened PQ regression, format checking and clippy.
  • Controls cover user-prefilter composition, selective/permissive filters, lower-level flat-scan/traversal dispatch, tombstoned nearest rows, and both query-warming orders across the delete/remap version boundary with fresh sessions. The dense-mask test proves masked nodes were distance-scored and excluded from output; it does not prove every scored node was expanded.

Claude re-reviewed published head c21fa99c2, confirmed both earlier findings resolved and found no new bugs, while recommending human review. This remains Draft, so Gatekeeper is skipped. Applicable pull-request CI workflows have not been created; the attempted close/reopen event repair was denied before execution. CI validation still requires an authorized human event repair, and the PR is not yet technically accepted.

Known limitation: explicit prewarm is not fixed

The separate Index::prewarm path still compacts deferred-remap HNSW storage before caching and can produce the same mismatch. This is a pre-existing follow-up, outside this PR. The warm-cache tests above warm through queries, not through Index::prewarm.

🤖 Generated with Claude Code

LuQQiu and others added 5 commits November 7, 2026 18:25
Answers whether query-time batch remapping is correct for IVF_HNSW_SQ at
this pin, where `segment_supports_batch_remapping` classifies it as
deferrable from the index file version alone.

Two passing tests exercise the real `Operation::Rewrite` commit path with
no eager remap: supported/translated coverage over the rewrite outputs,
indexed top-k equal to brute force (plain and prefiltered), the ANN node
retained, the BTree translated alongside, a multi-hop rewrite, a delete in
a rewritten output, and an old-version handle answering exactly after the
new version warmed the caches. A legacy pre-(0,3) vector file is confirmed
undeferrable: it is withdrawn from coverage and the query scans flat.

One ignored test pins a real divergence: deleting rows in a rewritten
output and then rewriting that output leaves the HNSW graph with more
nodes than its translated SQ storage has rows, so
`ensure_storage_covers_graph` fails the KNN. The flat scan and the BTree
answer correctly on the same history, so the fault is HNSW's node-id to
storage-row coupling rather than FRI translation.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
(cherry picked from commit 584f2ce265930886af93a491ec18c85541d97af8)
… rows

An HNSW graph's node ids are row numbers into its partition's vector
storage. With deferred index remapping the storage is translated at query
time, and the translation dropped every row it could not map (a source row
deleted before the rewrite that produced the mapping), compacting the rest.
That shifted the positions the graph holds and left the graph longer than
the storage, so a delete inside a rewritten output followed by a further
rewrite of that output failed the query outright:

  HNSW graph has 128 nodes but its vector storage has 123 rows, so 5
  node(s) have no vector to score

`IvfSubIndex` now reports whether it addresses its storage by row position
(`binds_storage_positions`, true only for HNSW). A partition of such a
sub-index is loaded preserving layout: a row the remap cannot map keeps its
slot carrying `RowAddress::TOMBSTONE_ROW`, so positions still match the
file's and rows equal nodes. Those slots are excluded from results through
the prefilter, which the search already consults, so traversal may pass
through a tombstoned node but no result can contain one, and the partition's
coverage no longer counts them. No graph rebuild, no graph renumbering and
no on-disk format change.

IVF_FLAT and IVF_PQ bind nothing by position and keep loading their
partitions compacted, byte for byte as before.

Covered by `hnsw_deferred_remap_is_exact_when_a_rewrite_follows_a_delete`,
which asserts the ANN node stays in the plan and that indexed top-k equals
the flat scan and brute force, plain and prefiltered, with no tombstoned or
retired address in the result.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
A partition of a position-binding sub-index is loaded preserving layout,
so a row the deferred remap could not map keeps its slot as
`RowAddress::TOMBSTONE_ROW`. That layout exists for the search alone;
every path that rewrites a partition's rows into a new index saw the
slots too. The eager remap (`remap_hnsw_partition`) was the corrupting
one: `QuantizerStorage::remap` keeps a row id absent from the mapping
unchanged, so a tombstoned slot would have been written into the new
storage and persisted as a graph node over no live row. The optimize
merge and the partition reader also loaded the slots and only dropped
them because the old-data filter happens to reject the tombstone's
fragment id.

Maintenance now reads partitions through `load_live_partition_storage`
and `PartitionEntry::live_batches`/`live_row_ids`, which drop tombstoned
slots up front: the remap translates live rows only, and a partition that
lost rows takes the existing log-and-rebuild branch exactly as before
layout was preserved. The search path is unchanged.

Covered by `hnsw_eager_remap_after_deferred_remap_drops_tombstoned_slots`:
after the delete-then-rewrite history, an inline remap of the segment
stores exactly the live rows, none of them the tombstone address, and
the remapped segment answers the ANN query exactly.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Compaction refuses `defer_index_remap: false` on a tagged FRI history
(dataset/optimize.rs), so the test's eager-compaction step could only
fail as NotSupported. Drive the same index rewrite through
`remap_column_index`, the eager path a tagged table actually has, and
keep the assertions on tombstoned slots and query exactness.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Tests on the delete-then-rewrite history that leaves tombstoned slots in
an IVF_HNSW_SQ partition. End to end: the tombstone mask composed with a
user prefilter, exactness on both sides of the flat-scan/traversal
selectivity threshold, recall held when the query's own nearest rows are
tombstoned, and both warming orders of an index cache across the
post-delete/pre-remap version boundary, each order on a fresh session so
the second really warms from cold.

The end-to-end predicates fix only global selectivity, so they do not
pin down which search branch a partition takes, and they cannot observe
which nodes a traversal visited; they are labelled exactness and recall
controls. The mechanism they rely on is proven at the sub-index level
instead: the existing test_subindex_prefilter_dispatch drives both
branches from controlled mask ratios, and a new
test_dense_prefilter_traverses_masked_nodes records the ids whose
distance was computed to show the dense traversal scores and expands
through a masked-off node rather than stopping at it, which is what
TombstoneAwarePreFilter relies on. The test-only CountingStorage now
records scored ids alongside its count.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@LuQQiu

LuQQiu commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@github-actions github-actions Bot added A-index Vector index, linalg, tokenizer bug Something isn't working labels Nov 9, 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.

Findings marked 🟡 are optional suggestions and need no follow-up push.

Additional findings (outside the current diff — GitHub can't attach inline comments there):

  • 🟣 rust/lance/src/index/vector/ivf/v2.rs — Pre-existing, left unfixed: users who prewarm an IVF_HNSW index under deferred remap still hit the node/row mismatch error this PR fixes for cold loads. Prewarm builds each HNSW partition through materialize_partition_for_prewarm (storage.rs:3235), which always compacts. It then caches that partition under the same IVFPartitionKey the search reads. Fix: make prewarm keep row slots for position-binding sub-indexes exactly as load_partition_storage does, e.g. pass a RowLayout into materialize_partition_for_prewarm and use RowLayout::Preserved when S::binds_storage_positions(). [also at: rust/lance-index/src/vector/storage.rs:3255 - pre-existing, left unfixed: users who prewarm an IVF_HNSW index under deferred remap still get compacted partitions and the "HNSW graph has N nodes but its vector storage has M rows" failure.]

    Why this was flagged

    Trigger: Index::prewarm (v2.rs:2927) on an IVF_HNSW_* index whose storage has a deferred remap (batch_remapper or frag_reuse_index) that cannot map some rows. That call runs prewarm_partitions -> IvfQuantizationStorage::materialize_partition_for_prewarm (storage.rs:3235-3295). That function hands the remapper to try_from_batch_with_quantizer/try_from_batch_with_remapper, which drops unmapped rows and compacts the rest. The resulting PartitionEntry is cached under IVFPartitionKey. Later queries hit that cache entry in load_partition_attached (v2.rs:2369), so they never go through the new RowLayout::Preserved path. The HNSW graph's node ids then point past or beside the shortened storage, which gives the "HNSW graph has N nodes but its vector storage has M rows" failure. The base branch fails the same way here, so this path is left unfixed. The PR's warm-cache tests warm the cache through queries, not through prewarm.

    Verification: pre-existing. The base already fails the same way by this route, and the PR fixes only the cold-load path. materialize_partition_for_prewarm (storage.rs:3235-3295) is unchanged by the diff. A later search reads the same key in load_partition_attached (v2.rs:2366-2394). It gets a cache hit and never reaches load_partition_storage, which is the only place that picks RowLayout::Preserved (v2.rs:2854-2860).

Comment thread rust/lance/src/index/vector/ivf/v2.rs Resolved
Comment thread rust/lance/src/index/vector/ivf/v2.rs Resolved
`PartitionEntry::live_batches` row-filtered the storage's exported
batches to drop the tombstoned slots a preserved-layout partition
carries. `ProductQuantizationStorage` keeps its codes transposed, one
byte of every row per stride, so filtering FixedSizeList rows removed
bytes from the middle of the column and left the surviving codes
attached to the wrong rows: `read_partition(.., with_vector = true)` on
an IVF_HNSW_PQ partition with tombstones returned corrupted codes. The
slots are now dropped through the storage's own `remap`, which rebuilds
layout-specific encodings row by row; the no-tombstone path is unchanged.

`IVFPartitionKey`'s schema version moves to 2: an HNSW partition entry
now caches the preserved layout, so a cache tier shared across releases
must not hand a compact-layout entry to this reader or the reverse.

Covered by `hnsw_pq_live_read_keeps_each_rows_codes_after_deferred_remap`:
on the delete-then-rewrite history, every live row's code bytes read
through the public partition reader equal the bytes the preserved-layout
partition held for that row id, no tombstone address is returned, and
the explicit remap stores exactly the live rows.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@LuQQiu

LuQQiu commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Two notes alongside c21fa99:

  • Prewarm: materialize_partition_for_prewarm still compacts the partition before caching, so a prewarmed IVF_HNSW partition does not keep the preserved layout this change relies on. That is pre-existing behaviour, untouched here, and tracked as a follow-up rather than folded into this Draft.
  • The description's wording on the CountingStorage test overstates what it checks. Accurate statement: test_dense_prefilter_traverses_masked_nodes proves that masked nodes were distance-scored and excluded from the output, not that every scored node was expanded.

🤖 Generated with Claude Code

@LuQQiu

LuQQiu commented Nov 9, 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 re-reviewed the latest head and found no new bugs. Because this is a large change to how IVF_HNSW partitions are loaded and searched under a deferred remap, a human look would still be worthwhile.

What was reviewed:

  • live_batches now drops tombstones through the storage's own remap, not a row filter on the batch, so transposed PQ codes keep the right rows.
  • The IVF partition cache-key schema is now version 2 (v2.rs), which keeps cache entries from before and after this change apart.
  • I also looked at the Preserved vs Compact layout choice in load_partition_storage, the TombstoneAwarePreFilter wrapping, and the builder's switch to load_live_partition_storage for the remap and merge paths.
Extended reasoning...

The change touches IVF/HNSW partition loading, the storage remap layout, prefilter composition, the partition cache key, and index rebuild paths across 6 files (about 1,670 added lines, most of them tests). It touches no auth, injection or data-exposure surface. The latest commit fixes both points from the earlier review: the PQ code order in live_batches and the cache-key version bump. I deferred because the change is large and correctness-critical for index search and remap. The Index::prewarm path is still a known, unfixed follow-up.

westonpace pushed a commit that referenced this pull request Nov 23, 2026
…e index (#11141)

## Summary

Deferred compaction (`defer_index_remap`) with deletions is currently
unusable for IVF_HNSW_* indices. When a partition loads through the
fragment-reuse index (FRI), its storage drops the deleted rows and every
later storage position shifts. The HNSW graph addresses storage by
position, so the partition fails to load ("HNSW graph has N nodes but
its vector storage has M rows"). Because of this, deferred remap is
gated off for HNSW tables.

This PR makes FRI auto-remap work for HNSW and fixes the physical remap
that follows.

1. **Load-time realignment (auto-remap).** When the loaded storage holds
fewer rows than the partition stores, the partition load computes where
each stored row landed and drops the removed nodes from the graph with
`remap_graph_batch`. If a level-0 walk from the entry point then misses
any survivor, the graph is repaired with `remap_graph_repair` instead.
This covers both the normal partition load and prewarm. Merge-only
compaction and non-HNSW sub-indices are unaffected: the check compares
counts from the partition metadata and does no extra I/O when nothing
was dropped.
- Drops are detected against the stored partition size, not the graph's
node count. HNSW graphs may legitimately cover only a prefix of their
storage, and those still load unchanged.
- New `IvfSubIndex` hooks: `positional_rows` and `remap_positions`,
which are no-ops by default.
- `IvfQuantizationStorage::partition_row_positions` maps each stored row
to its loaded position.
2. **Physical remap repairs instead of rebuilding.**
`remap_hnsw_partition` reads storage that FRI has already shrunk,
alongside the full graph from disk. The node counts never matched, so
every partition silently fell back to a full graph rebuild. The fix
composes the load-time positions with the remap's own removals and calls
`remap_graph_repair` once.

### Relation to #10846

#10846 (draft) addresses the same load-time
misalignment differently. It keeps deleted rows as tombstone slots, so
graph positions never shift, and filters them out at query time. Its
explicit remap still falls back to a rebuild. This PR is offered as an
alternative for the load-time part. The physical-remap repair fix (2) is
independent and could apply on top of either approach.

## Benchmark

The new `rust/lance/benches/hnsw_auto_remap.rs` restores a base
IVF_HNSW_SQ dataset, deletes rows, and compares four states:

- `pre`: deletions applied, no compaction yet.
- `auto`: after deferred compaction, auto-remap in effect.
- `phys`: after the physical remap.
- `rebuild`: after a full rebuild.

The results below were measured **before fix (2)**, so `phys` ≈
`rebuild` in them.

5M rows × 128-d, 1024 partitions, S3 from c7i.4xlarge (us-west-2):

| deleted | state | time to reach | cold prewarm | cold 1st query | warm
p50 | recall@10 |
|---|---|---|---|---|---|---|
| 1% | pre | – | 1.87 s | 1.09 s | 87 ms | 0.908 |
| 1% | auto | 4.5 s (compaction) | 4.84 s | 0.92 s | 58 ms | 0.904 |
| 1% | rebuild | 131 s | 2.85 s | 0.72 s | 54 ms | 0.904 |
| 10% | pre | – | 1.76 s | 0.73 s | 77 ms | 0.920 |
| 10% | auto | 3.8 s (compaction) | 4.70 s | 0.69 s | 43 ms | 0.912 |
| 10% | rebuild | 118 s | 2.65 s | 0.66 s | 51 ms | 0.902 |

- **Auto-remap** makes the index servable seconds after compaction
instead of after a roughly 2-minute remap or rebuild.
- **Its cost** is a one-time cold load, about 2.6× slower, plus about
0.5 points of recall from dropping edges. Warm query latency is
unchanged. (These runs predate the connectivity-gated repair; see the
local table below for its cost.)
- **The extra cold-load time** most likely comes from two extra reads
per partition: the row-id column and the full graph with its distance
column. Removing them is a possible follow-up.

Local 1M rows × 128-d, 256 partitions, **after fix (2)**: physical remap
logs zero rebuild fallbacks.

| deleted | repair (`phys`) | rebuild |
|---|---|---|
| 1% | 4.8 s | 8.2 s |
| 10% | 7.0 s | 7.2 s |
| 30% | 5.4 s | 5.6 s |

Local 1M rows, cold prewarm of the `auto` state as load-time realignment
evolved (`pre` ≈ 20 ms):

| deleted | drop edges only | always repair | repair only if stranded
(this PR) | recall (this PR / pre) |
|---|---|---|---|---|
| 1% | 152 ms | 4.2 s | 172 ms | 0.936 / 0.936 |
| 10% | 130 ms | 6.4 s | 213 ms | 0.934 / 0.935 |
| 30% | 137 ms | 5.0 s | 901 ms | 0.936 / 0.942 |

Repair cost scales with the share of nodes that lost a neighbor. That
share is about 1 − (1 − p)^30, so the gain is large at low deletion
rates and small at high ones.

## Tests

- `test_ivf_hnsw_defer_compaction_with_deletions` covers SQ/PQ × {load,
prewarm} × {33%, 95% deleted}. The 95% cases strand survivors when edges
are only dropped.
- `test_hnsw_prefix_graph_loads_without_dropped_rows` loads a graph
covering half its storage with no FRI.
- `remap.rs` unit tests check that a connected graph keeps the cheap
remap and a stranded one is repaired.
- `test_ivf_hnsw_physical_remap_after_deferred_deletions_repairs_graph`
asserts that edges of undamaged nodes survive the remap. Retention is
0.94 with fix (2) and 0.69 without.
- `cargo test -p lance --lib -- dataset::optimize index::vector hnsw`:
1460 passed. `cargo test -p lance-index --lib hnsw`: 82 passed.

## Lint

`cargo fmt --all` is clean. Clippy (`-p lance-index -p lance --no-deps
--tests --benches -D warnings`) reports nothing in the touched files.
**Blocker:** I could only run it with a local Rust 1.96 toolchain rather
than the pinned 1.98.1. That toolchain flags pre-existing
`nonminimal_bool` and `unreachable_code` lints in untouched files
(`scanner/fts.rs`, `io/exec/knn.rs`, `byte_stream_split.rs`), so CI
clippy is the authoritative check.

## Not in this PR

- Removing the data-plane gate that disables deferred remap for HNSW
tables.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

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

Labels

A-index Vector index, linalg, tokenizer bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant