Skip to content

feat(mem_wal): evaluate compound FTS queries on the active memtable - #9160

Merged
hamersaw merged 2 commits into
mainfrom
feat/memwal-fts-compound-queries
Sep 14, 2026
Merged

hamersaw merged 2 commits into
mainfrom
feat/memwal-fts-compound-queries

Conversation

@hamersaw

Copy link
Copy Markdown
Contributor

The active memtable refused every compound full-text query. A boolean or boost query against a MemWAL table whose memtable held an FTS index on the searched column failed outright, and validate_lsm_fts_query rejected it one layer up too — so the only way to get an answer was to exclude the memtable and read stale.

The capability was already there

FtsQueryExpr (mem_wal/index/fts.rs) has nested Boolean (must/should/must_not over arbitrary sub-queries) and Boost with an optional negative clause, and has since it was written. What was narrow was the scanner's intermediate FtsQueryType:

  • its Boolean variant flattened to Vec<String> terms, so nesting was unrepresentable
  • it had no Boost variant at all
  • local_fts_query refused compound shapes before reaching either

So this is mostly deletion. MemTableScanner's FtsQuery now carries an FtsQueryExpr directly, local_fts_query maps the index-level FtsQuery onto it recursively, and the hand-written enum-to-enum conversion in exec/fts.rs goes away — it was translating between two types that now agree.

The scanner's public builders (full_text_boolean, full_text_phrase, full_text_fuzzy*) keep their signatures, so callers are unaffected.

What still gets refused

validate_lsm_fts_query relaxes to a recursive walk with two restrictions left, both real rather than incidental:

  • fuzzy + operator=And — the fuzzy path expands each term independently and unions the expansions, so it cannot also require every term to match. This was already rejected; it just now applies at any depth.
  • multi-match — it spans columns, and the memtable holds one inverted index per column, so there is no single index to search. Cross-column support is separate work.

Column and document granularity are resolved once for the whole query rather than per leaf, since the memtable searches a single index; mixing Row and ListElement granularities across clauses is an error.

