Skip to content

feat(index): implement version 1 zone write seeds - #10102

Merged
LuQQiu merged 5 commits into
mainfrom
lu/zone-seeds-v1
Oct 21, 2026
Merged

LuQQiu merged 5 commits into
mainfrom
lu/zone-seeds-v1

Conversation

@LuQQiu

@LuQQiu LuQQiu commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Zone write seeds are per-column statistics embedded in data files, collected while those files are written. A later index update can reuse them instead of reading the column again.

This PR implements the V1 seed format defined in #9564 and #10155, fixes NaN-aware ZoneMap pruning, and preserves compatible seeds during binary-copy compaction.

Breaking compatibility: this PR automatically activates new reader and writer feature flags on tables with seed-enabled indices. Clients that do not support FLAG_ZONE_WRITE_SEEDS can no longer read or write the resulting snapshots. This can happen with default ZoneMap options, not just an explicit use_seeds: true.

1. What was wrong with NaN handling?

Arrow Rust's floating-point total order distinguishes the two NaN signs:

negative NaNs < -Infinity < ordinary finite values < +Infinity < positive NaNs

Previously, statistics counted both signs together and wrote max = +NaN whenever any NaN was present. This hid the ordinary maximum and did not say whether negative NaNs existed. Query evaluation also mishandled some NaN-only zones and predicates with NaN bounds.

Examples of incorrect pruning addressed here:

Zone contents Query What went wrong
Only negative NaNs x < 0 Could discard the zone even though negative NaNs match under Arrow Rust ordering.
Only positive NaNs x > 100 Could treat the lack of ordinary bounds as an empty zone, dropping matching positive NaNs.
Ordinary values and NaNs Range with a NaN literal as a bound Could short-circuit on nan_count and drop ordinary values that satisfy the range.

The PR changes both the statistics written into new seeds and the evaluation of existing index files. These are separate changes: the ZoneMap index file schema remains unchanged.

2. V1 seeds keep NaNs out of both min and max

Field Meaning in a V1 seed
min, max Bounds on non-null, non-NaN values, following Arrow Rust ordering. Infinities are included. Types without supported value bounds retain typed-null bounds.
null_count Exact number of null physical rows. For nested types this counts parent nulls, not null elements inside a non-null value.
nan_count Total number of NaNs, of either sign.
negative_nan_count Number of NaNs with the sign bit set. Positive NaNs = nan_count - negative_nan_count.
zone_length Number of physical rows summarized by the record, serialized as UInt64.

Positive NaNs no longer replace the ordinary max in V1 seeds, and negative NaNs no longer produce a positive-NaN marker either:

Values Previous seed bounds V1 seed bounds V1 NaN counts
1, 5, +NaN min = 1, max = +NaN min = 1, max = 5 total = 1, negative = 0
1, 5, -NaN min = 1, max = +NaN min = 1, max = 5 total = 1, negative = 1
1, 5, -NaN, +NaN, null min = 1, max = +NaN min = 1, max = 5 total = 2, negative = 1; nulls = 1

The shared statistics accumulator collects the negative count in its existing NaN pass. The seed writer saves the new column and adds version = "1" to the seed buffer's IPC schema metadata.

  • No version metadata means V0. Its NaN sign split is unknown, not zero. The decoder checks the version before interpreting bitmap metadata or statistics.
  • The optional seed_null_bitmap retains its encoding; run optimization reduces its size for contiguous nulls.
  • The data-file locator remains lance.seed.<column_name> = <buffer_index>:<rows_per_zone>.
  • The default zone size remains 8192 rows; configured zone sizes are unchanged.
  • Readers derive zone starts by summing zone_length, allowing short zones within concatenated seeds.
  • Harvesting verifies complete physical-row coverage before using the seed instead of a column scan.

Unsupported seed versions: behavior depends on the consumer

This writer emits V1. It does not negotiate an arbitrary requested output version, and it does not read old files' seeds before appending new data. A file with an unsupported seed therefore does not, by itself, prevent a later V1 append.

Consumer Unsupported seed version, such as V2
Seed decoder Returns NotSupported before interpreting bitmap metadata or statistics. It never assumes V0/V1 from matching column names.
ZoneMap index update Propagates the error and fails that index update without publishing new index coverage. It does not automatically fall back to scanning for an unsupported version. Existing scan fallback for missing seeds or declined configuration remains unchanged.
Binary-copy compaction Continues copying data but omits the affected output column's seed, including both its buffer and locator. Other columns can still carry compatible seeds.

Adding a graceful scan fallback for unsupported versions in the ZoneMap index consumer is outside this PR's scope. The current error is a maintenance limitation, not permission to interpret unknown statistics or mark an uncovered fragment as covered.

3. Query pruning handles ordinary values and both NaN signs

The evaluator checks whether ordinary values, negative NaNs, or positive NaNs could satisfy the whole predicate. It excludes a zone only if none can match. Unknown signs or NaN payloads are handled conservatively.

This fixes the examples above, including bounded ranges where different NaN signs might separately satisfy opposite bounds but neither satisfies the whole range. column_value_range returns unknown for NaN-bearing zones instead of advertising an unsafe global range.

The PR also fixes evaluation of remapped legacy zones: inherited null/NaN counts can outlive some rows, so they must not override available bounds and incorrectly prove that no ordinary values remain.

The ZoneMap index file format is unchanged

V1 applies to data-file write seeds, not to a new ZoneMap index file version. When serializing a ZoneMap index, the writer still emits the legacy max = +NaN marker for any NaN-bearing zone. Its persisted schema has no negative_nan_count; reopening it yields an unknown sign split.

The reader fixes make existing index files safe to evaluate, but persisted ZoneMap indices do not yet retain V1's more precise ordinary maximum and sign split. That limitation remains even when an index update harvests V1 seeds.

4. Compatibility activation and changes to the commit path

V1 requires FLAG_ZONE_WRITE_SEEDS (1 << 16) in both reader_feature_flags and writer_feature_flags. This PR changes the previously reserved capability to supported.

The fence matters because an old consumer could interpret V1's ordinary max = 5 as proof that x > 100 cannot match, ignoring a positive NaN in that zone. Supporting readers must understand the separate NaN counts before consuming V1 statistics.

This is the transition from unversioned seeds to version-aware consumers. Future optional seed-format revisions are intended to use per-buffer version checks rather than additional table feature flags. An unsupported seed is never interpreted; each consumer rejects it or treats it as unavailable as described above. This does not promise that an older client can maintain every future index format or transparently harvest every future seed version.

When does a table become incompatible with older clients?

Situation Behavior
Create a seed-enabled index with this build The index-creation commit sets both flags. Subsequent writes can emit V1 seeds. Unsupported older clients cannot access the flagged snapshot, even before a V1 seed is written.
Legacy table with a seed-enabled index but no flags A subsequent non-Restore commit retaining that index activates both flags. This is not restricted to appends. A write prepared before activation omits seeds; later writes from a flagged snapshot emit V1.
Existing V0 data files Remain unchanged and readable by the new implementation. Activation does not scan, rewrite, or backfill them.
Later index drop, overwrite, or restore after activation Capability bits remain sticky; these operations do not make the table compatible with older clients again.

There is no new explicit upgrade API or opt-in setting. Existing per-index use_seeds settings still select collection. Their defaults are unchanged, but some types—including strings, binary, and decimals—already default to enabled. Creating a ZoneMap index on a string column with default options therefore activates the new capability. Collection is not enabled for every column or for tables without a requesting index.

What changes outside seed encoding?

  • IndexSeedWriter::required_feature_flags() lets each writer declare its requirements; the default is zero, and the ZoneMap writer requests bit 16.
  • The shared SeedCollector allows a flagged writer only when the writer's snapshot already has its required reader and writer bits.
  • Ordinary and detached commit paths in io/commit.rs call apply_seed_feature_flags on the candidate manifest and prepared index list. It selects seed writers and adds their requirements. It does not inspect data-file footers. Commits with indices still run this selection after activation; legacy indices without inline details can require session-cached index-metadata lookups.

There is no change to dataset/write/commit.rs or lance-table/src/transaction/builder.rs, no seed-specific transaction field, no transaction proto change, and no process-local file ledger. Generic detached/batch commit validation was removed as outside this PR's scope. Arbitrary external file imports are not automatically inspected; low-level callers remain responsible for meeting the destination table's capability requirements. This PR also does not add protection for publishing files through a detached base older than, or unrelated to, their writing snapshot.

5. Binary-copy compaction carries compatible V1 seeds

Previously, extra global buffers—including seed buffers—made a file ineligible for binary-copy compaction. This PR recognizes and validates seed buffers so compatible files can use that path.

For each output column, it validates input seeds and physical coverage, resolves column identity through the file's physical-column mapping, concatenates compatible V1 records in copy order, shifts null bitmap offsets, and writes a new buffer and locator. Renamed or remapped fields are matched through that mapping rather than assuming their stored field IDs still apply.

No column rescan, statistics recomputation, or zone rechunking is performed. Every contributing input must have complete, compatible V1 statistics for a column's seed to be carried. Missing, V0, mixed-version, or unsupported-version seeds leave that output column without a seed while data still binary-copies. Same-version V1 records are concatenated and remain V1; unknown versions are never relabeled. No actual V2 implementation is added.

Unrelated unknown global buffers, corrupt supported seeds, invalid locators, and unverifiable physical-column mappings still disqualify binary copy. These are distinct from a recognized optional seed declaring an unsupported version. Debug messages distinguish an omitted column seed from a genuinely disabled binary-copy path.

This adds seed-buffer reads during eligibility checking and execution, plus an index-configuration lookup for output zone-size metadata. It is not a zero-I/O change. V0 seeded files may now binary-copy without retaining their optional seeds, rather than fall back to re-encoding; later normal index maintenance can still scan when seeds are unavailable.

API and scope

  • Adds the seed-writer capability method, signed NaN statistics, and seed parsing/merging helpers for binary copy.
  • Adds public struct fields to Statistics and FragmentSeed; downstream struct-literal constructors need updating.
  • Does not change the transaction wire format, implement fragment column statistics, or add index-update-on-write maintenance.
  • Does not change the ZoneMap index file schema or extend its existing scan fallback policy to unsupported seed versions.
  • Does not change generic detached/batch commit acceptance rules.
  • The scanner.rs diff adds regression tests, not new scanner runtime behavior.

Tests and validation

Coverage includes V0/V1 decoding, unknown versions, invalid counts, physical coverage, both NaN signs and payloads, NaN range bounds, indexed-versus-unindexed results, legacy remapped zones, activation and sticky flags, retries, serialized/batched/detached commits, and binary-copy preservation with renamed/remapped fields.

The future-version tests additionally verify:

  • A V2 seed with a different bitmap encoding is rejected by version before the bitmap is decoded.
  • Forced binary copy succeeds with mixed/unsupported or missing seeds, omits only the affected column's seed, and preserves another column's V1 seed.
  • Carried V1 null bitmap offsets agree with the output data.
  • A ZoneMap update encountering V2 returns NotSupported and leaves the committed dataset version and index coverage unchanged; uncovered data remains queryable.
  • Appending beside an unchanged V2-seeded file produces V1 seeds without extra file requests in the tested setup.

Latest implementation verification on head 9b6bee8c8:

  • Formatting and clippy with -D warnings passed for the affected crates.
  • 18 CommitBuilder tests passed.
  • 127 related seed, version, commit-I/O, binary-copy, and collector tests passed.

The request-count test covers append, update, and merge-insert with inline index details. It does not establish zero additional metadata I/O for cold legacy indices without inline details, nor is it a commit-latency benchmark. Broader suite and platform results are reported by the PR's CI checks; the local validation above is targeted, not a full-suite run.

@github-actions github-actions Bot added A-index Vector index, linalg, tokenizer enhancement New feature or request labels Oct 17, 2026
@LuQQiu
LuQQiu force-pushed the lu/zone-seeds-v1 branch 2 times, most recently from 5cbe5a7 to 3a0f266 Compare October 17, 2026 02:11
@LuQQiu
LuQQiu force-pushed the lu/zone-seeds-v1 branch 2 times, most recently from 2781648 to 2e99e67 Compare October 17, 2026 18:08
@LuQQiu
LuQQiu marked this pull request as ready for review October 17, 2026 18:21

@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 repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.

Tip: disable this comment in your organization's Code Review settings.

lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added K-changes Latest Gatekeeper recommendation requests changes. and removed K-changes Latest Gatekeeper recommendation requests changes. labels Oct 17, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Oct 18, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Oct 18, 2026

@westonpace westonpace left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This may be a late comment / moot point but why is this such a complicated change?

All we are doing is writing the negative nan count going forwards correct?

If so:

  • Why do we need an index version bump at all? Couldn't readers just look for the presence of the column and use it if they find it?
  • Why do we need feature flags? Can't we bump an index version without creating a new feature flag? (admittedly, I already approved that PR, but the question stands)
  • Why does the transaction builder need to know about any of this?

Comment thread rust/arrow-stats/src/lib.rs Outdated
Comment on lines +83 to +84
/// Count of NaN values with the sign bit set. `Some` exactly when
/// `nan_count` is; always `<= nan_count`.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Some exactly when nan_count is" is slightly awkward phrasing. Would it be clearer to just say None means the writer did not capture this value, not that it is 0.

Comment on lines +25 to +35
/// Whether this transaction's data writes embedded version 1 zone write
/// seeds in the files they published. `Some` is a write-path fact recorded
/// by the writer that held the seed collector, so the commit can set the
/// paired `FLAG_ZONE_WRITE_SEEDS` bits without re-deriving the answer from
/// index configuration, which a concurrent `DROP INDEX` can change between
/// the write and the commit. `None` means the fact is unknown — the
/// transaction was rebuilt from its serialized form or assembled outside
/// the write path — and the commit must inspect the published files
/// themselves. Deliberately not serialized: the files are the durable
/// record, and a serialized claim could drift from them.
pub wrote_v1_seeds: Option<bool>,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: This seems like a very invasive change. Why does a change in an index seed require changes in the table's transaction builder?

@LuQQiu

LuQQiu commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor Author

@westonpace You're right that adding negative_nan_count alone would not explain this much complexity. The compatibility issue comes from also changing the meaning of the existing bounds. That is separate from how we activate the flags; it does not, by itself, justify plumbing seed-specific state through the transaction builder.

Old seeds compute ordinary bounds, then overwrite max with +NaN whenever any NaN exists (it overloads the max with all nans which makes the whole thing quite complicated). V1 seeds keep non-null, non-NaN bounds and record NaNs separately.

The examples below each describe one Float64 zone. +NaN and -NaN are shorthand for appropriately typed query literals with matching NaN payloads. Under Arrow Rust ordering, negative NaNs sort below ordinary numbers and positive NaNs above them.

Existing reader bugs

These happen with the old statistics already; they are not new compatibility regressions:

Data Old statistics (min, max, nan_count) Query Old result Correct result
[1, 5, -NaN] (1, +NaN, 1) x < 0 [] [-NaN]
[1, 5] (1, 5, 0) x > -NaN [] [1, 5]
[+NaN] (null, +NaN, 1) x > 100 [] [+NaN]

These are reader bugs and can be fixed without changing the stored bounds.

A previously correct query can fail with the new seeds

For [1, 5, +NaN]:

Old seeds V1 seeds
min 1 1
max +NaN 5
nan_count 1 1
negative_nan_count Absent 0

For x > 100, the correct result is [+NaN].

  • Old statistics + old reader: the zone is retained, and the query returns [+NaN].
  • New statistics + old reader: max = 5 causes the zone to be skipped, and the query returns [].

The actual compatibility path matters: this PR keeps the ZoneMap index file format and its legacy marker unchanged. The failure above occurs if an old client harvests V1 data-file seeds, ignores their version and extra column, and writes those ordinary bounds into an index. The old seed-update path copies the bounds; it does not reconstruct the +NaN marker from nan_count.

Putting negative NaNs into min is not a compatible alternative either

This is an alternative layout, not the proposed V1 format:

Data Alternative bounds Query Old result Correct result
[1, 5, -NaN] min=-NaN, max=5 x IN (1, 5) [] [1, 5]

The old ZoneMap IN implementation rejects ordinary floating-point candidates when min is NaN.

Seed version versus feature flags

  • Seed version identifies the statistics contract for updated readers. A column-presence rule could also distinguish the layouts if we defined it that way; an explicit version is the discriminator used here. Neither approach makes already-released code reject the new semantics.
  • Feature flags provide that rejection mechanism: unsupported clients refuse the dataset rather than silently interpret ordinary bounds as legacy bounds. The reader bit blocks incompatible reads, and the writer bit blocks unsupported maintenance/writes.

An index-version bump alone cannot protect this path: seeds are stored in data files and can be consumed later during index maintenance. The compatibility fence must cover that consumption, not only the resulting index file.

@lance-gatekeeper lance-gatekeeper Bot added K-changes Latest Gatekeeper recommendation requests changes. and removed K-changes Latest Gatekeeper recommendation requests changes. labels Oct 19, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Oct 19, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Oct 19, 2026
Implement the version 1 zone write seed format: ordinary min/max bounds,
exact NaN counts split by sign, zones located by their lengths. Seeds are
carried through binary-copy compaction by concatenating the inputs' zone
records per output file and per column, so compacted data keeps feeding
index updates without a rescan.

The paired FLAG_ZONE_WRITE_SEEDS bits are derived at commit time from the
manifest's index configuration: a usable index that asks for seeds, in the
manifest being built or in the committing writer's snapshot, sets them, and
they stay sticky. Seeds are only ever written for such indices, so the bits
are set no later than the first commit that references a seeded file, and
nothing has to be read from data files or carried on the transaction.

The ZoneMap index file format is unchanged.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Oct 19, 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 Oct 19, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 19, 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.

Detached commits now reject incomparable snapshots, including mixed batch inputs. The NaN pruning, seed capability fence, and binary-copy field mapping remain intact.

Please mark this PR with the breaking-change label.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. and removed K-approved Latest Gatekeeper recommendation permits acceptance. labels Oct 19, 2026

@westonpace westonpace left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the changes. Since we've already created the feature flags then let's move forwards.

In the future I think we might need to write the index version into the seed files. Then have any seed extraction routine verify that all seeds have the same version. I think this would allow us to reject mixed seeds properly while avoiding the creation of new feature flags.

Comment thread rust/lance/src/dataset/write/commit.rs Outdated
Comment on lines +667 to +680
fn validate_detached_base_version(base_version: u64, read_version: u64) -> Result<()> {
if base_version == read_version
|| (!is_detached_version(base_version)
&& !is_detached_version(read_version)
&& base_version > read_version)
{
return Ok(());
}
Err(Error::invalid_input(format!(
"detached commit base version {base_version} cannot be used with transaction \
read version {read_version}: use the same snapshot, or a newer mainline \
snapshot when both versions are mainline"
)))
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems unrelated to the PR's goals. I'm guessing it popped up because some new test happened to trigger this existing bug?

Comment thread rust/lance/src/dataset/optimize.rs Outdated
)
.await
{
log::debug!("Binary copy disabled: {}", e);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we expand on this debug message to mention that the copy is disabled likely because of excess global buffers.

Comment on lines +740 to +742
// output footer (including global buffers) is re-generated. Extra
// global buffers are allowed only when every one of them is a
// recognized zone write seed, which the copy then carries or

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extra global buffers are allowed only when one of them is a recognized zone write seed

This seems like a significant limitation for binary copy, though I understand the dilemma. I think the behavior for now is fine but it just makes me even more wary of binary copy 😆

A seed whose format version this build does not support is a recognized
seed: binary copy still copies the data and omits only that column's seed
(no buffer, no locator), instead of refusing the fast path. Other columns
are decided independently; nothing is re-encoded, rescanned, relabeled or
merged across versions. The decoder keeps refusing such seeds, so an index
update fails before publishing anything, and the write path never reads
existing files' seeds. The binary-copy debug log now names extra global
buffers as the reason when a file is disqualified.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 21, 2026
LuQQiu and others added 2 commits October 21, 2026 10:46
…adata

The seed decoder checked the version after decoding the null bitmap, so a
future version with a different bitmap encoding would have failed as a
corrupt bitmap instead of an unsupported version. The version is now the
first thing interpreted, matching the binary-copy parser.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…seed PR

The generic rule for which read snapshot and detached base combinations
CommitBuilder accepts is not a seed feature. write/commit.rs is back to the
base revision, and the tests that required rejecting older or unrelated
detached bases are removed. Same-snapshot and newer-handle detached
publication tests and the sticky flag inheritance tests stay.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@LuQQiu

LuQQiu commented Oct 21, 2026

Copy link
Copy Markdown
Contributor Author

@westonpace Thanks for reviewing the PR! In V1, we introduce the seed version. Because the old legacy version zone seeds cannot handle new versions, we require the new read/write flag. But after this PR, the reader/writer can handle unknown seed version case, so new reader/writer flag will not be needed anymore.

I also removed the generic detached/batch commit validation as outside this PR’s scope and updated the binary-copy debug message as requested.

@LuQQiu
LuQQiu merged commit 59d4d98 into main Oct 21, 2026
@LuQQiu
LuQQiu deleted the lu/zone-seeds-v1 branch October 21, 2026 20:24
Xuanwo pushed a commit that referenced this pull request Oct 22, 2026
## Why

V1 zone write seeds keep ordinary min/max and count NaNs separately. The
current ZoneMap index loses that information when saving: any NaN
replaces `max` with a `+NaN` marker, and the negative NaN count is not
stored.

This proposal updates the existing ZoneMap index format so it can retain
those statistics.

Depends on #10102 for V1 seed handling and NaN-aware query evaluation.
This PR defines the format only; runtime support follows separately.

The V1 write-seed statistics contract was defined and approved in
[#9564](#9564). This proposal
applies the same bound and NaN-count meanings to the ZoneMap index file.

## Changes

- Define `IndexMetadata.index_version = 1`.
- Keep NaNs out of `min` and `max`; use Arrow Rust ordering for ordinary
bounds.
- Add non-null `negative_nan_count: UInt32`. `nan_count` remains the
total, so positive NaNs equal total minus negative.
- Make the null bitmap optional. Without it, null counts support pruning
and candidate rows require rechecking.
- Clarify that one logical index may have multiple segments, each with
its own `zonemap.lance` file.

V0 remains readable with unknown NaN signs. It cannot simply be
relabeled as V1; recovering missing statistics may require a scan.
Unsupported index versions follow the existing index-version
compatibility rules; no additional table reader/writer flag is proposed.
Write-seed feature flags are unchanged.

The schema also corrects the existing documentation's `zone_length` type
to UInt64, matching the current writer; its encoding is not changed.

## Scope and validation

Only `docs/src/format/index/scalar/zonemap.md` changes. No new index
type, protobuf change, cache layout, seed-aggregation policy, or runtime
implementation.

- Documentation build passed (existing unrelated link warnings).
- Pre-commit checks and `git diff --check` passed.

Related: #8190 also proposes ZoneMap V1 for null-only statistics.
Version allocation needs coordination before either proposal merges.
LuQQiu added a commit that referenced this pull request Oct 27, 2026
## Why

ZoneMap V0 uses `max = +NaN` to mark any zone containing NaNs, including
negative NaNs. This hides the ordinary maximum and does not tell the
reader which NaN signs are present.

#10102 added ordinary bounds and separate negative-NaN counts to write
seeds. This PR brings the same information into **ZoneMap index V1**,
implementing the format proposed in #9986. It does not change the seed
format again.

## What V1 stores

For example, a zone containing `[1.0, 5.0, -NaN, +NaN]` is represented
as:

| Field | V0 | V1 |
| --- | --- | --- |
| `min` | `1.0` | `1.0` |
| `max` | `+NaN` marker | `5.0` |
| `nan_count` | `2` | `2` |
| `negative_nan_count` | Not stored | `1` |

V1 keeps these meanings separate:

- `min` / `max`: bounds on non-null, non-NaN values, following **Arrow
Rust ordering**. Infinities are included. Bounds are null when there are
no ordinary values; nested types retain their existing null-only
behavior.
- `null_count`: number of nulls.
- `nan_count`: number of all NaNs.
- `negative_nan_count`: number of those NaNs with the sign bit set.
Positive NaNs are `nan_count - negative_nan_count`.

The reader uses the bounds and NaN counts together for conservative
pruning. NaNs no longer overwrite an ordinary bound in a V1 file.

## What happens to existing indexes?

**New indexes use V1; existing V0 segments remain readable and are not
eagerly rewritten.** Both versions can serve the same logical index.
Each segment is decoded according to its own `index_version`.

| Operation | Behavior |
| --- | --- |
| Create a new segment | Write V1 |
| Dataset maintenance selects a V0 segment for replacement | Rebuild its
covered data as V1 |
| Low-level `ScalarIndex::update` | Preserve the input version,
following the existing convention |
| Direct merge of V0 + V0 | Write V0 |
| Direct merge of V1 + V1 | Write V1 |
| Direct merge of V0 + V1 | Reject before writing; rebuilding is
required |

A valid V0 seed is eligible for V1 reuse only when its stored
`nan_count` is explicitly zero; its negative count is then provably
zero. Missing counts are not zero. A V0 seed containing NaNs cannot
supply V1's ordinary maximum and exact sign split, so the update falls
back to scanning rather than inventing statistics. Every output V1
record must satisfy the V1 contract; conservative V0 query compatibility
does not relax it. This PR retains coarse-grained fallback;
finer-grained seed reuse is separate work.

Optional V0 seeds with invalid counts or incomplete fragment coverage
also fall back to scanning before reaching the strict V1 writer.

## Safety and compatibility

- V1 read/write validation rejects impossible counts and NaN bounds. A
retained, shortened FRI-remapped zone is also rejected by direct merge
when its counts can no longer be established exactly; callers must
rebuild it instead. Destination fragments excluded from the merge are
filtered before fallible remap-run construction and validation.
- The existing `index_version` filter lets readers without V1 support
skip V1 segments and fall back to scans. New readers continue to read V0
segments under their original contract.
- No new table feature flag is added. Zone sizing, configurable
null-bitmap collection, and packed in-memory storage are outside this
PR.

## Tests

Coverage includes V0/V1 round trips, invalid statistics, unknown
versions, seed reuse/fallback, merge-version rules, remap-count safety,
a released V8 fixture rebuilt as V1, and fresh V1 segments committed
alongside untouched V0 coverage. Dataset tests assert the index is used
and results equal a scan.

Validation at `f497c6c97`:

- GitHub checks completed with no failures, including Linux x86/ARM,
macOS, Windows and compatibility tests. The external-plugin test fixture
now advertises the ZoneMap version it delegates to, fixing the earlier
four-platform CI failure.
- Author-run fmt and clippy passed; `lance-index` 2,775 passed / 3
ignored. Targeted ZoneMap tests: 68 lance-index and 117 Lance tests
passed; external-plugin integration tests: 7 passed.
- Author-run Lance library: 6,402 passed / 1 failed / 4 ignored. The
failure was the FTS background tiered-merge timing test; all five
isolated reruns passed. That local full invocation was **not entirely
green**. Other integration suites and doc tests passed.
- Author rebuilt Python bindings on the same head: targeted tests 25
passed; compatibility 7 passed / 1 skipped (the suite excludes ZoneMap
0.x downgrade); Python lint passed.

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

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
Xuanwo added a commit that referenced this pull request Nov 23, 2026
…arrow (#11294)

cc @westonpace — opening this PR to consolidate `lance-arrow-scalar` and
`lance-arrow-stats` into `lance-arrow` ahead of the `v15.0.0` release.
Happy to hear your thoughts if you still want to keep them as standalone
Arrow-versioned crates!

## Context

While preparing the `v15.0.0` stable release, we hit a hard Rust publish
blocker:

1. **Blocked `v15.0.0` crates.io publish**: `#10397` bumped
`lance-arrow-scalar` and `lance-arrow-stats` to `59.0.0` (pinned via
`=59.0.0` in the root `Cargo.toml`), while crates.io still only has
`58.0.0`. `.github/workflows/cargo-publish.yml` excludes both crates
(`--exclude lance-arrow-stats --exclude lance-arrow-scalar`), and there
is no other publish workflow, so `cargo publish --workspace` fails
immediately when resolving `lance-index`.
2. **Silent source drift on crates.io**: Because these two crates track
Arrow's major version instead of `workspace.package.version` and were
excluded after `#6972`, changes in `#6808` (`ArrowScalar::is_nan`) and
`#7966` (`Decimal128/Decimal256` min/max stats) landed without bumping
`58.0.0`. Rust users installing `lance 8.x–14.0.3` from crates.io
received the stale May `58.0.0` tarball instead of the workspace source,
and `#10102` added further Lance-specific ZoneMap seed NaN tracking on
top.
3. **Zero external usage & single-owner publishing**: On crates.io, both
crates have only internal Lance reverse dependencies
(`lance-arrow-stats`, `lance-index`, `lance`) and a single crate owner
(missing `github:lancedb:release`).
4. **Original goal still holds in `lance-arrow`**: The original
motivation in `#5955` / `#5967` was to avoid pulling DataFusion into
lower-level crates. `lance-arrow` has zero DataFusion dependencies, is
already depended on by `lance-encoding`, `lance-file`, `lance-core`, and
`lance-index`, and follows `workspace.package.version` cleanly.

Since `v15.0.0` is already a breaking major (Arrow 59 / DataFusion 55)
and crates.io SemVer prevents downgrading `59.0.0` back to `15.0.0`
under the old crate names, merging them into `lance-arrow` removes the
dual-track versioning and publish exclusions cleanly.

## Changes

- Move `ArrowScalar` (and its `From` conversions) into
`lance_arrow::scalar::ArrowScalar` (`rust/lance-arrow/src/scalar/`).
- Drop the unused custom binary scalar codec
(`rust/arrow-scalar/src/serde.rs`, 558 lines with zero callers outside
its own unit tests).
- Move `StatisticsAccumulator`, `Statistics`, `NanCounts`, `count_nans`,
and `count_nans_signed` into `lance_arrow::stats`
(`rust/lance-arrow/src/stats.rs` and
`rust/lance-arrow/src/stats/nan.rs`), along with its proptest regression
seeds (`rust/lance-arrow/proptest-regressions/stats.txt`).
- Add `arrow-cast` and `arrow-row` to `rust/lance-arrow/Cargo.toml`
(both are already workspace Arrow dependencies; `lance-arrow` remains
free of DataFusion).
- Update internal callers (`lance-index` zonemap/bloomfilter and
`rust/lance/tests/arrow_ordering.rs`) and remove `rust/arrow-scalar` and
`rust/arrow-stats` from the workspace and all three lockfiles
(`Cargo.lock`, `python/Cargo.lock`, `java/lance-jni/Cargo.lock`).
- Drop `--exclude lance-arrow-stats --exclude lance-arrow-scalar` from
`.github/workflows/cargo-publish.yml`, and update the
`arrow-ordering-compat` path trigger in `.github/workflows/rust.yml` and
`rust/AGENTS.md`.

## Notes on `arrow-ordering-compat`

No ordering expectations in `rust/lance/tests/arrow_ordering.rs`
changed—only the two `use` imports were updated from
`lance_arrow_scalar` / `lance_arrow_stats` to `lance_arrow::scalar` /
`lance_arrow::stats`. Because the base branch's copy of
`arrow_ordering.rs` still references the removed crates, the base-branch
compile check in `arrow-ordering-compat` will need the
`arrow-ordering-reviewed` label once reviewed.

## Verification

- `cargo fmt --all -- --check`
- `cargo test --profile ci --locked -p lance-arrow` (366 passed,
including 34 `scalar::arrow_scalar`, 4 `scalar::convert`, 64 `stats::`,
and 9 doctests)
- `cargo test --profile ci --locked -p lance-index --lib
'scalar::zonemap::tests'` (85 passed) and `'scalar::bloomfilter::tests'`
(36 passed)
- `cargo test --profile ci --locked -p lance --test arrow_ordering` (46
passed)
- `RUSTDOCFLAGS="-D warnings" cargo doc --profile ci --locked --no-deps
-p lance-arrow`
- `cargo clippy --profile ci --locked --all --tests --benches -- -D
warnings`
- `cargo clippy --profile ci --locked -p lance --test arrow_ordering --
-D warnings`
- `cargo package --workspace --no-verify --all-features` and `cargo
publish --workspace --all-features --dry-run --no-verify` (all 28
workspace crates resolve and pass dry-run)
- `cargo metadata --frozen` verified across `Cargo.toml`,
`python/Cargo.toml`, and `java/lance-jni/Cargo.toml`
Xuanwo added a commit that referenced this pull request Nov 24, 2026
…v0 writes by default (#11433)

## Summary

Fixes a cross-version compatibility break introduced by #10102 before
releasing Lance v15.0.0.

### Problem

Since Lance v10 (#7427), `ZoneMap` indices on string, binary, decimal,
fixed-size binary (>8 bytes), and nested columns default to `use_seeds =
true`. In #10102, any commit on a dataset carrying a `use_seeds = true`
ZoneMap index automatically set `FLAG_ZONE_WRITE_SEEDS` (`1 << 16`) in
both `reader_feature_flags` and `writer_feature_flags`.

Because `v14.0.0` reserves bit 16 as unsupported and `v15.0.0` is the
first stable release able to read it, automatic activation breaks
rolling upgrades: a single v15 writer performing any normal commit
(`Append`, `Update`, `Delete`, `DataReplacement`, `Compact`, etc.)
permanently (sticky bit) locks out all Lance `< 15` readers with no
rollout window. This also diverged from the zone write seeds format spec
(#9564, `docs/src/format/index/scalar/zone_write_seeds.md`, *"Activation
is explicit, not triggered by opening a table"*) and from every other
v15 reader feature flag (`FLAG_MANAGED_BLOBS`,
`FLAG_SPILLED_ROW_LINEAGE`, `FLAG_INLINE_DELETIONS`), all of which
require explicit opt-in.

### Changes

- **Remove automatic activation**: Remove `apply_seed_feature_flags`
from the commit path (`rust/lance/src/io/commit.rs`,
`rust/lance/src/dataset/write/seeds.rs`). Normal commits and
`CreateIndex` no longer set `FLAG_ZONE_WRITE_SEEDS`.
- **Add explicit opt-in config**: Add dataset config key
`lance.zone_write_seeds.version` (valid values `"0"` and `"1"`)
validated when modified on both legacy (`UpdateConfig`, `Overwrite`) and
composite transaction paths (`rust/lance-table/src/feature_flags.rs`,
`rust/lance-table/src/transaction/`).
- Absent or `"0"`: `FLAG_ZONE_WRITE_SEEDS` stays unset; writers emit v0
seeds.
- `"1"`: Atomically sets `FLAG_ZONE_WRITE_SEEDS` in both
`reader_feature_flags` and `writer_feature_flags`. Once set, the flag
remains sticky across subsequent commits, index drops, restores, and
clones; setting `"0"` pins future writes back to v0 while keeping the
flag sticky.
- Designed to live in the same `lance.zone_write_seeds.*` namespace as
#11373.
- **Keep v0 write seeds by default**: Add `ZoneMapSeedVersion::{V0, V1}`
to `ZoneMapSeedWriter` (`rust/lance-index/src/scalar/zonemap.rs`).
Tables that have not activated `FLAG_ZONE_WRITE_SEEDS` (or are pinned to
`"0"`) emit v0 seeds (no `version` metadata, no `negative_nan_count`,
`max = +NaN` when `nan_count > 0`, `required_feature_flags() == 0`).
This preserves Lance `< 15` read/write compatibility **without**
regressing `optimize_indices` performance (since #10165 already reuses
v0 seeds with `nan_count == 0`, covering all non-float and NaN-free
float zones).
- **Binary-copy compaction**: Carry v1 seeds when
`write_v1_zone_write_seeds` is true; otherwise drop v0 seeds cleanly
without activating `FLAG_ZONE_WRITE_SEEDS`
(`rust/lance/src/dataset/optimize/binary_copy.rs`).
- **Tests**:
- Updated and expanded unit/integration tests across `lance-table`,
`lance-index`, and `lance` covering v0 default writes, explicit v1
opt-in, sticky flag behavior, config validation, binary-copy compaction,
and external scalar plugins.
- Extended `ZonemapBloomfilterIndex` in
`python/python/tests/compat/test_scalar_indices.py` with a string column
(which defaults to `use_seeds=True` on Lance >= 10) so the compat matrix
catches write-seed regressions going forward.

## Verification

- `cargo test --profile ci -p lance-table --lib --doc`
- `cargo test --profile ci -p lance-index --lib zonemap`
- `cargo test --profile ci -p lance --lib -- seed` / `binary_copy` /
`zone_map`
- `cargo test --profile ci -p lance --test external_scalar_plugin`
- `cargo fmt --all -- --check` & `cargo clippy --profile ci --all
--tests --benches -- -D warnings`
- `cd python && uv run make lint` (ruff, pyright, cargo fmt, cargo
clippy)
- Smoke-tested `ZonemapBloomfilterIndex` locally against the built
`pylance` wheel
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 enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants