Skip to content

refactor: read JSON through one accessor in the JSON semantic module - #9479

Merged
Xuanwo merged 9 commits into
mainfrom
xuanwo/semantic-type-json-accessor
Sep 23, 2026
Merged

Xuanwo merged 9 commits into
mainfrom
xuanwo/semantic-type-json-accessor

Conversation

@Xuanwo

@Xuanwo Xuanwo commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

Part of #7073. Builds on #9478.

Problem

Code that computes on JSON decided whether a column holds JSON by matching lance.json over LargeBinary itself. The same JSON column was therefore tokenized as JSON when it came from storage but as plain text when it arrived as Arrow JSON text (arrow.json over Utf8), and the JSON scalar index could not read Arrow JSON text at all. JSONPath selection was also written twice: JsonArray::json_path kept only the first match, while json_extract returns every match as one JSON array.

Behavior

  • lance_arrow::json is the one place that encodes and decodes JSONB and selects JSONPath values. JsonEncoding::of_field recognizes a JSON field in either representation, and JsonValues reads its values as JSONB or as text, whichever the consumer needs, regardless of the representation they arrived in.
  • FTS index builds and unindexed FTS input read JSON documents through JsonValues, so both representations are tokenized as JSON. The JSON scalar index accepts Arrow JSON text and indexes the same values it would from JSONB.
  • The SQL JSON functions use the shared JSONPath selection. JsonArray::json_path now returns every match of a multi-match path as one JSON array, the same as json_extract.
  • Breaking API changes: lance_index::scalar::inverted::json::JsonTextStream::new is replaced by the fallible try_new, which rejects a column that does not hold JSON, and jsonb_to_json is removed in favor of JsonValues::to_text.
  • No format change, and blob behavior is unchanged. JsonValues is an internal Rust API, not a plugin extension point.

Tradeoffs

  • dataset/sql.rs, lance-datafusion/src/projection.rs and io/exec/projection.rs do not inspect JSON metadata themselves: SQL only converts its output to Arrow JSON through SchemaAdapter, and the projections carry field metadata through unchanged. They are left as they are; choosing the user-facing output encoding belongs to the read path.
  • An FTS index records its tokenizer when it is created, so existing indices keep theirs. The document-type change only affects new indices built from Arrow JSON text.

…ndary

Data file writers now reject any array whose Arrow type or extension
differs from the file schema before encoding, returning a structured
FieldTypeMismatch. Dataset writes convert Arrow JSON to Lance JSONB in the
one current-format data file writer instead of at each call site.
JSON encoding detection, JSONB/text conversion and JSONPath selection now
live in lance_arrow::json. FTS and the JSON scalar index read values
through JsonValues, so they treat stored JSONB and Arrow JSON text alike.
@github-actions github-actions Bot added the A-index Vector index, linalg, tokenizer label Sep 22, 2026
Build the expected Arrow fields once per writer, match batch columns by
position before falling back to a name search, and skip batches whose
schema equals the last accepted one.
@Xuanwo
Xuanwo marked this pull request as ready for review September 23, 2026 03:44
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 23, 2026
FieldTypeMismatch now carries the expected and actual Arrow fields instead
of a separate type-and-extension struct, and the check walks nested
fields without tracking a path stack.
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 23, 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 23, 2026
do_write_fragments_impl hands each batch to both the data file writer and
the index seed observers. Convert it once before both, so appending view
or Arrow JSON input to a seeded column no longer fails in the seed writer.
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 23, 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 23, 2026
Base automatically changed from xuanwo/semantic-type-write-boundary to main September 23, 2026 04:58
@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. and removed K-approved Latest Gatekeeper recommendation permits acceptance. labels 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 shared JSON accessor is preferable to per-consumer metadata branching: FTS, JSON scalar indexing, and JSONPath evaluation apply the same representation semantics to stored JSONB and Arrow JSON text, while existing index tokenizer metadata remains intentionally preserved. The affected accessor, UDF, and index paths have focused regression coverage, including multi-match JSONPath selection.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 23, 2026
@Xuanwo
Xuanwo merged commit d45b546 into main Sep 23, 2026
40 of 41 checks passed
@Xuanwo
Xuanwo deleted the xuanwo/semantic-type-json-accessor branch September 23, 2026 05:28
sbrunk added a commit to sbrunk/lance that referenced this pull request Sep 25, 2026
The flat `combined_fields` path wraps its input in one `JsonTextStream` per
JSON target column, so it depends on that stream declaring the schema its
batches actually have. Upstream lance-format#9479 made `JsonTextStream` derive one schema
from its input and use it for both `schema()` and the batches, which fixes the
mismatch this branch originally patched. What remains are regression tests for
the caller that the mismatch broke.

Two `combined_fields` scans over `arrow.json` columns with mixed index
coverage, so the plan carries a flat child: one over two JSON columns, which
needs name resolution to survive wrapping the stream twice, and one mixing a
JSON column with a plain text column, where the JSON column is not at
position 0 so a positional read would tokenize the wrong data. Both fail if
`JsonTextStream::schema()` lists only the JSON column.
sbrunk added a commit to sbrunk/lance that referenced this pull request Sep 25, 2026
The flat `combined_fields` path wraps its input in one `JsonTextStream` per
JSON target column, so it depends on that stream declaring the schema its
batches actually have. Upstream lance-format#9479 made `JsonTextStream` derive one schema
from its input and use it for both `schema()` and the batches, which fixes the
mismatch this branch originally patched. What remains are regression tests for
the caller that the mismatch broke.

Two `combined_fields` scans over `arrow.json` columns with mixed index
coverage, so the plan carries a flat child: one over two JSON columns, which
needs name resolution to survive wrapping the stream twice, and one mixing a
JSON column with a plain text column, where the JSON column is not at
position 0 so a positional read would tokenize the wrong data. Both fail if
`JsonTextStream::schema()` lists only the JSON column.
sbrunk added a commit to sbrunk/lance that referenced this pull request Sep 25, 2026
The flat `combined_fields` path wraps its input in one `JsonTextStream` per
JSON target column, so it depends on that stream declaring the schema its
batches actually have. Upstream lance-format#9479 made `JsonTextStream` derive one schema
from its input and use it for both `schema()` and the batches, which fixes the
mismatch this branch originally patched. What remains are regression tests for
the caller that the mismatch broke.

Two `combined_fields` scans over `arrow.json` columns with mixed index
coverage, so the plan carries a flat child: one over two JSON columns, which
needs name resolution to survive wrapping the stream twice, and one mixing a
JSON column with a plain text column, where the JSON column is not at
position 0 so a positional read would tokenize the wrong data. Both fail if
`JsonTextStream::schema()` lists only the JSON column.
sbrunk added a commit to sbrunk/lance that referenced this pull request Sep 26, 2026
The flat `combined_fields` path wraps its input in one `JsonTextStream` per
JSON target column, so it depends on that stream declaring the schema its
batches actually have. Upstream lance-format#9479 made `JsonTextStream` derive one schema
from its input and use it for both `schema()` and the batches, which fixes the
mismatch this branch originally patched. What remains are regression tests for
the caller that the mismatch broke.

Two `combined_fields` scans over `arrow.json` columns with mixed index
coverage, so the plan carries a flat child: one over two JSON columns, which
needs name resolution to survive wrapping the stream twice, and one mixing a
JSON column with a plain text column, where the JSON column is not at
position 0 so a positional read would tokenize the wrong data. Both fail if
`JsonTextStream::schema()` lists only the JSON column.
BubbleCal pushed a commit that referenced this pull request Sep 29, 2026
## TL;DR

Follow up to #7905, which added `combined_fields` (BM25F) but returned
an error whenever a query reached a fragment that one of the target
columns had not indexed. This PR replaces that error with a flat scan
over those fragments, so `combined_fields` also works on rows added
since the indexes were built.

## What changes

| Commit | Files | + | − | Subject |
|---|---:|---:|---:|---|
| `a1e707f02` | 15 | 1,717 | 116 | feat(fts): score unindexed and
partially indexed fragments in combined_fields |
| `a2d980886` | 4 | 2,334 | 5 | test(fts): cover the combined_fields
flat scan and overlay corpus statistics |
| **Total** | **17** | **4,051** | **121** | about 2,300 lines of it
tests |

The query API is untouched: `query.rs`, `parser.rs`, `tokenizer.rs` and
`traits.rs` are unchanged. `CombinedFieldColumn` gains one field,
`stale_rows`, which is public but internal to scoring. Most of the 121
deleted lines are in code from #7905, mainly the error path that the
union plan replaces. One #7905 test changes meaning: in
`test_element_document_nested_lists_use_deepest_boundary`, a normal scan
over the appended fragment now returns all four rows instead of the
coverage error. Its `fast_search` and post-optimize checks are
unchanged.

Before, on a dataset with one appended fragment:

```
Invalid user input: combined_fields requires every target column to be indexed
over every scanned fragment, but 1 of 2 fragments are not fully covered.
Optimize the indexes on body, title and retry.
```

After, the same query returns those rows, ranked correctly against the
indexed ones.

## How it works

```
plan_combined_fields_query
        │
        └─ some fragment not covered → union of two children
             │
             ├── CombinedFieldsQueryExec  (restricted to the covered fragments)
             │
             └── FlatCombinedFieldsExec   (the remaining fragments)
                   • reads the column values and blends dl' and tf' per row
                   • publishes the corpus statistics that both children use
             │
             ▼
        UnionExec → SortExec(score DESC, row_id ASC) → fetch(k)
```

Both children score against the same corpus. Only the flat side can see
the rows that no index covers, so it measures what they contribute and
publishes the combined statistics. The indexed side waits for those
rather than using only its own `docCount'`, `docFreq'` and `avgdl'`.
Getting this wrong would be hard to spot: the right rows still come
back, but with scores that depend on which child happened to produce
them.

A fragment counts as not covered if any target column's index is missing
it, or if a newer data overlay made its entries stale. Coverage stays a
per fragment decision, because a row has to be scored either entirely
from the index or entirely from the scan.

A stale row needs one more step. The index holds its pre-overlay value
until the index is optimized, and the flat scan folds in its current
one, so counting both inflates `docCount` and `docFreq`. That is enough
to reorder results after an overlay that changed no searchable value at
all. `InvertedIndex::bm25_row_stats_for_terms` therefore takes the stale
rows and subtracts what they still contribute, reading posting
membership to do it. Only a column that actually has stale rows pays for
that.

## Correctness

- Adds 15 test functions and 23 cases to
`dataset_fts_combined_fields.rs`, taking it from 13 functions and 16
cases to 28 and 39, plus overlay coverage in
`dataset_overlay_index_masking.rs`. 62 tests match the `combined` filter
in `lance --lib`, and `scalar::inverted` is at 882 of 882.
- Every dataset test checks exact scores against the brute force
`oracle` reference, which recomputes every statistic from the raw text
and shares no code with the scan. A wrong shared corpus still returns
almost the right rows in almost the right order, so a test that only
checked which rows came back would pass anyway.
- Covered: mixed indexed and flat plans, per column index skew over both
row id schemes, partially indexed columns, an unindexed row winning top
k, fragments made stale by an overlay, deletions followed by optimize,
external row masks, filters, nulls and empty strings on the flat path,
list and large list and nested columns, a column under a list, and the
plan shape itself, so a query that should union cannot answer from the
index alone.
- `test_fts_combined_fields_overlay_preserves_every_score` pins the
stale row subtraction by comparing score bit patterns across a
same-value overlay. Ids alone would not catch it, because the same rows
come back either way.
- `test_fts_combined_fields_tied_scores_are_deterministic` covers tie
ordering for both plan shapes. A fully covered dataset returns the exec
with no `SortExec` above it, while a mixed plan gets its order from the
sort's second key, so the two shapes need separate checks.

## Stack

The branches that build on this one. They live on a fork, and GitHub
cannot stack PRs across forks, so each dependent PR also shows this PR's
commits. The compare links give the real diff for each.

```
main (includes #7905)
└── combined-fields-bm25f-part2           #9444  ← this PR (flat scan)
     ├── fts-builder-doc-order
     │    └── combined-fields-maxscore
     │         └── combined-fields-block-skip
     │              └── combined-fields-bench
     ├── fts-json-stream-schema
     ├── combined-fields-python           #8550
     └── combined-fields-java             #8549
```

| Branch (diff) | Base | PR | Cmts | Files | + | − | Description |
|---|---|---|---:|---:|---:|---:|---|
| `combined-fields-bm25f-part2` | main | #9444 | 2 | 17 | 4,051 | 121 |
flat scan for fragments the indexes do not cover |
|
[fts-builder-doc-order](sbrunk/lance@combined-fields-bm25f-part2...fts-builder-doc-order)
| part 2 | none yet | 1 | 1 | 493 | 0 | order inverted index docs by
row_id at build time |
|
[combined-fields-maxscore](sbrunk/lance@fts-builder-doc-order...combined-fields-maxscore)
| builder-doc-order | none yet | 1 | 8 | 903 | 82 | prune candidate
scoring with MAXSCORE |
|
[combined-fields-block-skip](sbrunk/lance@combined-fields-maxscore...combined-fields-block-skip)
| maxscore | none yet | 1 | 10 | 1,091 | 106 | skip posting blocks a row
id seek jumps past |
|
[combined-fields-bench](sbrunk/lance@combined-fields-block-skip...combined-fields-bench)
| block-skip | none yet | 1 | 4 | 1,191 | 1 | Lance vs Lucene BM25F
validation harness |
|
[fts-json-stream-schema](sbrunk/lance@combined-fields-bm25f-part2...fts-json-stream-schema)
| part 2 | none yet | 1 | 1 | 184 | 1 | tests for flat scans over JSON
columns (the `JsonTextStream` schema fix itself landed upstream in
#9479) |
|
[combined-fields-python](sbrunk/lance@combined-fields-bm25f-part2...combined-fields-python)
| part 2 | #8550 | 2 | 5 | 227 | 1 | Python binding for
`combined_fields` |
|
[combined-fields-java](sbrunk/lance@combined-fields-bm25f-part2...combined-fields-java)
| part 2 | #8549 | 1 | 4 | 321 | 24 | Java binding for `combined_fields`
|
sbrunk added a commit to sbrunk/lance that referenced this pull request Sep 29, 2026
The flat `combined_fields` path wraps its input in one `JsonTextStream` per
JSON target column, so it depends on that stream declaring the schema its
batches actually have. Upstream lance-format#9479 made `JsonTextStream` derive one schema
from its input and use it for both `schema()` and the batches, which fixes the
mismatch this branch originally patched. What remains are regression tests for
the caller that the mismatch broke.

Two `combined_fields` scans over `arrow.json` columns with mixed index
coverage, so the plan carries a flat child: one over two JSON columns, which
needs name resolution to survive wrapping the stream twice, and one mixing a
JSON column with a plain text column, where the JSON column is not at
position 0 so a positional read would tokenize the wrong data. Both fail if
`JsonTextStream::schema()` lists only the JSON column.
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 breaking-change K-approved Latest Gatekeeper recommendation permits acceptance.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants