Skip to content

fix: honor nested projections in the mem-wal LSM scanner - #8970

Merged
hamersaw merged 4 commits into
lance-format:mainfrom
hamersaw:feature/mem-wal-nested-projection
Sep 24, 2026
Merged

hamersaw merged 4 commits into
lance-format:mainfrom
hamersaw:feature/mem-wal-nested-projection

Conversation

@hamersaw

@hamersaw hamersaw commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Problem

A projection naming a struct leaf is widened back to the whole struct. SELECT meta.a on a mem-wal table returns meta: Struct<a, b> instead of meta: Struct<a>.

Every projection surface in the mem-wal scanner resolved names through flat, top-level lookups — field_with_name / column_with_name against the Arrow schema — so a dotted path either missed entirely or matched only its parent. validate_projection_names rejected meta.a outright; canonical_output_schema silently dropped it.

Fix

Schema. canonical_output_schema and validate_projection_names resolve through lance_core::datatypes::Schema, which already narrows a struct to the selected leaf and merges sibling leaves of one parent into a single field (meta.a + meta.c → meta: Struct<a, c>, via do_project's candidate_field.merge()). canonical_output_schema returns Result as a consequence.

Data. The eight dataset arms (base table + SSTable across the scan, point-lookup, vector and FTS planners) now project by schema rather than by expression. That distinction is load-bearing — ProjectionPlan::from_schema documents that a partial nested projection "cannot be done easily using expressions", and expressions are what Scanner::project builds. Scanner::project_with_schema is added for it.

The six memtable execs share a new take_projected_columns, which takes whole stored columns and trims them to the projected shape with RecordBatchExt::project_by_schema — already recursive through structs, lists and maps, and null-buffer preserving. Columns whose type already matches pass through untouched, so a projection with no nested paths costs nothing.

Both arms therefore emit the same narrowed schema before UnionExec, and SSTable reads fetch only the selected sub-columns rather than whole structs.

Two inconsistencies fixed along the way

  • MemTableScanner::output_schema silently dropped a column that compute_projection_indices rejected outright — the two disagreed on the same input. Both now resolve through one projected_data_fields and error alike.
  • validate_projection_names used Schema::project, which errors on a missing top-level column but returns an empty struct for a missing child — so meta.nope passed validation. It now uses Schema::resolve, which checks every path segment.

Tests

  • projection.rs: four new cases — leaf narrowing, sibling merging at the parent's position, whole-struct passthrough, and nested validation accepting meta.a while rejecting meta.nope.
  • builder.rs: projecting_a_struct_leaf_narrows_the_memtable_output — end-to-end through MemTableScanner, asserting the sibling does not survive.
  • Full mem_wal suite: 692 passed, 0 failed.

Lint status

cargo fmt --all clean. cargo clippy -p lance --lib --tests clean on every touched file. I have not run the full cargo clippy --all --tests --benches -- -D warnings that AGENTS.md asks for — the machine this was developed on is disk-bound and the full bench build was not viable. Flagging it explicitly rather than implying it passed; CI will cover it.

🤖 Generated with Claude Code

https://claude.ai/code/session_01YR3wEnDq7cD2a9v2DdTGsZ

A projection naming a struct leaf (`meta.a`) was widened back to the whole
struct. Every projection surface in the mem-wal scanner resolved names
through flat, top-level lookups — `field_with_name` / `column_with_name`
against the Arrow schema — so a dotted path either missed entirely or
matched only its parent.

The two halves of the fix:

* Schema. `canonical_output_schema` and `validate_projection_names` now
  resolve through `lance_core::datatypes::Schema`, which narrows a struct
  to the selected leaf and merges sibling leaves of one parent into a
  single field (`meta.a` + `meta.c` -> `meta: Struct<a, c>`).
  `canonical_output_schema` returns `Result` as a consequence.

* Data. The eight dataset arms (base table + SSTable across the scan,
  point-lookup, vector and FTS planners) project by schema rather than by
  expression. That distinction is load-bearing: `ProjectionPlan` documents
  that a partial nested projection cannot be expressed through expressions,
  which is what `Scanner::project` builds. `Scanner::project_with_schema`
  is added for it. The six memtable execs share `take_projected_columns`,
  which trims whole stored columns to the projected shape via
  `RecordBatchExt::project_by_schema` (recursing structs, lists and maps,
  preserving null buffers).

Both arms therefore emit the same narrowed schema before `UnionExec`, and
SSTable reads fetch only the selected sub-columns.

Also fixes two inconsistencies found along the way:

* `MemTableScanner::output_schema` silently dropped a column that
  `compute_projection_indices` rejected outright. Both now resolve through
  one `projected_data_fields` and error alike.

* `validate_projection_names` used `Schema::project`, which errors on a
  missing top-level column but yields an empty struct for a missing
  *child*, letting `meta.nope` through. It now uses `Schema::resolve`,
  which checks every path segment.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YR3wEnDq7cD2a9v2DdTGsZ
@github-actions github-actions Bot added the bug Something isn't working label Sep 3, 2026
`LsmPointLookupPlanner::new` became fallible when `canonical_output_schema`
started returning `Result`. The JNI and Python call sites live in crates
excluded from the workspace, so `cargo check --workspace` did not see them
and CI failed to compile `lance-jni` and `pylance`.

Also narrows `Scanner::project_with_schema` to `pub(crate)`. The mem-wal
scanner is its only caller; it can be widened if another consumer appears.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FbN1Lguzmae4AwxtEDkLJC
@github-actions github-actions Bot added A-python Python bindings A-java Java bindings + JNI labels Sep 9, 2026
@hamersaw
hamersaw marked this pull request as ready for review September 9, 2026 15:40
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 9, 2026
Two projection surfaces still resolved names flatly, so a nested path
(`meta.a`) either errored or was silently dropped.

* Point lookup. `canonical_output_schema` narrows the target to `meta:
  Struct<a>`, but `gather_rows` takes the stored column whole, so
  `RecordBatch::try_new` rejected the batch on a type mismatch — a
  regression, since the pre-fix target was the whole struct. Gathered
  columns are now narrowed with one `project_by_schema` pass, skipped
  entirely when every projected column matches its stored type. Reached
  from both the `lookup` fast path and `lookup_many`'s batched gather.

* FTS. `canonical_fts_schema` is the one planner that kept its own
  target builder, and its `field_with_name` lookup missed `meta.a`
  inside a `filter_map`, so the column was dropped from the target and
  then from every source by `project_to_canonical`. It now resolves
  through `resolve_data_fields` — the same nested-path resolver every
  other arm uses — and appends `_score` / `_doc_index` around it,
  returning `Result` as a consequence. `resolve_data_fields` and
  `top_level_of` widen to `pub(super)` for it.

Both were caught by review on lance-format#8970. Regression tests cover the leaf
narrowing on `lookup`, `lookup_many`, the FTS source arm end-to-end and
its empty-plan arm, plus a whole-struct control that pins the
no-narrowing path. All four fail without the fix.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HWcgzgQikLcUNeZMqWKnB4
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Sep 9, 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 9, 2026

@xuanyu-z xuanyu-z 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.

makes sense, many of the changes are plumbing and adding take_projected_columns

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 <noreply@anthropic.com>
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 23, 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 upstream merge preserves nested leaf projection across point lookup and FTS. Both maintained-index and transient-index fresh-tier FTS paths retain the requested narrowed struct under the updated query binding.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 23, 2026
@hamersaw
hamersaw merged commit 1751139 into lance-format:main Sep 24, 2026
39 checks passed
@hamersaw
hamersaw deleted the feature/mem-wal-nested-projection branch September 24, 2026 00:31
westonpace pushed a commit that referenced this pull request Oct 7, 2026
Make `Scanner::project_with_schema` public, and fix the projection path
underneath so that exposing it is safe.

## Public API

| item | change |
|---|---|
| `Scanner::project_with_schema` | `pub(crate)` to `pub`. No signature
change. |
| `ProjectionPlan::from_schema` | Behaviour. A field the dataset lacks,
or a type mismatch, is now an error instead of a silently narrower or
wrong projection. |

## Why `project_with_schema` should be public

It projects by a possibly partial schema: a nested field narrowed to a
subset of its children. Expression-based projection cannot express that,
since `project` flattens `metadata.location.x` into a top-level column
of that name. Only the mem-wal scanner can reach it today, so an
external caller must rebuild the nested shape by hand.

## Companion fix: validate the schema where it is accepted

`from_schema` is where a caller's schema becomes a set of field ids, but
it checks only top-level names. Everything below that is taken on trust,
and field ids are dataset-scoped identities, so trusting them only works
when the schema came from the same dataset. Two shapes get through:

- a nested child the base lacks resolves to nothing, so a caller asking
for two children receives one;
- a schema numbered independently carries ids that can land on unrelated
base fields, so the projection reads the wrong column.

Both trip a `debug_assert` in debug builds and pass silently in release.

The fix resolves the requested fields through
`Schema::project_by_schema` with `OnMissing::Error` and
`OnTypeMismatch::Error`, matching by name, rewriting ids to the base's
own, and rejecting what the dataset does not have. The take path already
validates this way before calling here, and no in-crate caller depends
on the lax behaviour.

Name resolution rather than an id check is deliberate: a caller holding
an Arrow-derived schema should not have to know how Lance numbers fields
internally. It also catches type mismatches, which an id check cannot.

## Tests

Each fails without the change it covers.

- `projection.rs`: a nested child absent from the base is reported
rather than dropped.
- `projection.rs`: an independently numbered schema resolves by name
rather than by colliding id.
- `scanner.rs`: a partial nested projection keeps its shape, carries the
legacy row-id and row-address flags, preserves `BlobHandling`, and
matches `take_rows`.
- Doc-test: the scanner test is in-crate and so blind to visibility, so
a doc-test covers it, failing to build at `pub(crate)`.

## Related validation gaps found while writing this

None is a live bug, and none is addressed here.

- **`Projection::union_schema`** documents that fields are added "only
if they exist in the base schema" and that it "will panic" on a
non-negative id the base lacks. It does neither: such ids are inserted
unchecked, and the `debug_assert` meant to catch them sits in the `id <
0` branch it cannot reach. All four callers pass base-derived ids, so
nothing breaks today; the contract and the dead assertion mislead.
- **`ProjectionRequest::into_projection_plan`** pre-validates only when
the schema has no system columns, since `project_by_schema` cannot
handle `_rowid`. This PR closes that branch, `from_schema` now
validating after system columns are separated out, which also makes the
outer special-casing redundant.
- **`Projection::union_arrow_schema`** passes
`OnTypeMismatch::TakeSelf`, silently coercing a field whose type
disagrees with the dataset, where the path hardened here errors.

## PR History

- #5134 proposed adding such a method. Closed as stale.
- #9287 re-raised it and was approved but conflicted with..
- #8970 which also added the same API, as `project_with_schema` for the
mem-wal scanner, but with `pub(crate)` visibility.

This PR opens visibility and adds validation.

---

**Tracking:** The visibility change is ported in part from
rerun-io#72; the projection fix was found while preparing it.

---------

Co-authored-by: Clement Rey <cr.rey.clement@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-java Java bindings + JNI A-python Python bindings 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