Skip to content

perf(rowids): probe the fragments instead of merging every row id - #8883

Merged
Xuanwo merged 13 commits into
lance-format:mainfrom
dshepelev15:rowid-index-probe
Sep 1, 2026
Merged

Xuanwo merged 13 commits into
lance-format:mainfrom
dshepelev15:rowid-index-probe

Conversation

@dshepelev15

Copy link
Copy Markdown
Contributor

Supersedes #8624 by @pengw0048, which no longer merges cleanly into main. This PR carries that branch's commits unchanged (every review finding on #8624 was addressed there, and the gate recommendation was approve), merges current main, and resolves the one conflict: main extracted TakeStream::resolve_row_addrs while #8624 made RowIdIndex::get fallible, so the helper now takes a fallible closure and both resolution paths propagate the lookup error.

Problem

RowIdIndex::new reads every row id of every fragment whose sequence is not a
plain Range. decompose_sequence has a constant-time path for
U64Segment::Range without deletions; every other encoding, and every fragment
that carries a deletion file, materializes one (row_id, address) pair per row,
sorts them, and re-encodes two segments. get_row_id_index builds the index for
the whole dataset, so a lookup of one row id pays for the whole table.

A delete puts a table on that path and keeps it there. While the deletion files
exist, the build checks the deletion vector row by row. After a compaction
materializes those deletions, the ids inside each fragment are no longer
contiguous, so the build decodes and re-encodes every row id instead.

The cost repeats: the index weighs about as much as the sequences it copies, so
on a large table it does not fit DEFAULT_METADATA_CACHE_SIZE, and the next
lookup builds it again.

Change

new picks one of two representations and never changes it.

  • The merged map is what it builds today, and it stays the default: a
    Range-only sequence decomposes in constant time, and a small table is cheap
    to read whatever its encoding.
  • A probe answers from one entry per fragment — the Arc<RowIdSequence>,
    the deletion vector, and each segment's row id range plus its physical start
    offset. new reads those bounds instead of every row id. A lookup binary-
    searches the fragments by their lowest row id, descends a max-end heap so a
    fragment out of reach of the id costs nothing, and asks the covering segment
    for position.

new probes only when both hold: the merged build would read more than
MERGE_ROWS_BUDGET row ids, and no more than MAX_PROBE_DEPTH fragments cover
any one id. So wherever the merged map reads faster, it is also the one new
builds.

An unsorted U64Segment::Array gets a sorted lookup table, built with the entry
and charged with it, because its own position scans. build_chunk_from_pairs
sorts its pairs for the same reason, which makes a merged chunk searchable too.

The integrity boundary

new no longer materializes ids on the probe path, so it cannot compare id sets
the way merge_overlapping_chunks does. The check moved to the lookup, where it
is free: a probe already visits every candidate fragment rather than stopping at
the first hit, and a second live match returns the same corrupt-index error the
merged build raises. get and get_many are fallible for this, and every
production caller propagates the error. validate_stable_row_ids remains the
complete offline check.

Checking at construction instead is possible but not cheap on the shape this PR
is for: proving overlapping id sets disjoint without reading them means
intersecting the sequences bit by bit, on the order of 10^10 word operations at
depth 46 over that table's id space, paid again on every process that opens the
dataset. The fallible lookup keeps the boundary without that cost.

Microbenchmarks (from #8624)

Release build, 96-core Linux x86-64. build is RowIdIndex::new; the lookup
columns are 100,000 random live ids.

shape build get get_many
1,000 fragments, 20M sparse ids, 2 fragments per id 0.22 ms vs 485 ms 236 ns vs 23 µs 175 ns vs 24 µs
4,000 fragments, 4M ids, every fragment covers every id 104.7 ms vs 101.5 ms 14 ns vs 13 ns 21 ns vs 18 ns
1,000 fragments, 20M contiguous ids, disjoint 0.23 ms vs 0.19 ms 36 ns vs 36 ns 16 ns vs 14 ns
1 fragment, 2M descending ids (unsorted Array) 7.6 ms vs 8.9 ms 203 ns vs 2 ms 55 ns vs 2 ms

Row 1 is the shape a compacted table has, and the merged map is slower to build
and slower to read there: merging the overlap produces one wide sparse segment
whose position counts bits up to the offset.

On a real table

Verified on a production dataset of 17,375,589,419 rows in 19,960 fragments on
S3, with stable row ids and a compaction history. Both sides are release wheels
built from this repository — before is current main (324cedd), after is
this branch. _take_rows of one column; each "first call" is a fresh process,
"second call" is the same process again. Dataset open (~69 s for this manifest)
is excluded.

before (main) after (this PR)
1 row id, first call 88.8 s 2.20 s
1 row id, second call 70.9 s 1.31 s
200 scattered row ids, first call 94.3 s 10.9 s
200 scattered row ids, second call 72.5 s 8.63 s

On main the second call pays almost the full price again: the merged index
outweighs the metadata cache and is rebuilt per lookup, which is the repeating
cost described above.

Closes #8621

Note for maintainers: the gate review on #8624 asked for the breaking-change
label (RowIdIndex::get/get_many became fallible); I cannot set labels on
this repository.

🤖 Generated with Claude Code

pengw0048 and others added 10 commits August 18, 2026 14:59
…e index

RowIdIndex::new walked every row id of every fragment whose sequence is
not a plain Range, and get_row_id_index builds the index for the whole
dataset, so one point lookup paid for the whole table. Keep one entry per
fragment with per-segment bounds instead, and resolve on lookup.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Peng Wang <[email protected]>
…eement

Build a row-id to position map for U64Segment::Array, the one encoding whose
position() walks the segment. Resolve get_many through get so the two APIs
return the same address for a row id that two fragments claim. Charge the
sequences, deletion vectors and position maps the index retains through its
Arcs, so a cache that weighs the entry bounds what the entry keeps alive.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Peng Wang <[email protected]>
…rlap

new() checks again that no row id is live in two fragments, so the integrity
boundary stays where it was. Two fragments can only claim an id where their
row id ranges intersect, so the check walks the intersecting pairs and only
the ids inside each intersection. Drops verify(), which no caller reached.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Peng Wang <[email protected]>
A prefix maximum cannot stop a backward walk once one fragment covers a wide
range, so a miss walked every fragment whose start sits below the id: 4.46 us
per miss at 16,384 fragments against 2 ns before this branch. Descend a
max-end tree instead, which holds at 233 ns as the fragment count grows.

Fragments whose ranges interleave produce a quadratic number of intersecting
pairs, and walking their ids cost 1.61 s at 2,048 fragments. Estimate that
work first and skip it above a budget; validate() runs it on demand. Fill the
array position table on first use so a table nobody looks up costs nothing,
which returns deep_size_of to what it was before the table existed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Peng Wang <[email protected]>
…cheap

Keep the merged map for the shapes it serves well, and answer from a
per-fragment probe otherwise. `new` reads each segment's bounds instead
of every row id, and builds the merged map when that build is cheap or
once probes have paid for it.
Three review findings, all of them about the lazy build:

- The representation is now chosen by `new` and never changes, so a cached
  entry cannot grow after its weight is fixed. The lazy upgrade was
  solving a case that does not exist: wherever the merged map reads faster
  it is also the one `new` builds, and where it does not, probing wins on
  both build and lookup.
- An unsorted `Array` segment gets a sorted lookup table, built with the
  entry and charged with it, so a probe binary-searches instead of
  scanning. `build_chunk_from_pairs` sorts its pairs for the same reason,
  which also makes a merged chunk searchable.
- A probe visits every candidate instead of stopping at the first hit, so
  a row id live in two fragments resolves the same way through `get` and
  `get_many`, and trips an assertion in a debug build.
…agments

The probe path visits every candidate fragment, so the duplicate check is
free; it now returns the same corrupt-index error the merged build raises,
instead of a debug assertion. get and get_many are fallible and every
production caller propagates the error.

Co-Authored-By: Claude Opus 5 <[email protected]>
Resolve the take.rs conflict by making resolve_row_addrs fallible so the
row id index lookup error propagates through both resolution paths.

Co-Authored-By: Claude Fable 5 <[email protected]>
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Aug 31, 2026
…ps the gate

The deep-overlap test read MERGE_ROWS_BUDGET ids per fragment, 68M in
total, and spent 27 s merging them. The gate only needs the total to
pass the budget while every fragment covers every id, so spread just
over the budget across the fragments. The probing-wins case likewise
needs one row past the budget, not twice the budget.

Co-Authored-By: Claude Fable 5 <[email protected]>
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Aug 31, 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 only prior finding is fixed: the threshold-selection coverage now exercises the same boundary with a lightweight fixture. The fragment-probe design addresses the measured cold-build cost while preserving lookup integrity and fallible error propagation.

Please mark this PR with the breaking-change label.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Aug 31, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Aug 31, 2026
# Conflicts:
#	rust/lance/src/dataset/optimize.rs
@Xuanwo
Xuanwo merged commit 0b030b1 into lance-format:main Sep 1, 2026
35 checks passed
Xuanwo pushed a commit that referenced this pull request Sep 3, 2026
…ps (#8930)

## Problem

`take_rows` by stable row id resolves ids through `RowIdIndex`, cached
per manifest version in
the metadata cache. On a large table the index never stays cached, and
each lookup pays a
popcount over a whole bitmap prefix.

Measured on a 17.4B-row table (19,960 fragments, stable row ids,
compacted after deletes, no
deletion files; inline row-id sequences 884 MiB, of which 849 MiB are
`RangeWithBitmap`
segments at ~82% density; the probe representation from #8883 is
selected):

- `DeepSizeOf for RowIdIndex` charges the `Arc<RowIdSequence>`s it holds
(897 MiB), and
`load_row_id_index` read those sequences through `load_row_id_sequence`,
which caches each of
them under its own `RowIdSequenceKey` (889 MiB). The same memory was
charged twice, 1.78 GiB
against the 1 GiB default budget, so the index was rejected on every
insert and rebuilt on
every `take_rows`: 0.10 s with the sequences cached, 0.85 s after file
metadata evicted them.
- `U64Segment::position` on a `RangeWithBitmap` counts the ones before
the offset with
`bitmap.slice(0, offset).count_zeros()`: a popcount over up to ~75 KB
per lookup. 35% of
  lookup time in `perf`.
- `RowIdIndex::probe` zero-initialised a 1.5 KB stack array on every
call: ~23% of the probe's
  own time in `perf annotate`.

## Change

`lance-table/src/rowids/index.rs`

- `probe` walks the implicit max-end heap without a stack: `(node, lo,
width)`, moving up while
the node is a right child and then over to the sibling. Visiting left to
right also lets it
  stop as soon as `lo >= upper`.
- `SegmentEntry` gains a `SegmentLookup` enum. `BitmapRank(Vec<u32>)`
holds the set bits before
each 256-byte block of a `RangeWithBitmap` bitmap (`RANK_BLOCK_BYTES`,
1/64 of the bitmap),
so `position` is one directory read plus a popcount of at most 255
bytes. The directory is
built in the same pass that counts the segment's rows, so the build does
not read the bitmaps
  an extra time. `Positions` is the existing unsorted-`Array` map.
- `RowIdIndex::sequence(fragment_id)` returns the sequence the index
holds for a fragment
  (`slots: HashMap<u32, usize>`).

`lance/src/dataset/rowids.rs`

- `load_row_id_index` decodes the sequences directly
(`read_row_id_sequence`) instead of through
the per-sequence cache. The index is then the sole owner of that memory,
its charge is exact,
  and it stays cached whenever it fits.
- `load_row_id_sequence` first asks this version's cached index for the
fragment's sequence and
returns that `Arc` — after checking that the fragment's `row_id_meta`
matches the committed
fragment, so an uncommitted rewrite of the same fragment id is never
answered from the index.
It falls back to the per-sequence cache as before. A scan with `_rowid`
after a take therefore
  does not cache a second copy of every sequence.
- Deletion vectors are read only for fragments that have a deletion
file; the `get_fragments()`
  clone of every `Fragment` is gone.

`lance-table/src/rowids/bitmap.rs`: `count_ones(&[u8])` becomes
`pub(super)`.

Unchanged: the merged representation and its lookups, the probe/merge
gate, and every `get`
result (the probe visits the same candidate set in the opposite order).

## Numbers

criterion, `row_id_index_shot_table` on the real table's row-id
sequences (19,960 fragments):

| bench | main | this PR |
|---|---|---|
| build (`RowIdIndex::new`) | 45.6 ms | 57.3 ms (rank directories; once
per version) |
| get_many/1 | 112 ns | 67 ns |
| get_many/1000 | 731 µs | 148 µs |
| get_many/100000 | 92.0 ms | 14.7 ms |
| get | 1.76 µs | 274 ns |

Same group on the synthetic shot-table-shaped data the bench generates
(2000 fragments):
get 422 → 126 ns, get_many/100000 24.8 → 8.0 ms, build 5.06 → 5.41 ms.

S3, fresh process, default 1 GiB metadata cache, the real table:

| | main | this PR |
|---|---|---|
| `get_row_id_index`, second call | 0.101 s (rebuilt) | 0.000 s (cached)
|
| `get_many(1000)` | 793 ns/id | 180 ns/id |
| `take_rows(1)`, warm rounds | 0.60–1.07 s | 0.46 s |
| `take_rows(200)`, rounds 1–3 | 10.6 / 13.7 / 9.1 s | 8.9 / 5.9 / 4.7 s
|

Control table with `Range`-only sequences (19,047 fragments, merged
representation, 16 MiB
index, already cacheable on main): parity within noise (`get` 82 → 83
ns, `get_many/1000`
70 → 72 µs, `take_rows(200)` warm 1.42 s both), and 984 cache entries
after the index instead
of 19,049.

The remaining `take_rows` time on the large table is reading each
fragment's full column
metadata (~1.2 MiB over the wire per fragment: the files are v2.0, which
always opens with full
metadata). That is outside this PR.

## Tests

- `test_probe_ranks_a_bitmap_wider_than_one_block`: every slot of a
bitmap spanning several
rank blocks resolves to the right offset, holes and out-of-range ids to
`None`.
- `test_sequence_by_fragment_id`: `sequence()` returns the held `Arc`,
`None` for a fragment
  without row ids and for an unknown id.
- `test_row_id_index_owns_the_sequences_it_caches`: building the index
adds exactly one cache
entry, a second `get_row_id_index` returns the same `Arc`,
`load_row_id_sequence` is answered
from the index without a new entry, and a rewritten fragment with the
same id is decoded
  instead of served from the index.
- Existing `rowids` tests in `lance-table` (103) and `lance` (37), and
`dataset::take` (31), pass.

`cargo fmt --all` and `cargo clippy --all --tests --benches -- -D
warnings` are clean.

## Notes

- Deletion vectors are still cached both under `DeletionFileKey` and
inside the index, so a
table with many deletion files still double-charges them. Out of scope
here.
- The `row_id_index_shot_table` criterion group builds shot-table-shaped
fragments: 44% compacted
in groups of 16 into 82%-dense bitmap and 1%-hole slices with
interleaving spans, the rest
  plain `Range`. `BENCH_SHOT_FRAGMENTS` scales the fragment count.

---------

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Point lookup by stable row id costs ~2 minutes of CPU when row-id sequences hold holes

3 participants