Skip to content

fix(mem_wal): keep null rows out of memtable B-tree range filters - #9796

Merged
hamersaw merged 1 commit into
lance-format:mainfrom
xuanyu-z:fix/memtable-btree-null-ranges
Oct 9, 2026
Merged

hamersaw merged 1 commit into
lance-format:mainfrom
xuanyu-z:fix/memtable-btree-null-ranges

Conversation

@xuanyu-z

@xuanyu-z xuanyu-z commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

What

A memtable filter of the form value < x returned the column's null rows as matches. Every memtable B-tree backend lists null keys first in its snapshot, and BTreeIndexExec answered a range by comparing each snapshot key with the bounds; a null sorts below every value, so an open lower bound took it in. The answer is used as exact, so nothing removed those rows afterwards.

A range now skips null keys. The snapshot itself still lists them, since training reads it.

Testing

  • New an_open_lower_bound_excludes_nulls, over an integer, a string and a float column: fails on main (the null row comes back), passes with the fix.
  • cargo nextest run -p lance -E 'test(/mem_wal/)' passes (820 tests); cargo clippy -p lance --all-targets -- -D warnings and cargo fmt --all -- --check are clean.

Every memtable B-tree backend lists null keys first in its snapshot, and a range filter compared each key with the bound, so `value < x` returned the column's null rows as matches. A range filter now skips null keys.
@github-actions github-actions Bot added the bug Something isn't working label Oct 8, 2026
@xuanyu-z
xuanyu-z marked this pull request as ready for review October 8, 2026 21:18

@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 pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@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 range executor is the right boundary for enforcing SQL null semantics while keeping snapshots complete for index training.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 8, 2026
@hamersaw
hamersaw merged commit 9761a43 into lance-format:main Oct 9, 2026
hamersaw pushed a commit that referenced this pull request Oct 9, 2026
## Why

The memtable maintains exactly three index kinds, and which three is
written into the code: an enum of kinds, a config enum paired with it, a
per-kind arm in validation, one collection per kind in the store, and
two flush loops split by whether a kind trains from a value stream.
Adding a kind means touching all of them, and a caller cannot add one at
all.

## What changes

**A kind is a plugin.** `MemIndexPlugin` declares which base-table index
it maintains and builds instances; `MemIndex` is one instance: take
rows, answer what it recognises, report its memory, hand the flush what
it can save it. The B-tree, HNSW and inverted indexes become three
implementations. A `MemIndexSpec` describes one maintained index
(plugin, columns, field ids, resolved settings) and replaces
`MemIndexConfig` and its per-kind structs.

**Writers carry a registry.** `ShardWriterConfig::mem_index_registry`
(or `with_mem_index_registry`, `with_mem_index_plugin`) holds the
plugins a writer can maintain; the default is the three built-ins. A
type url reaches the plugin whose details message is exactly its own
message name. Two specs name the same index only when their plugins are
the same Rust type at the same version, so a plugin keeps whatever else
decides how it builds in the params it resolves. Under
`maintain_all_indexes` an index no registered plugin claims, or whose
columns do not resolve, is skipped with a warning; a named set is
validated against the plugins the writer will open with
(`validate_maintained_indexes_with`,
`update_mem_wal_maintained_indexes_with`,
`InitializeMemWalBuilder::mem_index_registry`). A maintained index's
columns resolve by field id to their full path, so an index on a nested
field is never bound to a top-level field of the same name.

**The contract callers rely on.** An index is asked, while planning, the
query it will be searched with (`can_answer`); only finding which
full-text granularities exist asks a probe. Declining at search time a
query it accepted while planning is an error, and so is a failed search;
neither becomes an empty answer. A filter may answer with candidates
(`MemSearchResult::at_most`), which the memtable re-checks against the
filter before returning them. A row past the readable count is dropped
from any answer, since its append may still fail. An index receives
every batch of one write in one call (`insert_batches`), so HNSW inserts
them as one graph range.

**Lookups go by capability, not type.** A query finds its index with
`IndexStore::index_answering(column, query)`, first by index name. The
primary-key index is a capability an index opts into
(`MemIndex::as_primary_key`). A user index on exactly the key column is
shared and remembered by its name, so a plugin may hand out a new
capability object on every call; otherwise the memtable keeps its own
B-tree outside the named indexes, where no user index name can collide
with it, and a filter on the key column still uses it. Rewrite tracking,
which decides whether a vector or full-text search may trust its own
top-k, runs whenever a primary key exists.

**The flush is one loop, one index at a time.** Each index writes
nothing, asks to be built from the written generation, hands back
training rows, or writes its own file (`FlushOutcome`). As before, the
vector and full-text kinds write nothing when they hold no rows, so an
empty list-element full-text index is not rebuilt as a whole-row one; a
B-tree with no keys is built from the generation's rows. The flush
builds only scalar types itself; a vector or full-text plugin asking it
to is refused by name. A scalar build takes rows in the shape the plugin
declares, through `CreateIndexBuilder::preprocessed_stream`.

**Nulls stay out of B-tree answers.** A range walks the backend from its
lower bound and never returns null keys, and a filter comparing with
null (`x IN (1, NULL)`) matches no null row. #9796 fixed the range case
in the code this replaces; its test passes here.

## Behaviour changes

Each was compared with `main` by running one seeded workload of writes,
seals, flushes and reopens against both builds and comparing every read;
these are the only differences.

- A memtable filter `x IN (1, NULL)` answered by the B-tree no longer
returns rows where `x` is null; `main` returned them, while SQL and a
base-table scan return none.
- Rewrite tracking (does a write replace a key the memtable holds?) runs
on every table with a primary key, since any plugin may cut a search to
its own top results; `main` ran it only beside a vector or full-text
index. Results are unchanged, and the cost does not show: 200 puts of
1,000 new keys each into a table with only a B-tree index took 26–27 ms
on this branch and 27–30 ms on `main` (release build, median of 5, 3
runs each).
- Under `maintain_all_indexes`, an index whose field is not in the
schema is skipped with a warning; `main` failed the writer open. An
index on a nested field is never bound to a top-level field of the same
name.
- Two different indexes under one name are refused; `main` kept the last
one silently. One index listed twice is still one index, as before.

## How a caller plugs in an index kind

A caller, such as LanceDB, implements two traits and hands the plugin to
the writer; everything else goes through them.

```mermaid
flowchart LR
    subgraph caller["Caller"]
        plugin["impl MemIndexPlugin<br/>name · details_message · version<br/>resolve · validate · create<br/>flush_index_type · training_criteria"]
        index["impl MemIndex<br/>columns · can_answer · search<br/>insert / insert_batches<br/>resident_bytes · flush<br/>as_primary_key (optional)"]
        plugin -- "create()" --> index
    end
    registry["MemIndexRegistry::default()<br/>.with_plugin(plugin)"]
    plugin --> registry
    registry --> config["ShardWriterConfig<br/>.with_mem_index_registry(..)"]
    registry --> check["validate_maintained_indexes_with<br/>update_mem_wal_maintained_indexes_with<br/>InitializeMemWalBuilder::mem_index_registry"]
    config --> writer["Dataset::mem_wal_writer"]
    base[("base-table index<br/>details type url")] -. "claimed by details_message" .-> registry
```

```mermaid
sequenceDiagram
    participant W as ShardWriter
    participant P as MemIndexPlugin
    participant S as IndexStore (one per memtable)
    participant I as MemIndex
    participant F as Flush
    Note over W,P: open
    W->>P: resolve(base index) → MemIndexSpec (columns, field ids, params)
    W->>P: validate(spec)
    Note over W,I: each new memtable
    W->>P: create(spec, capacity)
    P-->>S: MemIndex (on exactly the key column, as_primary_key() may share it as the key index)
    Note over W,I: write
    W->>S: insert_batches(one write)
    S->>I: insert_batches(every batch of the write, in one call)
    Note over W,I: read: filter, vector or full-text search
    W->>S: index_answering(column, the query to run)
    S->>I: can_answer(query)
    S->>I: search(query, max_visible)
    I-->>S: Filter{at_least, at_most} or Ranked, best first
    Note over S: candidates (at_most) are re-checked against the filter.<br/>Declining or failing a query it accepted is an error.
    Note over W,I: key lookups and dedup use PrimaryKeyIndex::newest_visible
    Note over W,F: flush, once the memtable is sealed
    F->>I: flush(generation)
    I-->>F: Skip, BuildFromGeneration, TrainingData(rows) or Wrote(metadata)
    F->>F: build the scalar index or record the written one in the generation
```

## Breaking changes

- Removed: `MemIndexKind`, `MemIndexConfig`, `BTreeIndexConfig`,
`HnswIndexConfig`, `FtsIndexConfig`, `validate_index_configs`,
`IndexStore::from_configs`. Replacements: `MemIndexSpec` (with `btree`,
`hnsw`, `fts` constructors), `validate_index_specs`,
`IndexStore::from_specs`.
- `ShardWriterConfig` gains a public `mem_index_registry` field;
`..Default::default()` fills it with the built-ins.
- `ShardWriter::open`, `ShardWriter::replace_index_configs` and
`ShardWriter::evolve_schema` take `Vec<MemIndexSpec>`.
- `IndexStore::insert_batches` returns `Result<()>`;
`IndexStore::from_specs` and `validate_index_specs` refuse two different
specs under one name.
- `MemIndexPlugin` requires `Any`; `PrimaryKeyIndex` no longer requires
`MemIndex`. `IndexStore`'s type-keyed lookups (`get_btree`,
`get_hnsw_by_column`, `get_fts_by_column` and the like) are removed;
`index_answering` and `fts_granularities_on` answer the same questions.

## Not in this PR

- Splitting `index/fts.rs` (7,800 lines) into smaller files: existing
code, a follow-up of its own.
- A `{name, field id}` column type in place of parallel lists, and fully
qualified details names in the registry: shape changes better made with
their next users.

## Testing

- A test plugin wraps a built-in under another type with the same name
and deviates one way at a time (declines the real search or only the
probe, accepts then declines or fails, answers with candidates or with a
row past the readable count, hands out a fresh key capability, cannot be
a key index, asks the flush to build it, fails or misnames its flush,
panics on insert). One table runs the filter, vector, full-text and
cross-column full-text searches against each deviation through the real
scan; the rest run through the real flush, store or writer.
- A user index named `__pk__id` on another column, beside a primary key
`id`, returns what the filter matches through fresh reads, an overwrite,
a delete, a flush and a reopen.
- Writer and API: one index named twice is maintained once and two
different ones under one name are refused; an index resolved to another
column takes its field id, or is skipped or refused when the column is
missing; a B-tree on a nested field is skipped under
`maintain_all_indexes`.
- Flush: an empty list-element full-text index writes nothing; a
full-text index with word positions answers a phrase query once flushed.
- Compared with `main`: one seeded workload (puts with overwrites and
nulls, deletes, seals, flushes, crash-and-reopen and close-and-reopen;
single and composite keys) ran against both builds, reading after every
step through filtered and projected scans with limits and offsets,
vector search, every full-text query kind, key lookups, `contains_pks`,
the routing of each memtable query, and the indexes of each flushed
generation. Over 200 seeds the only difference is the `IN (..., NULL)`
fix above; a run of `main` against itself shows the same run-to-run
variation in approximate vector results and ties at a full-text limit.
- Every test of a fix was checked to fail with the fix reverted.
- `cargo nextest run -p lance` passes (5,152 tests); `cargo doc -p
lance` with `-D warnings` and `cargo fmt --all -- --check` are clean;
`cargo clippy -p lance --all-targets -- -D warnings` reports only
`clippy::chunks_exact_to_as_chunks` in `index/vector/ivf.rs`, which
`main` also fails.
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.

3 participants