Tests

  • boolean_query_reaches_the_active_memtable — the point of the change. Base table and active memtable each hold matching rows; a MUST lance / MUST_NOT beta query returns the base row and the memtable row, and drops the memtable row carrying beta. Both clauses have to survive to the in-memory index for that to hold.
  • multi_match_query_is_refused_by_the_active_memtable — the remaining refusal, with the reason in the message.
  • local_fts_query_maps_leaf_shapes_and_rejects_the_rest extended: boolean clause-for-clause, boost with its negative clause and demotion factor, a boolean nested inside a boolean (asserting the nesting isn't flattened), and multi-match still refused.

700 mem_wal tests pass; clippy clean on the changed files.

Downstream

This unblocks the corresponding sophon work — the WAL read arm can then carry boolean and boost queries to the fresh tier instead of silently answering from base fragments alone.

🤖 Generated with Claude Code

https://claude.ai/code/session_01QBv2WLSq5oy6kR2gVrfFDh

@github-actions github-actions Bot added the enhancement New feature or request label Sep 11, 2026
@hamersaw
hamersaw marked this pull request as ready for review September 12, 2026 01:12
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Sep 12, 2026
@hamersaw
hamersaw force-pushed the feat/memwal-fts-compound-queries branch from e1e4605 to f37e6c0 Compare September 12, 2026 11:11
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Sep 12, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 12, 2026
@hamersaw

Copy link
Copy Markdown
Contributor Author

Pushed a revision addressing the gate.

Boost is now refused rather than mapped. The two sides disagree on what negative_boost means, not just how it is applied: FtsQueryExpr::Boost multiplies a demoted row's positive score by it and discards the negative score, so 1.0 is "no demotion"; the public compound scorer subtracts negative_boost * negative_score, where 0.0 is. Mapping one onto the other would have active rows rank differently from committed rows for the same query, which is exactly what the reproducer shows.

Reconciling them means changing the memtable's established boost semantics — three existing tests pin the multiplicative form (test_boost_query_negative_boost_factor asserts s_half ≈ s_no * 0.5) — so that is its own commit with its own reasoning, not something to fold into a compound-query PR. Taking the second option you offered.

This PR now delivers boolean only. The Boost mapping test became an assertion that Boost is refused, and validate_lsm_fts_query rejects it at the LSM layer too, so neither tier can reach it. Multi-match stays refused here and is lifted in #9172.

@hamersaw
hamersaw force-pushed the feat/memwal-fts-compound-queries branch from f37e6c0 to 69f7f2c Compare September 12, 2026 12:49
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 12, 2026
@hamersaw

Copy link
Copy Markdown
Contributor Author

Revised again — boost now works rather than being refused, which is the better answer to your finding.

The memtable's search_boost applies the subtractive contract: positive - negative_boost * negative_score for a document the negative clause also matches, positive otherwise. That is BoostScorer::score verbatim, so both tiers rank a boost query identically. It needed the negative score rather than just membership, so the key set became a map. Scores may go negative; only non-finite values are an error upstream (checked_score), so nothing is clamped.

test_boost_query_negative_boost_factor pinned the multiplicative contract (s_half ≈ s_no * 0.5) and is rewritten against the subtractive one — including the case the old form could not express at all: negative_boost = 0.0 now means no demotion and leaves the positive score untouched.

Your reproducer is in as public_boost_query_keeps_subtractive_scoring_in_memtable, asserting the formula rather than just the ordering, so a future regression to a multiplicative or membership-only form fails rather than passing on relative rank.

Worth saying plainly: my previous revision took the "keep Boost rejected" option because I read the fix as a semantics change needing its own PR. That was the wrong call — the multiplicative form had no callers outside its own tests, so it was never a contract anyone depended on, just an inconsistency. Fixing it here is both smaller and more honest than shipping a compound-query PR that refuses one of the compound queries.

lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Sep 12, 2026
@hamersaw
hamersaw force-pushed the feat/memwal-fts-compound-queries branch from 69f7f2c to e570b3e Compare September 12, 2026 13:53
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Sep 12, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 12, 2026
The active memtable refused every compound full-text query. A boolean or
boost query against a MemWAL table whose memtable held an FTS index on
the searched column failed outright, and the LSM planner rejected it one
layer up as well — so the only way to get an answer was to exclude the
memtable and read stale.

Most of the capability was already there. The in-memory inverted index's
`FtsQueryExpr` has nested boolean (must/should/must_not over arbitrary
sub-queries) and boost with a negative clause. What was narrow was the
scanner's intermediate `FtsQueryType`: its `Boolean` variant flattened to
`Vec<String>` terms, it had no `Boost` variant at all, and
`local_fts_query` refused compound shapes before reaching any of it.

Drop that intermediate form. `MemTableScanner`'s `FtsQuery` now carries
an `FtsQueryExpr` directly, `local_fts_query` maps the index-level
`FtsQuery` onto it recursively, and the exec's hand-written conversion
goes away — it was translating between two enums that now agree. The
scanner's public builders keep their signatures, so callers are
unaffected.

Boost needed one real fix rather than plumbing. `search_boost` multiplied
a demoted document's positive score by `negative_boost` and discarded the
negative score, so 1.0 meant "no demotion"; `BoostScorer::score` computes
`positive - negative_boost * negative_score`, where 0.0 does. Same field
name, opposite direction — active rows would have ranked differently from
committed rows for the same query, and could have differed in sign. The
memtable now applies the subtractive form, which needs the negative
*score* rather than just membership. Scores may go negative; only
non-finite values are an error upstream (`checked_score`), so nothing is
clamped.

`test_boost_query_negative_boost_factor` pinned the multiplicative
contract (`s_half ≈ s_no * 0.5`) and is rewritten against the subtractive
one, including the case the old form could not express: `negative_boost =
0.0` leaves the positive score untouched.

Multi-match stays refused: it spans columns while the memtable holds one
inverted index per column, so there is no single index to search.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01QBv2WLSq5oy6kR2gVrfFDh
@hamersaw
hamersaw force-pushed the feat/memwal-fts-compound-queries branch from e570b3e to b4e4b60 Compare September 12, 2026 14:33
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 12, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 12, 2026
**Stacked on #9160** — targets `feat/memwal-fts-compound-queries`, not
`main`. See *Why it is stacked* below; it is not just convenience.

## The bug

The active memtable builds an inverted index only for columns in the
write spec's maintained set, and that set is fixed when the spec is
installed — an FTS index created afterwards can never join it. For any
other column `active_source_can_execute_fts` is false and the arm
becomes `empty_plan()`.

Not an error. Just nothing. So the query succeeds, the plan says it
consulted the memtable, and every matching row still in memory is
missing from the answer.

Two ordinary ways in: an index built after `set_lsm_write_spec`, or
`maintained_indexes=[]`.

## The fix

Index the visible prefix for the query. The cost is a tokenize pass over
rows that are already resident and bounded by the seal threshold — the
same pass any brute-force scoring would need.

Going through a *real* index rather than a bespoke scorer is the part
worth arguing for: every query shape then behaves here exactly as it
does on a maintained column — compound trees, phrase, fuzzy — instead of
whatever subset a hand-written scorer happens to cover. The alternative
shape (a `MemTableBruteForceFtsExec` mirroring
`MemTableBruteForceVectorExec`) would have had to reimplement
`FtsQueryExpr` evaluation to avoid regressing what #9160 just enabled.

The transient store carries the PK columns too. `enable_pk_index`
refuses to run once a search index holds rows, so it is configured
first, and the FTS exec needs it to drop superseded postings before
applying the query limit.

An empty memtable returns `None` and keeps the empty arm, so it pays
nothing.

## Why it is stacked

The transient index makes compound queries *reach*
`validate_lsm_fts_query` on this path for the first time — previously an
unmaintained column skipped validation entirely, because the memtable
arm was never built. On `main` that validator still rejects compound
shapes, so landing this first would turn a working base-only boolean
query into a hard error. #9160 relaxes it; this needs that.

Caught by an existing test, which is the evidence:
`boolean_query_ignores_active_memtable_without_relevant_fts_index` went
red against `main` and passes on the stack.

## Tests

- `unmaintained_column_is_indexed_for_the_query` — a memtable with a PK
index and no FTS index contributes its matching row alongside the base
table's. Asserts the precondition
(`fts_document_granularities_by_column` empty) so it can't pass for the
wrong reason.
- `empty_memtable_builds_no_transient_index` — nothing to index, nothing
built.
- The existing test above is renamed to
`..._searches_active_memtable_without_a_maintained_fts_index`: its
memtable row carries none of the query's terms, so the result is
unchanged — what changed is that the memtable was actually searched.

702 `mem_wal` tests pass.

## Downstream

This is what a rejection-shaped PR in sophon (closed,
lancedb/sophon#7827) was standing in for. With this, an unmaintained FTS
index costs a tokenize pass instead of silent data loss.

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

https://claude.ai/code/session_01QBv2WLSq5oy6kR2gVrfFDh

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 14, 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 expanded revision preserves the active-tier compound-query contract and incorporates the transient-index path from #9167 for unmaintained FTS columns. The transient store uses the published memtable prefix, applies newest-PK filtering before top-k, and inherits the persisted analyzer, positions, and selected document granularity. This is preferable to the minimal compound-only patch, which would leave matching fresh rows silently absent on an unmaintained column.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 14, 2026

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

looks good

@hamersaw
hamersaw merged commit f7e212e into main Sep 14, 2026
39 checks passed
@hamersaw
hamersaw deleted the feat/memwal-fts-compound-queries branch September 14, 2026 22:53
hamersaw added a commit that referenced this pull request Sep 16, 2026
Both parents have landed — #9160 squash-merged into `main`, carrying
#9167 with it — so this is no longer stacked. Rebased onto `main`; the
diff is now this PR's own commit alone.

## The gap

`plan_search` took one column and bound the whole query to it
(`FtsQuery::with_column` rebinds *every* leaf, including a multi-match's
per-column ones). So a cross-column multi-match was rejected: the
memtable holds one inverted index per column and there was nothing to
route it to.

## Decompose, don't thread

A top-level multi-match splits into one per-column match, each planned
by the existing single-column path, and the results are unioned.

That was the design call worth making. Threading a column dimension
through `plan_search` / `build_source_plan` / granularity resolution
would have touched every per-source behavior — prefilter, the
cross-generation block-list, the transient-index fallback from #9167 —
and risked each of them diverging between the one-column and many-column
cases. Decomposing reuses all of it verbatim. The cost is one pass over
the sources per column.

None of the base-table cross-column machinery was reusable here, for the
record: `cross_column_compound_search` (2,147 lines) operates on
`Vec<Arc<InvertedIndex>>` — on-disk indexes — and the memtable has
`FtsMemIndex` with a separate evaluator.

## Collapsing the duplicates

A row matching in two columns is scored twice and arrives twice. The
base-table path scores each field independently and takes the
**maximum** per row (`DisjunctionScore::Max`), and over an input already
sorted by `_score` descending, keeping the first occurrence per primary
key *is* that maximum.

`FirstByPkExec` does that — a filter, not a grouped aggregate, so the
streaming top-k shape the FTS planner is built around survives. Its
input ordering is load-bearing and the module doc says so.

## What stays refused

Only multi-match decomposes. A boolean or boost spanning columns is one
predicate over several fields — `must: [a in title, b in body]` is a
conjunction, not a union of per-column results — so unioning per-column
plans would answer a different query. Refused, with the reason in the
message.

## Tests

- `multi_match_searches_every_column_and_collapses_duplicates` — four
memtable rows: title-only, body-only, both, neither. Asserts all three
matching rows come back **and** that the row matching in both appears
exactly once.
- `cross_column_boolean_is_refused` — the non-decomposable shape.
- Supersedes `multi_match_query_is_refused_by_the_active_memtable` from
#9167; that restriction is what this lifts.

714 `mem_wal` tests pass on the rebased tree. (The count grew from 703
because `main` picked up `mem_wal` tests from other merged work — this
PR adds two.)

## Note for the sophon side

The max is taken over per-source **local** BM25 scores, so a
cross-column query on a WAL table can rank differently from a non-WAL
table for two reasons rather than one. That widens the existing
local-scoring trade rather than introducing a new class of divergence —
but it is worth knowing when the sophon multi-match arm lands.

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

https://claude.ai/code/session_01QBv2WLSq5oy6kR2gVrfFDh

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
hamersaw added a commit to hamersaw/lance that referenced this pull request Sep 23, 2026
Resolve conflicts with the fresh-tier FTS changes (lance-format#9160, lance-format#9172, lance-format#9292,
lance-format#9363): keep main's transient-index fallback in the active-memtable arm
alongside the fallible nested-projection canonical schema, combine the
import sets, and move the two new nested-projection tests to the
column-bound `plan_search` signature.

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

Labels

enhancement New feature or request K-approved Latest Gatekeeper recommendation permits acceptance.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants