Skip to content

[opt](inverted index) Add a sparse SNII norms format that skips NULL rows - #70883

Merged
airborne12 merged 2 commits into
apache:masterfrom
airborne12:snii-sparse-norms
Nov 24, 2026
Merged

airborne12 merged 2 commits into
apache:masterfrom
airborne12:snii-sparse-norms

Conversation

@airborne12

@airborne12 airborne12 commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Background

SNII writes BM25 norms, one byte per row, for every analyzed index with positions
(support_phrase): SniiIndexColumnWriter::add_nulls appends encode_norm(0) for each
NULL row, and NormsPodWriter stores [doc_count][one byte per row]. A VARIANT column has
one logical index per extracted path, so a segment stores these bytes once per path, for
every row of the segment, even where the path is NULL. BM25 reads the norm of a row only
when a posting reaches it, and a NULL row has no postings.

What problem does this PR solve?

Issue Number: None
Related PR: #68039 (lets users drop norms on VARIANT paths, at the cost of score() on them)
PR Type: Performance

Problem Summary:

On a VARIANT column with many sparse paths, the bytes of the NULL rows make up most of the
norms: #68039 reports norms as 97.1% of an index file on V2/V3, whose norms have the same
one-byte-per-row layout as SNII's. This PR adds a sparse norms section to SNII that stores
the norms of the non-NULL rows only, or one norm that all of them share, and reads back
exactly the bytes a dense section holds, so BM25 scores do not change. Writers keep writing
dense norms; a debug point lets the writer keep the smaller of the two forms so the tests
cover write and read end to end, and a follow-up PR makes that choice the default. After an
upgrade, existing segments and users see no change.

Details

  • Change map: 1200 changed lines: 527 of production code, 669 of tests, 4 of proto.
    • Format (about 275): SniiSectionRefsPB.sparse_norms = 6, section type
      kNormsSparse = 15, the sparse codec and dense_section_size in norms_pod, and
      NullBitmapReader::for_each_non_null_run.
    • Reader (about 175): LogicalIndexReader checks the new region's length at open, expands
      it with the null bitmap on first use, and charges the searcher cache by the expanded size;
      the segment rewrite snapshot and index_disk_usage count the region.
    • Writer (about 80): LogicalIndexWriter::build_norms_section (moved out of
      finalize_build) computes the size of both forms behind the debug point
      LogicalIndexWriter::finalize_build.sparse_norms and writes the smaller one, and the
      compound writer records a sparse section in field 6.
  • Why it was slow: the cost follows from the code: each SNII index that writes norms
    stores doc_count bytes, one per row, NULL rows included, and a segment holds one such
    index per indexed VARIANT path. A path present in 1% of the rows still stores a byte for
    every row.
  • Optimization: the sparse payload is
    [u8 mode][varint64 doc_count][varint64 value_count][stored bytes]: one byte per non-NULL
    row in docid order (kValues), or one byte shared by all of them (kConstant). The null
    bitmap the index already stores tells which rows are NULL, so the section needs no
    presence set of its own. The reader rebuilds one byte per row and gives a NULL row
    kNullRowNorm, which equals encode_norm(0), the byte the dense form stores for it. The
    BM25 inputs (doc count, total term frequency, the norm of every row) are therefore
    unchanged. The writer keeps the sparse form only when its section is strictly smaller:
    the sparse header costs a mode byte and a varint value count, so with very few NULL rows
    the dense form wins, and a tie keeps the dense form, which every reader of norms knows.
  • Results: no size change in this PR, since writers keep dense norms. By the format, for
    40 rows: with 23 NULL rows (the unit test corpus) the sparse section is 26 bytes instead
    of 47; with 2 NULL rows and differing norms both forms are 47 bytes and the dense one is
    kept; with 3 the sparse one is 46; 40 rows that share one norm, without NULL rows, store
    10 bytes. Sizes on real VARIANT data come with the follow-up that turns the writer on.
  • Applicability and cost: sparse norms apply only to SNII indexes that write norms and
    whose sparse section is smaller: enough NULL rows, or one norm shared by every non-NULL
    row; any other index keeps the dense section byte for byte. Choosing costs one scan over
    the norms of the index to find a shared norm. The
    reader expands the section once per index, on the first scoring query, with a walk over the
    null bitmap and one copy or fill per run of non-NULL rows, and then holds doc_count bytes
    as it does for dense norms. Field 6 is optional and new; a BE that predates it ignores it
    and sees an index without norms, so MATCH still works and score() returns
    INVERTED_INDEX_NOT_SUPPORTED instead of reading the bytes wrongly.

Testing

All on a local ASAN BE UT build of the PR head (based on ac5b289), with
GLIBC_COMPATIBILITY=OFF (see Notes for Reviewers):

  • Before the implementation, with the new APIs stubbed, the new cases failed on their
    assertions: 4 SniiCoreMetadata, 8 SniiNormsPod, and the SniiNullBitmap,
    SniiSparseNormsTest, SniiRewriteSnapshot and IndexDiskUsageCollectorTest cases.
    Before the size rule, WriterKeepsTheSmallerForm, SharedNormIsStoredOnceWithoutNullRows
    and DenseSectionSizeIsTheWrittenSize failed the same way.
  • SniiNormsPod.*: sparse round trips (values, one shared norm, every row NULL, no NULL
    row, 5000 rows with 90% NULL rows) and rejection of malformed sections (unknown mode,
    counts that disagree with the null bitmap or the doc count, wrong lengths, the dense frame
    type, a flipped byte). NullRowNormIsTheNormOfAnEmptyDocument ties kNullRowNorm to
    query::encode_norm(0).
  • SniiCoreMetadata.*: field 6 round trip, dense and sparse together rejected, sparse norms
    without positions rejected, missing offset or length rejected.
  • SniiSparseNormsTest.*: the same corpus written dense and sparse gives the same norm for
    every posting a scoring cursor returns, for every row, and the same scoring stats; the
    cache charge follows the expanded size; the writer keeps the smaller form (a tie stays
    dense, one more NULL row turns sparse); rows that share one norm store it once without
    NULL rows; differing norms without NULL rows stay dense.
  • SniiIndexReaderAnalyzedQueryTest.SparseNormsScoreLikeDenseNorms: through MATCH and
    CollectionSimilarity, every matched row scores bit for bit the same with dense and sparse
    norms, and the sparse file is smaller.
  • SniiRewriteSnapshot.RejectsSparseNormsReferenceOutsideThePhysicalArea and
    IndexDiskUsageCollectorTest.CollectSniiAttributesSparseNormsToTheIndex.
  • Related suites: filter *Snii*:*snii*:*CollectionStatistic*:IndexDiskUsage*:*InvertedIndexWriter*:*NormsPod*:*NullBitmap*:*CoreMetadata*,
    1748 tests from 217 suites passed.
  • build-support/check-format.sh and build-support/check-build-hygiene.sh passed.
    build-support/run-clang-tidy.sh reports no finding on the changed lines; the local
    clang-tidy could not fully analyze the files (see Notes for Reviewers).
  • Not run: regression tests (nothing user-visible changes here; the follow-up adds one) and a
    test with a BE that predates field 6.

Notes for Reviewers

  • Field 6 instead of field 5 or a container feature bit: a BE that predates this PR checks
    field 5 against the dense length when it opens a logical index, so sparse bytes there would
    stop the whole index from opening, MATCH included; a required_features bit would make it
    refuse the whole container.
  • There is no BE config for the format: the form follows from the data, both forms read back
    the same bytes, and no released reader knows field 5 but not field 6. A pick of SNII norms
    to another branch should take this reader with it.
  • LogicalIndexReader::open_null_bitmap is the null-bitmap part of read_null_docids, moved
    out unchanged so that the sparse load reuses it; read_null_docids keeps its behavior.
  • Local environment: with GLIBC_COMPATIBILITY=ON, the unmodified base fails to link
    doris_be_test with the local ldb toolchain, whose libglibc-compatibility.a also defines
    preadv, posix_spawnp and others that lance_symbol_versions.c defines. The option
    changes link libraries only. The local clang-tidy rejects -Wno-c2y-extensions from the
    clang 20 compile database and misses sanitizer/asan_interface.h, so it reported every
    changed file as not fully analyzed; filtering its full output by the changed lines finds no
    finding.

Release note

None

Check List (For Author)

  • Behavior changed: No
  • Does this need documentation: No
  • Pre-submission status: Partially verified: clang-tidy could not fully analyze the changed
    files with the local toolchain, and BE UT ran with GLIBC_COMPATIBILITY=OFF

AI Disclosure

  • Tool: Claude Code (Claude Opus 5.5)
  • Generated: code, tests, this description
  • Human review: TODO(author)

…rows

### Background

SNII writes BM25 norms, one byte per row, for every analyzed index with positions
(`support_phrase`): `SniiIndexColumnWriter::add_nulls` appends `encode_norm(0)` for each
NULL row, and `NormsPodWriter` stores `[doc_count][one byte per row]`. A VARIANT column has
one logical index per extracted path, so a segment stores these bytes once per path, for
every row of the segment, even where the path is NULL. BM25 reads the norm of a row only
when a posting reaches it, and a NULL row has no postings.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#68039 (lets users drop norms on VARIANT paths, at the cost of score() on them)
PR Type: Performance

Problem Summary:

On a VARIANT column with many sparse paths, the bytes of the NULL rows make up most of the
norms: apache#68039 reports norms as 97.1% of an index file on V2/V3, whose norms have the same
one-byte-per-row layout as SNII's. This PR adds a sparse norms section to SNII that stores the norms of the non-NULL
rows only and reads back exactly the bytes a dense section holds, so BM25 scores do not
change. Writers keep writing dense norms; a debug point writes the sparse form so the tests
cover write and read end to end, and a follow-up PR makes it the default for indexes with
NULL rows. After an upgrade, existing segments and users see no change.

### Details

- **Change map:** 1128 changed lines: 507 of production code, 617 of tests, 4 of proto.
  - Format (about 265): `SniiSectionRefsPB.sparse_norms = 6`, section type
    `kNormsSparse = 15`, the sparse codec in `norms_pod`, and
    `NullBitmapReader::for_each_non_null_run`.
  - Reader (about 165): `LogicalIndexReader` checks the new region's length at open, expands
    it with the null bitmap on first use, and charges the searcher cache by the expanded size;
    the segment rewrite snapshot and `index_disk_usage` count the region.
  - Writer (about 75): `LogicalIndexWriter::build_norms_section` (moved out of
    `finalize_build`) writes the sparse section behind the debug point
    `LogicalIndexWriter::finalize_build.sparse_norms`, and the compound writer records it in
    field 6.
- **Why it was slow:** the cost follows from the code: each SNII index that writes norms
  stores `doc_count` bytes, one per row, NULL rows included, and a segment holds one such
  index per indexed VARIANT path. A path present in 1% of the rows still stores a byte for
  every row.
- **Optimization:** the sparse payload is
  `[u8 mode][varint64 doc_count][varint64 value_count][stored bytes]`: one byte per non-NULL
  row in docid order (`kValues`), or one byte shared by all of them (`kConstant`). The null
  bitmap the index already stores tells which rows are NULL, so the section needs no
  presence set of its own. The reader rebuilds one byte per row and gives a NULL row
  `kNullRowNorm`, which equals `encode_norm(0)`, the byte the dense form stores for it. The
  BM25 inputs (doc count, total term frequency, the norm of every row) are therefore
  unchanged.
- **Results:** no size change in this PR, since writers keep dense norms. By the format, an
  index of 40 rows with 23 NULL rows (the unit test corpus) stores a 26-byte sparse section
  instead of a 47-byte dense one, and an index whose rows all share one norm stores one byte
  for them. Sizes on real VARIANT data come with the follow-up that turns the writer on.
- **Applicability and cost:** sparse norms apply only to SNII indexes that write norms and
  have NULL rows; an index without NULL rows keeps the dense section byte for byte. The
  reader expands the section once per index, on the first scoring query, with a walk over the
  null bitmap and one copy or fill per run of non-NULL rows, and then holds `doc_count` bytes
  as it does for dense norms. Field 6 is optional and new; a BE that predates it ignores it
  and sees an index without norms, so `MATCH` still works and `score()` returns
  `INVERTED_INDEX_NOT_SUPPORTED` instead of reading the bytes wrongly.

### Testing

All on a local ASAN BE UT build of this commit (rebased on ac5b289), with
`GLIBC_COMPATIBILITY=OFF` (see Notes for Reviewers):

- Before the implementation, with the new APIs stubbed, the new cases failed on their
  assertions: 4 `SniiCoreMetadata`, 8 `SniiNormsPod`, and the `SniiNullBitmap`,
  `SniiSparseNormsTest`, `SniiRewriteSnapshot` and `IndexDiskUsageCollectorTest` cases.
- `SniiNormsPod.*`: sparse round trips (values, one shared norm, every row NULL, no NULL
  row, 5000 rows with 90% NULL rows) and rejection of malformed sections (unknown mode,
  counts that disagree with the null bitmap or the doc count, wrong lengths, the dense frame
  type, a flipped byte). `NullRowNormIsTheNormOfAnEmptyDocument` ties `kNullRowNorm` to
  `query::encode_norm(0)`.
- `SniiCoreMetadata.*`: field 6 round trip, dense and sparse together rejected, sparse norms
  without positions rejected, missing offset or length rejected.
- `SniiSparseNormsTest.*`: the same corpus written dense and sparse gives the same norm for
  every posting a scoring cursor returns, for every row, and the same scoring stats; the
  cache charge follows the expanded size; an index without NULL rows stays dense.
- `SniiIndexReaderAnalyzedQueryTest.SparseNormsScoreLikeDenseNorms`: through `MATCH` and
  `CollectionSimilarity`, every matched row scores bit for bit the same with dense and sparse
  norms, and the sparse file is smaller.
- `SniiRewriteSnapshot.RejectsSparseNormsReferenceOutsideThePhysicalArea` and
  `IndexDiskUsageCollectorTest.CollectSniiAttributesSparseNormsToTheIndex`.
- Related suites: filter `*Snii*:*snii*:*CollectionStatistic*:IndexDiskUsage*:*InvertedIndexWriter*:*NormsPod*:*NullBitmap*:*CoreMetadata*`,
  1745 tests from 217 suites passed.
- `build-support/check-format.sh` and `build-support/check-build-hygiene.sh` passed.
  `build-support/run-clang-tidy.sh` reports no finding on the changed lines; the local
  clang-tidy could not fully analyze the files (see Notes for Reviewers).
- Not run: regression tests (nothing user-visible changes here; the follow-up adds one) and a
  test with a BE that predates field 6.

### Notes for Reviewers

- Field 6 instead of field 5 or a container feature bit: a BE that predates this PR checks
  field 5 against the dense length when it opens a logical index, so sparse bytes there would
  stop the whole index from opening, `MATCH` included; a `required_features` bit would make it
  refuse the whole container.
- There is no BE config for the format: the form follows from the data, both forms read back
  the same bytes, and no released reader knows field 5 but not field 6. A pick of SNII norms
  to another branch should take this reader with it.
- `LogicalIndexReader::open_null_bitmap` is the null-bitmap part of `read_null_docids`, moved
  out unchanged so that the sparse load reuses it; `read_null_docids` keeps its behavior.
- Local environment: with `GLIBC_COMPATIBILITY=ON`, the unmodified base fails to link
  `doris_be_test` with the local ldb toolchain, whose `libglibc-compatibility.a` also defines
  `preadv`, `posix_spawnp` and others that `lance_symbol_versions.c` defines. The option
  changes link libraries only. The local clang-tidy rejects `-Wno-c2y-extensions` from the
  clang 20 compile database and misses `sanitizer/asan_interface.h`, so it reported every
  changed file as not fully analyzed; filtering its full output by the changed lines finds no
  finding.

### Release note

None

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Partially verified: clang-tidy could not fully analyze the changed
  files with the local toolchain, and BE UT ran with `GLIBC_COMPATIBILITY=OFF`

### AI Disclosure

- Tool: Claude Code (Claude Opus 5.5)
- Generated: code, tests, this description
- Human review: TODO(author)
### Background

The SNII writer path behind the debug point `LogicalIndexWriter::finalize_build.sparse_norms`
wrote sparse norms for every index with NULL rows and dense norms for every other index.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#70883 (this commit is part of it)
PR Type: Performance

Problem Summary:

The sparse section adds a mode byte and a varint value count, so an index with very few NULL
rows got a larger section than the dense one. An index without NULL rows whose rows all share
one norm, such as one-token values, still stored one byte per row. The writer now computes the
size of both forms and keeps the smaller one; a tie keeps the dense form.

### Details

- **Why it was slow:** the choice depended only on whether NULL rows existed, not on size.
- **Optimization:** `build_norms_section` compares `NormsPodWriter::dense_section_size` with
  `sparse_section_size` (whose shared-norm mode now also applies without NULL rows) and writes
  the sparse form only when it is strictly smaller. `dense_section_size` also replaces the two
  copies of the dense size formula in `NormsPodWriter::finish` and `validate_norms_region`.
- **Results:** by the format, for 40 rows whose norms differ, 2 NULL rows make both forms 47
  bytes and the dense form is kept, 3 NULL rows make the sparse form 1 byte smaller; 40 rows
  sharing one norm without NULL rows store a 10-byte section instead of 47 bytes.
- **Applicability and cost:** still reached only through the debug point. One more scan over
  the norms of the index to find a shared norm when the debug point is on.

### Testing

Local ASAN BE UT build with `GLIBC_COMPATIBILITY=OFF`:

- Before the change, `SniiSparseNormsTest.WriterKeepsTheSmallerForm`,
  `SniiSparseNormsTest.SharedNormIsStoredOnceWithoutNullRows` and
  `SniiNormsPod.DenseSectionSizeIsTheWrittenSize` failed on their assertions; they pass after.
- Filter `*Snii*:*snii*:*CollectionStatistic*:IndexDiskUsage*:*InvertedIndexWriter*:*NormsPod*:*NullBitmap*:*CoreMetadata*`:
  1748 tests from 217 suites passed.
- `build-support/check-format.sh` and `build-support/check-build-hygiene.sh` passed; clang-tidy
  reports no finding on the changed lines.

### Release note

None

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Partially verified: clang-tidy could not fully analyze the changed
  files with the local toolchain, and BE UT ran with `GLIBC_COMPATIBILITY=OFF`

### AI Disclosure

- Tool: Claude Code (Claude Opus 5.5)
- Generated: code, tests, this description
- Human review: TODO(author)
@airborne12

Copy link
Copy Markdown
Member Author

run buildall

@airborne12

Copy link
Copy Markdown
Member Author

/review

@github-actions github-actions 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.

Static review of all 22 changed files at f94ccec found one P2 issue: sparse decoding leaves significant temporary buffers outside memory accounting. No P0/P1 finding or existing blocking thread was identified. Default writers remain dense; sparse output requires the debug point.

Critical checkpoint Conclusion from static inspection
Goal and supporting tests Sparse values/constant frames reconstruct dense norm bytes and preserve scoring inputs. Added codec, reader and CollectionSimilarity tests exercise this; production size reduction remains deferred.
Scope and clarity Changes are focused on the sparse representation, its reader, debug writer, rewrite bounds and disk attribution. All changed paths were reviewed.
Concurrency and locks Concurrent scoring queries share the existing mutex/future loader. I/O and expansion run outside the mutex; successful immutable data is published under it. No new lock ordering found.
Lifecycle and initialization NormsCacheState::Data owns expanded bytes and the borrowing reader together; cache handles retain the index and file. No new ownership cycle or cross-TU initializer dependency found.
Configuration No new operator configuration or FE variable. The existing debug-point facility controls sparse writing.
Storage compatibility and rolling upgrades Dense serialization remains unchanged; field 6 avoids interpreting sparse bytes as dense. Older readers see no norms and refuse scoring. Production sparse activation must account for the older-rewriter limitation described below.
Thrift/protobuf compatibility New sparse_norms=6 is optional. Fields 1-5 retain their meanings on branch-4.2/master; snii.proto is absent on branch-3.1/4.0/4.1. This PR targets master, so allocation order is correct.
Parallel paths Materialized and streamed writers share finalization. Current-head rewrites preserve sparse extents and metadata. Native compaction rebuilds norms from posting frequencies and maps NULL rows independently; it does not load source norms.
Conditions and error handling Mode, canonical counts, length, CRC, NULL cardinality and placement errors return Status before publication. Comments explain sparse selection, tie handling and validation. No additional silent-success path established.
Test coverage Inspected round trips, constant/all-NULL/no-NULL cases, malformed frames, size thresholds/ties, row/statistic/score equivalence, cache charge, rewrite bounds and disk attribution. Scratch-memory tracking and mixed-version rewrite behavior lack direct coverage.
Changed test results No regression result files changed. Unit-test expectations agree with the inspected representation and size rules; no test execution is claimed.
Observability Existing corruption statuses and index_disk_usage attribution cover the new representation. No additional logging or metric requirement identified.
Transactions and persistence Section refs are persisted through core metadata; current writers use the existing compound finalization/failure boundary. No EditLog, transaction failover, visible-version or MoW/delete-bitmap change.
Data-write atomicity and crashes The shared writer/session poisoning and final container tail remain the publication boundary; no new crash-recovery or write-concurrency defect established.
FE/BE propagation No new RPC/session variable or FE-to-BE send path.
Performance and memory Sparse selection compares exact framed sizes and keeps dense on ties; expansion occurs once per shared reader. Retained expanded bytes are charged correctly, but transient decode memory is the inline P2 finding. No new libc/toolchain/ABI dependency was introduced by these source changes.
Other issues and user focus No additional user focus was supplied. No other actionable issue remained after the final recheck; existing inline comments/reviews were refreshed and none were present.

Rollout constraint: a pre-field-6 rewriter can omit a constant sparse tail on an index with no tokens and no NULL rows because it bounds its prefix copy using known section refs. Current-head rewrites include sparse_norms, and an exhaustive producer check confirms normal writers cannot create sparse files in this PR. This older-writer/debug-only combination was dismissed as a current default-path regression and retained as a constraint before production writer activation. A field-5-only implementation exists in 4.2.0-rc04, so an assumption that no older implementation exists is insufficient for that later activation.

Validation limits: this was static inspection only. No builds, tests, benchmarks, style tools or mixed-binary runs were executed. Runtime memory measurements and SQL regression execution remain unverified. There are no unresolved review candidates or uncovered changed files within this static scope.

Review converged after 3 round(s).

const RegionRef& norms = section_refs().sparse_norms;
const auto read_len = static_cast<size_t>(norms.length);
std::vector<uint8_t> section;
RETURN_IF_ERROR(reader_->read_at(norms.offset, read_len, &section));

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.

[P2] Account for sparse decode scratch in the query memory tracker

On the first scoring load of a sparse index, this ordinary vector holds the entire sparse section while open_sparse allocates the expanded dense vector; open_null_bitmap also creates frame/CRoaring scratch with an empty reservation callback. The searcher cache charges only doc_count plus fixed state, and this head's jemalloc wrappers do not charge ordinary STL allocations to a task tracker. For a valid 1,000,000-row index with five NULLs and varying norms, the writer selects a 1,000,010-byte sparse section, so almost another megabyte remains unaccounted alongside the charged million-byte dense vector. Larger segments and concurrent first loads multiply that untracked peak and bypass query memory limits. Please track/reserve the sparse section and NULL decode scratch with task-scoped RAII, keeping their lifetime and charge separate from the retained dense cache bytes.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks, confirmed. read_sparse_norms keeps the whole section in a plain std::vector and decodes the null bitmap without a reservation. The SNII FileReader::read_at only fills plain vectors, which are not charged to the query's memory tracker, and the searcher cache charge covers only the expanded doc_count bytes. So during the first load, the section and the null bitmap decode are outside the query memory limit.

In this PR, writers keep writing dense norms. The sparse form is written only behind the debug point LogicalIndexWriter::finalize_build.sparse_norms, so no index written by a normal load reaches this code.

The follow-up PR that turns the sparse form on by default will charge the section and the null bitmap decode to the current thread's memory tracker for the duration of the load, with a unit test. It will also handle your rollout note about a rewriter that predates field 6, before any sparse section can be written by default.

@airborne12
airborne12 marked this pull request as ready for review November 23, 2026 23:42

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

LGTM

@airborne12
airborne12 merged commit 891ae34 into apache:master Nov 24, 2026
46 of 48 checks passed
@airborne12
airborne12 deleted the snii-sparse-norms branch November 24, 2026 13:36
@github-actions

Copy link
Copy Markdown
Contributor

PR approved by anyone and no changes requested.

@github-actions github-actions Bot added the approved Indicates a PR has been approved by one committer. label Nov 24, 2026
@github-actions

Copy link
Copy Markdown
Contributor

PR approved by at least one committer and no changes requested.

airborne12 added a commit to airborne12/apache-doris that referenced this pull request Nov 25, 2026
### Background

SNII lays out each logical index as postings, dictionary, norms, null bitmap and bloom filter,
in this order. A segment rewrite copies the segment up to the end of the last section that the
kept indexes reference, then writes their metadata again, byte for byte.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#70968 (this commit is part of it), apache#70883 (adds the sparse norms format)
PR Type: Bugfix

Problem Summary:

A BE that predates apache#70883 does not know the sparse norms reference, so its rewrite copies the
segment only up to the end of the dense norms, null bitmap or bloom filter. With the size-based
choice on by default, an index without NULL rows and without terms (every row empty) kept its
shared norm in a sparse section with nothing after it. Such a rewrite drops that section and
keeps a reference to it, so a newer BE then cannot load or score the index. The writer now
keeps sparse norms only when the null bitmap or the bloom filter follows them.

### Details

- **Frequency:** an index whose rows are all empty or all stop words and that has no NULL row,
  in a segment rewritten by a BE that predates apache#70883.
- **Root cause:** `build_norms_section` chose sparse norms whenever they were smaller, also when
  they would be the last section of the index.
- **Why existing tests missed it:** no test wrote an index without terms and NULL rows, and none
  checked where the sparse section lies.
- **Fix:** `build_norms_section` considers sparse norms only when `null_docids_` or
  `term_hashes_` is not empty, which is when the writer adds a null bitmap or a bloom filter
  after the norms. Such an index keeps dense norms.
- **Other paths and branches:** the column writer and SNII compaction both go through
  `build_norms_section`.

### Testing

Local ASAN BE UT build with `GLIBC_COMPATIBILITY=OFF`:

- `SniiSparseNormsTest.NormsThatWouldEndTheIndexStayDense` failed before the fix (a 10-byte
  sparse section with no null bitmap and no bloom filter) and passes after it.
- `SniiSparseNormsTest.OlderRewritersCopyTheSparseSection`: for the corpora that keep sparse
  norms, the end of the sections an older BE knows covers the sparse section.

### Release note

None

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Partially verified: clang-tidy could not fully analyze the changed
  files with the local toolchain, and BE UT ran with `GLIBC_COMPATIBILITY=OFF`

### AI Disclosure

- Tool: Claude Code (Claude Opus 5.5)
- Generated: code, tests, this description
- Human review: TODO(author)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved Indicates a PR has been approved by one committer. reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants