This is an automated email from the ASF dual-hosted git repository.
airborne12 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/master by this push:
new d43bbb7472d [opt](inverted index) Write SNII norms in the smaller form
by default (#70968)
d43bbb7472d is described below
commit d43bbb7472dbba3da48b2c2a6eccf0f454bf8355
Author: Jack <[email protected]>
AuthorDate: Mon Nov 30 11:21:07 2026 +0800
[opt](inverted index) Write SNII norms in the smaller form by default
(#70968)
### Background
SNII writes BM25 norms, one byte per row, for every analyzed index with
positions
(`support_phrase`). Since #70883 an index can instead hold a sparse
norms section that stores
the norms of the non-NULL rows only, or one norm that all of them share,
and every reader reads
back the bytes a dense section holds. The writer chose that form only
behind a debug point. A
VARIANT column has one logical index per indexed path, so a segment
stores one byte per row for
each path, also where the path is NULL.
### What problem does this PR solve?
Issue Number: None
Related PR: #70883 (adds the sparse norms format and reader), #68039
(lets users drop norms on VARIANT paths, at the cost of score())
PR Type: Performance
Problem Summary:
On a VARIANT column with sparse paths, the norms of the NULL rows make
up most of an SNII index.
This PR makes the writer keep the smaller of the dense and sparse norms
for every SNII index, so
loads and compactions write sparse norms when they are smaller and a
section that every BE knows
follows them; BM25 scores do not change. It
also charges the memory that the first load of sparse norms reads to the
loading task, which
the review of #70883 found untracked. After an upgrade, existing
segments keep their dense norms
and new segments of such indexes are smaller.
### Details
- **Change map:** 489 changed lines: 44 of production code, 161 of unit
tests, 119 of a
regression test, and 165 of its generated `.out` file.
- Writer (10): `LogicalIndexWriter::build_norms_section` compares the
two forms for every
index whose norms the null bitmap or the bloom filter follows, not only
behind a debug point.
The debug point `LogicalIndexWriter::build_norms_section.dense_norms`
keeps dense norms, for
tests that compare both forms.
- Reader (34): `read_sparse_norms` charges the section and the null
bitmap (its frame and its
decoded form) to the current task while the load runs, with a small RAII
helper
`TaskMemoryCharge`.
- **Why it was slow:** each SNII index with norms stores `doc_count`
bytes, NULL rows included,
and a segment holds one such index per indexed VARIANT path. A path
present in 2% of the rows
still stores a byte for every row.
- **Optimization:** the writer computes the size of the dense and the
sparse section and writes
the sparse one only when it is strictly smaller; a tie keeps the dense
form. Each index is laid
out as postings, dictionary, norms, null bitmap and bloom filter, and a
BE that predates #70883
rewrites a segment by copying it up to the end of the last section it
knows, so the writer
keeps sparse norms only when the null bitmap or the bloom filter follows
them. An index
without NULL rows and without terms (every row empty) therefore keeps
dense norms. The sparse section
and the null bitmap that the reader reads before expanding the norms are
plain allocations,
and the searcher cache charge covers only the expanded bytes, so the
reader now charges them
to the task with `CONSUME_THREAD_MEM_TRACKER`, as
`collection_statistics.cpp` does for the null
docids it reads from SNII.
- **Results:** on a local RELEASE build of this branch, 1,000,000 rows
of a VARIANT column with
50 text paths, each present in 2% of the rows, under one SNII index
(`english`,
`support_phrase`), in one segment:
| | dense norms forced | this PR |
|---|---|---|
| index file (`INDEX_DISK_SIZE`) | 57,578,333 B | 8,578,470 B (-85.1%) |
| `stats_bytes` of the 50 paths (`index_disk_usage`) | 50,004,640 B |
1,004,787 B |
| data file | 113,005 B | 113,005 B |
`score()` of `MATCH_ANY` on one path returns the same 13,333 rows with
the same scores on both
tables.
- **Applicability and cost:** only SNII indexes that write norms change,
and only when the sparse
section is smaller (enough NULL rows, or one norm shared by every
non-NULL row) and the index has
a NULL row or a term. Any other index
keeps its dense section byte for byte. Writing costs one more scan over
the norms of each index.
The first scoring load of a sparse index expands it once, as before, and
now charges up to the
section and null bitmap sizes to the task during that load.
- **Behavior change:** new segments of the indexes above store their
norms in
`SniiSectionRefsPB.sparse_norms` (field 6). A BE that predates #70883
sees such an index as
having no norms: `MATCH` works and `score()` returns an error. A segment
rewrite on such a BE
still copies the sparse section, since a section it knows always follows
it.
### Testing
All BE unit tests ran on a local ASAN BE UT build of this branch with
`GLIBC_COMPATIBILITY=OFF`
(see Notes for Reviewers):
- With the tests switched to the writer's default path and before the
writer change, 8 cases
failed on their assertions (`SniiSparseNormsTest` 6, the
`IndexDiskUsageCollectorTest` and
`SniiIndexReaderAnalyzedQueryTest` sparse cases); they pass after it.
- `SniiSparseNormsTest.SparseNormsLoadIsChargedWhileItRuns` failed
before the reader change (a
peak charge of 0 bytes while the load read 53) and passes after it; the
charge returns to 0
once the load ends.
- `SniiWriterGoldenBytes.EnglishPhrase` and `UnicodePhrase` now pin both
forms: the default
digests moved (the corpus has 4 NULL rows among 12), and with dense
norms forced the digests
are the ones before this PR.
- `SniiSparseNormsTest.NormsThatWouldEndTheIndexStayDense` failed before
the fix for the review
finding (a 10-byte sparse section with no null bitmap and no bloom
filter after it) and passes
after it. `SniiSparseNormsTest.OlderRewritersCopyTheSparseSection`
checks that, wherever the
writer keeps sparse norms, the end of the sections an older BE knows
covers them.
- Filter
`*Snii*:*snii*:*CollectionStatistic*:IndexDiskUsage*:*InvertedIndexWriter*:*NormsPod*:*NullBitmap*:*CoreMetadata*`:
1751 tests from 217 suites passed.
- `AnalysisWriteGolden.MatchesTheFrozenDigests` (TeamCity beut failed on
17287a21af7, most
likely on it) froze the bytes of SNII files whose corpus has NULL rows,
so they moved by 6
bytes. The frozen `write/snii` lines now come from dense norms forced
and still match; four
`write/snii-smaller-norms` lines, added with `ANALYSIS_GOLDEN_REGEN`,
freeze the default files.
- Every suite of the 155 BE test files that use SNII, plus
`AnalysisWriteGolden`: on this branch
2109 passed, 3 skipped, none failed. On master 7dd131e514c with this PR,
the same set had the
golden failure above and two cases,
`VariantValuesSegmentTestWithFormat.ValuesIndexExistsOnlyInSniiSegments/0`
and `/2` (V1 and V2,
"index file is empty"), that fail the same way on master without this
PR.
- Regression test
`inverted_index_p0/storage_format/test_storage_format_snii_sparse_norms`
on a
local RELEASE cluster of 17287a21af7 (the fix for the review finding
does not change its
inputs, which all have terms and NULL rows), `.out` generated by
`run-regression-test.sh -forceGenOut`:
a table written with dense norms forced and one written by default
return the same rows and
scores (30 rows, 3 different scores) on a text column and on a VARIANT
path, and the second
has smaller `stats_bytes` on both indexes (468 to 108 and 470 to 110
bytes).
- The size measurement in Details, on the same cluster.
- `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.
- Not run: a cluster that mixes this BE with one that predates #70883.
### Notes for Reviewers
- Rollout: branch-4.2 has SNII norms (field 5) but not #70883, and 4.2.0
is not released. If
4.2.0 shipped without #70883, its BEs could not compute `score()` on
segments written by this
version during a rolling upgrade, so #70883 should be picked into
branch-4.2 before 4.2.0.
- `snii/writer/memory_reporter.h` says the jemalloc hook already charges
SNII allocations to the
task. That hook was removed in #53794, so plain allocations are not
charged; this PR does not
change the writer side.
- Local environment: with `GLIBC_COMPATIBILITY=ON`, the unmodified base
fails to link
`doris_be_test` with the local ldb toolchain (duplicate `preadv` and
others from
`lance_symbol_versions.c`); the option changes link libraries only. The
regression cluster is
a RELEASE build because this worktree's `custom_env.sh` sets
`BUILD_TYPE=RELEASE`. The local
clang-tidy rejects `-Wno-c2y-extensions` from the clang 20 compile
database and misses
`sanitizer/asan_interface.h`.
### Release note
SNII inverted indexes that store BM25 norms (analyzed with
`support_phrase`) now store them only
for the non-NULL rows, or once when every row shares one, whenever that
is smaller. Indexes on
VARIANT paths that most rows lack become much smaller, for example 57.6
MB to 8.6 MB for 50
paths each present in 2% of 1,000,000 rows. Scores do not change. A BE
without #70883 cannot
compute `score()` on segments written this way.
### Check List (For Author)
- Behavior changed: Yes (see Details)
- Does this need documentation: No
- Pre-submission status: Partially verified: clang-tidy could not fully
analyze the changed
files with the local toolchain, BE UT ran with
`GLIBC_COMPATIBILITY=OFF`, the regression test
ran on a RELEASE build, and no mixed-version cluster was tested
### AI Disclosure
- Tool: Claude Code (Claude Opus 5.5)
- Generated: code, tests, this description
- Human review: TODO(author)
---
.../inverted/snii/reader/logical_index_reader.cpp | 34 ++++-
.../inverted/snii/writer/logical_index_writer.cpp | 10 +-
be/test/storage/index/index_disk_usage_test.cpp | 6 +-
.../inverted/analysis/golden/analysis_golden.txt | 5 +
.../analysis/golden/analysis_write_golden_test.cpp | 33 ++++-
.../snii/reader/snii_index_source_test.cpp | 81 ++++++++--
.../snii/snii_index_reader_analyzed_query_test.cpp | 6 +-
.../snii/writer/snii_writer_golden_bytes_test.cpp | 30 +++-
.../test_storage_format_snii_sparse_norms.out | 165 +++++++++++++++++++++
.../test_storage_format_snii_sparse_norms.groovy | 119 +++++++++++++++
10 files changed, 463 insertions(+), 26 deletions(-)
diff --git a/be/src/storage/index/inverted/snii/reader/logical_index_reader.cpp
b/be/src/storage/index/inverted/snii/reader/logical_index_reader.cpp
index 3ed9fc8da5d..aab10ed9fc6 100644
--- a/be/src/storage/index/inverted/snii/reader/logical_index_reader.cpp
+++ b/be/src/storage/index/inverted/snii/reader/logical_index_reader.cpp
@@ -31,6 +31,7 @@
#include <vector>
#include "common/compiler_util.h"
+#include "runtime/thread_context.h"
#include "storage/index/inverted/snii/encoding/byte_source.h"
#include "storage/index/inverted/snii/encoding/crc32c.h"
#include "storage/index/inverted/snii/encoding/section_framer.h"
@@ -88,6 +89,26 @@ constexpr uint64_t kMaxDictLookupBatchBytes = 4ULL * 1024 *
1024;
// separately: a dense section at its validated length, sparse norms at one
// byte per row, the size they are expanded to.
constexpr size_t kNormsAllocationOverheadCharge = 128;
+
+// Charges bytes held in plain allocations to the current task until it goes
away.
+class TaskMemoryCharge {
+public:
+ TaskMemoryCharge() = default;
+ explicit TaskMemoryCharge(int64_t bytes) { charge(bytes); }
+ TaskMemoryCharge(const TaskMemoryCharge&) = delete;
+ TaskMemoryCharge& operator=(const TaskMemoryCharge&) = delete;
+ ~TaskMemoryCharge() { RELEASE_THREAD_MEM_TRACKER(_bytes); }
+
+ void charge(int64_t bytes) {
+ DCHECK_EQ(_bytes, 0);
+ _bytes = bytes;
+ CONSUME_THREAD_MEM_TRACKER(_bytes);
+ }
+
+private:
+ int64_t _bytes = 0;
+};
+
// The term lookup cache keeps at most this many terms per reader, each at
most this long and with
// at most this many bytes of inline postings, so its footprint has a fixed
bound.
constexpr size_t kTermLookupCacheTerms = 32;
@@ -651,15 +672,26 @@ Status
LogicalIndexReader::read_sparse_norms(std::vector<uint8_t>* dense,
format::NormsPodReader* out)
const {
const RegionRef& norms = section_refs().sparse_norms;
const auto read_len = static_cast<size_t>(norms.length);
+ // The section and the null bitmap are plain allocations freed once the
norms are expanded,
+ // and the searcher cache charge covers only the expanded bytes, so charge
them to the task
+ // while they live.
+ const TaskMemoryCharge section_charge(static_cast<int64_t>(read_len));
std::vector<uint8_t> section;
RETURN_IF_ERROR(reader_->read_at(norms.offset, read_len, §ion));
if (section.size() != read_len) {
return Status::Error<ErrorCode::INVERTED_INDEX_FILE_CORRUPTED, false>(
"logical_index: short sparse norms read");
}
+ TaskMemoryCharge null_bitmap_charge;
format::NullBitmapReader nulls;
bool has_nulls = false;
- RETURN_IF_ERROR(open_null_bitmap(NullDocidsDecodeReservation(), &nulls,
&has_nulls));
+ // Called once the null bitmap frame is read and checked, with the size of
its decoded form.
+ const auto charge_null_bitmap = [this, &null_bitmap_charge](uint64_t
decoded_bytes) {
+ null_bitmap_charge.charge(
+ static_cast<int64_t>(section_refs().null_bitmap.length +
decoded_bytes));
+ return Status::OK();
+ };
+ RETURN_IF_ERROR(open_null_bitmap(charge_null_bitmap, &nulls, &has_nulls));
// Validated against uint32 when the index was opened.
const auto doc_count = static_cast<uint32_t>(stats().doc_count);
return format::NormsPodReader::open_sparse(Slice(section), doc_count,
diff --git a/be/src/storage/index/inverted/snii/writer/logical_index_writer.cpp
b/be/src/storage/index/inverted/snii/writer/logical_index_writer.cpp
index c6ee1231da5..a40816f45b4 100644
--- a/be/src/storage/index/inverted/snii/writer/logical_index_writer.cpp
+++ b/be/src/storage/index/inverted/snii/writer/logical_index_writer.cpp
@@ -936,9 +936,13 @@ Status LogicalIndexWriter::prepare_build(io::FileWriter*
posting_out) {
Status LogicalIndexWriter::build_norms_section() {
// Sparse norms drop the bytes of the NULL rows, and store a norm that
every row shares once.
- // Writers keep dense norms; this debug point lets tests choose between
the two forms.
- bool consider_sparse = false;
- DBUG_EXECUTE_IF("LogicalIndexWriter::finalize_build.sparse_norms", {
consider_sparse = true; });
+ // They are kept only when the null bitmap or the bloom filter follows
them: a BE that predates
+ // them rewrites a segment by copying it up to the end of the last section
it knows, so sparse
+ // norms at the end of an index would be lost. For example, an index whose
rows are all empty
+ // and none NULL keeps dense norms. This debug point keeps dense norms for
tests.
+ bool consider_sparse = !null_docids_.empty() || !term_hashes_.empty();
+ DBUG_EXECUTE_IF("LogicalIndexWriter::build_norms_section.dense_norms",
+ { consider_sparse = false; });
const std::span<const uint32_t> null_docids(null_docids_.data(),
null_docids_.size());
size_t section_size =
format::NormsPodWriter::dense_section_size(doc_count_);
bool constant = false;
diff --git a/be/test/storage/index/index_disk_usage_test.cpp
b/be/test/storage/index/index_disk_usage_test.cpp
index 637c769de2c..1ed2cfe8a3b 100644
--- a/be/test/storage/index/index_disk_usage_test.cpp
+++ b/be/test/storage/index/index_disk_usage_test.cpp
@@ -710,10 +710,10 @@ TEST_F(IndexDiskUsageCollectorTest,
CollectSniiAttributesSparseNormsToTheIndex)
};
auto collect = [&](bool sparse, const std::string& rowset_id) {
const bool debug_points_were_enabled = config::enable_debug_points;
- config::enable_debug_points = true;
+ config::enable_debug_points = !sparse;
DebugPoints::instance()->clear();
- if (sparse) {
-
DebugPoints::instance()->add("LogicalIndexWriter::finalize_build.sparse_norms");
+ if (!sparse) {
+
DebugPoints::instance()->add("LogicalIndexWriter::build_norms_section.dense_norms");
}
auto schema = create_schema();
std::vector<IndexSpec> specs {
diff --git a/be/test/storage/index/inverted/analysis/golden/analysis_golden.txt
b/be/test/storage/index/inverted/analysis/golden/analysis_golden.txt
index eb14c2e786e..a7dbd3246ef 100644
--- a/be/test/storage/index/inverted/analysis/golden/analysis_golden.txt
+++ b/be/test/storage/index/inverted/analysis/golden/analysis_golden.txt
@@ -2052,3 +2052,8 @@
write/v2-array/builtin/chinese/fine_grained/lower_case=unset/stopwords=unset row
write/v2-array/builtin/ik/ik_max_word/lower_case=unset/stopwords=unset rows
419 c35a7c8e356a3bca
write/v2-array/builtin/icu/lower_case=unset/stopwords=unset rows 282
118e86a496cf6071
write/v2-array/custom/char_replace+standard+word_delimiter+asciifolding+lowercase
rows 399 a760e05471aca7f6
+# added at 91051d3f3d4
+write/snii-smaller-norms/builtin/chinese/fine_grained/lower_case=unset/stopwords=unset
rows 5321 90fe015f2ae8f4c1
+write/snii-smaller-norms/builtin/ik/ik_max_word/lower_case=unset/stopwords=unset
rows 5200 7f3b6167bfa33e77
+write/snii-smaller-norms/builtin/icu/lower_case=unset/stopwords=unset rows
4156 2fdcb0e17dbb4f9f
+write/snii-smaller-norms/custom/char_replace+standard+word_delimiter+asciifolding+lowercase
rows 4685 feaf589737ca1537
diff --git
a/be/test/storage/index/inverted/analysis/golden/analysis_write_golden_test.cpp
b/be/test/storage/index/inverted/analysis/golden/analysis_write_golden_test.cpp
index 2196a0db645..08a4ca3a1e1 100644
---
a/be/test/storage/index/inverted/analysis/golden/analysis_write_golden_test.cpp
+++
b/be/test/storage/index/inverted/analysis/golden/analysis_write_golden_test.cpp
@@ -17,7 +17,8 @@
// Frozen index files. The analysis goldens freeze the tokens; these freeze
what the production
// writers make of them, so the paths from the analyzers into the writers are
covered too: the SNII
-// file bytes, and for V1 and V2, whose files carry timestamps, the terms with
their documents and
+// file bytes, with dense norms and with the form the writer chooses, and for
V1 and V2, whose files
+// carry timestamps, the terms with their documents and
// positions read back, for a string column and, on V2, for an array column,
whose elements reach
// the analyzer another way. The digests are in analysis_golden.txt under
"write/".
@@ -50,6 +51,7 @@
#include "storage/tablet/tablet_schema.h"
#include "testutil/golden_file.h"
#include "testutil/tmp_file_dirs_util.h"
+#include "util/debug_points.h"
#include "util/hash_util.hpp"
#include "util/slice.h"
@@ -74,10 +76,14 @@ constexpr const char* kConfigs[] = {
struct Format {
const char* name;
InvertedIndexStorageFormatPB format;
+ // Keeps the SNII writer to dense norms, the form of every index before
the writer chose
+ // between dense and sparse norms; the "snii" digests were frozen then.
+ bool dense_norms = false;
};
constexpr Format kFormats[] = {
- {.name = "snii", .format = InvertedIndexStorageFormatPB::SNII},
+ {.name = "snii", .format = InvertedIndexStorageFormatPB::SNII,
.dense_norms = true},
+ {.name = "snii-smaller-norms", .format =
InvertedIndexStorageFormatPB::SNII},
{.name = "v1", .format = InvertedIndexStorageFormatPB::V1},
{.name = "v2", .format = InvertedIndexStorageFormatPB::V2},
};
@@ -209,6 +215,22 @@ ArrayRows array_rows(const
std::vector<std::vector<std::string>>& batches) {
return rows;
}
+// Writes the rows in `format`, with the SNII writer kept to dense norms when
the format asks.
+std::string write_format(const Format& format, const std::string& name, const
TabletIndex& meta,
+ const std::vector<std::vector<std::string>>& batches)
{
+ if (!format.dense_norms) {
+ return write_index(name, format.format, meta, batches);
+ }
+ const bool debug_points_were_enabled = config::enable_debug_points;
+ config::enable_debug_points = true;
+ DebugPoints::instance()->clear();
+
DebugPoints::instance()->add("LogicalIndexWriter::build_norms_section.dense_norms");
+ std::string prefix = write_index(name, format.format, meta, batches);
+ DebugPoints::instance()->clear();
+ config::enable_debug_points = debug_points_were_enabled;
+ return prefix;
+}
+
// Writes the rows into the V2 index of an array column; returns the index
path prefix.
std::string write_array_index(const std::string& name, const TabletIndex& meta,
const ArrayRows& rows) {
@@ -344,9 +366,10 @@ TEST_F(AnalysisWriteGolden, MatchesTheFrozenDigests) {
for (const Format& format : kFormats) {
const std::string key = std::string(kWritePrefix) + format.name +
"/" + config->name;
const std::string prefix =
- write_index(std::to_string(&format - kFormats) + "_" +
- std::to_string(config -
_configs.begin()),
- format.format, meta, batches);
+ write_format(format,
+ std::to_string(&format - kFormats) + "_" +
+ std::to_string(config -
_configs.begin()),
+ meta, batches);
const WriteDigest digest = format.format ==
InvertedIndexStorageFormatPB::SNII
? snii_digest(prefix)
: clucene_digest(prefix,
format.format, meta);
diff --git
a/be/test/storage/index/inverted/snii/reader/snii_index_source_test.cpp
b/be/test/storage/index/inverted/snii/reader/snii_index_source_test.cpp
index 152611f54e7..cea86ec8e2b 100644
--- a/be/test/storage/index/inverted/snii/reader/snii_index_source_test.cpp
+++ b/be/test/storage/index/inverted/snii/reader/snii_index_source_test.cpp
@@ -29,6 +29,8 @@
#include <vector>
#include "common/config.h"
+#include "runtime/memory/mem_tracker.h"
+#include "runtime/thread_context.h"
#include "storage/index/inverted/query/exec/block_doc_set.h"
#include "storage/index/inverted/query/exec/roaring_docid_sink.h"
#include "storage/index/inverted/query/exec/term_pattern.h"
@@ -429,13 +431,13 @@ TEST_F(SniiScoredSourceTest,
EncodedNormsAreReadOnceAndOnlyWhenAsked) {
EXPECT_EQ(rounds(), read);
}
-// The same corpus written with dense norms and through the writer path that
may choose sparse
-// norms. Every non-NULL row holds "alpha" twice and, when even, "beta" once.
+// The same corpus written with dense norms forced and with the writer's own
choice of form.
+// Every non-NULL row holds "alpha" twice and, when even, "beta" once.
class SniiSparseNormsTest : public ::testing::Test {
protected:
static constexpr uint32_t kDocCount = 40;
- static constexpr const char* kSparseNormsPoint =
- "LogicalIndexWriter::finalize_build.sparse_norms";
+ static constexpr const char* kDenseNormsPoint =
+ "LogicalIndexWriter::build_norms_section.dense_norms";
struct Written {
MemoryFile file;
@@ -485,15 +487,27 @@ protected:
return input;
}
- // Writes `input`, through the writer path that may choose sparse norms
when `sparse`, and
- // opens it for reading.
+ // Rows that all hold no token, none of them NULL: the index has no term,
so no bloom filter
+ // section, and every row has the norm of an empty document.
+ static writer::SniiIndexInput corpus_without_terms() {
+ writer::SniiIndexInput input;
+ input.index_id = 12;
+ input.index_suffix = "sparse";
+ input.config = format::IndexConfig::kDocsPositions;
+ input.doc_count = kDocCount;
+ input.encoded_norms.assign(kDocCount, format::kNullRowNorm);
+ return input;
+ }
+
+ // Writes `input` and opens it for reading. With `sparse`, the writer
chooses the form of the
+ // norms with debug points off; without it, the writer is made to keep
dense norms.
static std::unique_ptr<Written> write(const writer::SniiIndexInput& input,
bool sparse) {
auto written = std::make_unique<Written>();
const bool debug_points_were_enabled = config::enable_debug_points;
- config::enable_debug_points = true;
+ config::enable_debug_points = !sparse;
DebugPoints::instance()->clear();
- if (sparse) {
- DebugPoints::instance()->add(kSparseNormsPoint);
+ if (!sparse) {
+ DebugPoints::instance()->add(kDenseNormsPoint);
}
writer::SniiCompoundWriter compound_writer(&written->file);
assert_ok(compound_writer.add_logical_index(input));
@@ -605,6 +619,37 @@ TEST_F(SniiSparseNormsTest,
IndexWithoutNullRowsStaysDense) {
EXPECT_EQ(written->index.section_refs().sparse_norms.length, 0U);
}
+// A BE that predates sparse norms rewrites a segment by copying it up to the
end of the last section
+// it knows, so sparse norms must never end an index. Without NULL rows and
without terms, no null
+// bitmap and no bloom filter follow the norms, so the index keeps dense norms
although its rows
+// share one norm.
+TEST_F(SniiSparseNormsTest, NormsThatWouldEndTheIndexStayDense) {
+ const auto written = write(corpus_without_terms(), /*sparse=*/true);
+ const auto& refs = written->index.section_refs();
+ EXPECT_EQ(refs.null_bitmap.length, 0U);
+ EXPECT_EQ(refs.bsbf.length, 0U);
+ EXPECT_NE(refs.norms.length, 0U);
+ EXPECT_EQ(refs.sparse_norms.length, 0U);
+}
+
+// Wherever the writer keeps sparse norms, a section that every BE knows
follows them, so the
+// prefix that an older BE copies on a rewrite holds them.
+TEST_F(SniiSparseNormsTest, OlderRewritersCopyTheSparseSection) {
+ const auto check = [](const writer::SniiIndexInput& input) {
+ const auto written = write(input, /*sparse=*/true);
+ const auto& refs = written->index.section_refs();
+ ASSERT_NE(refs.sparse_norms.length, 0U);
+ uint64_t known_end = 0;
+ for (const format::RegionRef& region :
+ {refs.dict_region, refs.posting_region, refs.norms,
refs.null_bitmap, refs.bsbf}) {
+ known_end = std::max(known_end, region.offset + region.length);
+ }
+ EXPECT_GE(known_end, refs.sparse_norms.offset +
refs.sparse_norms.length);
+ };
+ check(corpus(mostly_null_rows()));
+ check(corpus({}, /*shared_norm=*/true));
+}
+
// The writer keeps the smaller form, and a tie keeps the dense one, which
every reader of norms
// knows. Both forms frame their payload alike, so the payloads decide: for 40
rows whose norms
// differ, dense is 1 + 40 bytes and sparse is 3 + (40 - NULL rows) bytes. Two
NULL rows tie,
@@ -631,6 +676,24 @@ TEST_F(SniiSparseNormsTest,
SharedNormIsStoredOnceWithoutNullRows) {
EXPECT_EQ(all_norms(*sparse->source), all_norms(*dense->source));
}
+// Loading sparse norms reads their section and the null bitmap, which are
freed once the norms
+// are expanded. They are charged to the loading task only while the load
runs; the expanded
+// bytes stay under the searcher cache charge.
+TEST_F(SniiSparseNormsTest, SparseNormsLoadIsChargedWhileItRuns) {
+ const auto sparse = write(corpus(mostly_null_rows()), /*sparse=*/true);
+ const auto& refs = sparse->index.section_refs();
+ ASSERT_NE(refs.sparse_norms.length, 0U);
+ ASSERT_NE(refs.null_bitmap.length, 0U);
+ MemTracker tracker("UT-SniiSparseNormsLoad");
+ {
+ SCOPED_CONSUME_MEM_TRACKER(&tracker);
+ EXPECT_EQ(all_norms(*sparse->source).size(), kDocCount);
+ }
+ EXPECT_GE(tracker.peak_consumption(),
+ static_cast<int64_t>(refs.sparse_norms.length +
refs.null_bitmap.length));
+ EXPECT_EQ(tracker.consumption(), 0);
+}
+
// The corpus read through a metered reader, so the rounds of every open count.
class SniiIndexSourceRoundsTest : public ::testing::Test {
protected:
diff --git
a/be/test/storage/index/inverted/snii/snii_index_reader_analyzed_query_test.cpp
b/be/test/storage/index/inverted/snii/snii_index_reader_analyzed_query_test.cpp
index 595ed3e8aad..51c14e4c42b 100644
---
a/be/test/storage/index/inverted/snii/snii_index_reader_analyzed_query_test.cpp
+++
b/be/test/storage/index/inverted/snii/snii_index_reader_analyzed_query_test.cpp
@@ -572,10 +572,10 @@ TEST_F(SniiIndexReaderAnalyzedQueryTest,
SparseNormsScoreLikeDenseNorms) {
}
const auto scores_of = [&](bool sparse, std::string_view name, int64_t*
file_size) {
const bool debug_points_were_enabled = config::enable_debug_points;
- config::enable_debug_points = true;
+ config::enable_debug_points = !sparse;
DebugPoints::instance()->clear();
- if (sparse) {
-
DebugPoints::instance()->add("LogicalIndexWriter::finalize_build.sparse_norms");
+ if (!sparse) {
+
DebugPoints::instance()->add("LogicalIndexWriter::build_norms_section.dense_norms");
}
auto reader = open_reader(scored_segment_with_nulls_input(), name,
_text_meta,
InvertedIndexReaderType::FULLTEXT);
diff --git
a/be/test/storage/index/inverted/snii/writer/snii_writer_golden_bytes_test.cpp
b/be/test/storage/index/inverted/snii/writer/snii_writer_golden_bytes_test.cpp
index 0a729b3a024..4a539a32bfa 100644
---
a/be/test/storage/index/inverted/snii/writer/snii_writer_golden_bytes_test.cpp
+++
b/be/test/storage/index/inverted/snii/writer/snii_writer_golden_bytes_test.cpp
@@ -43,6 +43,7 @@
#include "storage/index/inverted/snii/writer/posting_window_emitter.h"
#include "storage/index/inverted/snii/writer/snii_compound_writer.h"
#include "storage/tablet/tablet_schema.h"
+#include "util/debug_points.h"
#include "util/slice.h"
namespace doris::segment_v2 {
@@ -258,6 +259,19 @@ uint64_t golden_digest(const std::string& name, const
TabletIndex& meta) {
return fnv1a64(bytes);
}
+// The digest of the corpus written with dense norms forced, the form every
index had before the
+// writer chose between dense and sparse norms.
+uint64_t dense_norms_digest(const std::string& name, const TabletIndex& meta) {
+ const bool debug_points_were_enabled = config::enable_debug_points;
+ config::enable_debug_points = true;
+ DebugPoints::instance()->clear();
+
DebugPoints::instance()->add("LogicalIndexWriter::build_norms_section.dense_norms");
+ const uint64_t digest = golden_digest(name, meta);
+ DebugPoints::instance()->clear();
+ config::enable_debug_points = debug_points_were_enabled;
+ return digest;
+}
+
// Writes `rows` through the production stack and returns the size of the
segment file.
size_t written_size(const std::string& name, const TabletIndex& meta,
const std::vector<std::string>& rows) {
@@ -319,8 +333,12 @@ private:
// Whole-image digests re-harvested for the protobuf v1 metadata layout. They
// still pin posting bytes together with every framing, directory, and metadata
// byte, so future format changes remain explicit.
-constexpr uint64_t kGoldenEnglishPhrase = 0x8157f9dd81c5397cULL;
-constexpr uint64_t kGoldenUnicodePhrase = 0x9e2a4ba4abedaef9ULL;
+// The corpus has 4 NULL rows among 12, so the analyzed indexes now keep
sparse norms, and their
+// digests moved. Written with dense norms forced, they keep their earlier
digests.
+constexpr uint64_t kGoldenEnglishPhrase = 0x3d26e539492c3b63ULL;
+constexpr uint64_t kGoldenUnicodePhrase = 0x7074a5beaa075dbfULL;
+constexpr uint64_t kGoldenEnglishPhraseDenseNorms = 0x8157f9dd81c5397cULL;
+constexpr uint64_t kGoldenUnicodePhraseDenseNorms = 0x9e2a4ba4abedaef9ULL;
constexpr uint64_t kGoldenKeywordDocsOnly = 0x27cec04c70573201ULL;
// The default of the knob is part of the written format's behavior: the
fixture above pins it to 0
@@ -382,6 +400,10 @@ TEST_F(SniiWriterGoldenBytes, EnglishPhrase) {
EXPECT_EQ(digest, kGoldenEnglishPhrase)
<< "actual=0x" << std::hex << digest
<< " -- token-path output changed; see file header before
re-harvesting";
+ const uint64_t dense_digest = dense_norms_digest("english_phrase_dense",
meta);
+ EXPECT_EQ(dense_digest, kGoldenEnglishPhraseDenseNorms)
+ << "actual=0x" << std::hex << dense_digest
+ << " -- dense norms output changed; see file header before
re-harvesting";
}
TEST_F(SniiWriterGoldenBytes, UnicodePhrase) {
@@ -391,6 +413,10 @@ TEST_F(SniiWriterGoldenBytes, UnicodePhrase) {
EXPECT_EQ(digest, kGoldenUnicodePhrase)
<< "actual=0x" << std::hex << digest
<< " -- token-path output changed; see file header before
re-harvesting";
+ const uint64_t dense_digest = dense_norms_digest("unicode_phrase_dense",
meta);
+ EXPECT_EQ(dense_digest, kGoldenUnicodePhraseDenseNorms)
+ << "actual=0x" << std::hex << dense_digest
+ << " -- dense norms output changed; see file header before
re-harvesting";
}
TEST_F(SniiWriterGoldenBytes, KeywordDocsOnly) {
diff --git
a/regression-test/data/inverted_index_p0/storage_format/test_storage_format_snii_sparse_norms.out
b/regression-test/data/inverted_index_p0/storage_format/test_storage_format_snii_sparse_norms.out
new file mode 100644
index 00000000000..09c0dca5655
--- /dev/null
+++
b/regression-test/data/inverted_index_p0/storage_format/test_storage_format_snii_sparse_norms.out
@@ -0,0 +1,165 @@
+-- This file is automatically generated. You should know what you did if you
want to edit this
+-- !dense_content_score --
+10 0.6668
+100 0.8653
+110 0.9606
+130 0.6668
+140 0.8653
+150 0.9606
+170 0.6668
+180 0.8653
+190 0.9606
+20 0.8653
+210 0.6668
+220 0.8653
+230 0.9606
+250 0.6668
+260 0.8653
+270 0.9606
+290 0.6668
+30 0.9606
+300 0.8653
+310 0.9606
+330 0.6668
+340 0.8653
+350 0.9606
+370 0.6668
+380 0.8653
+390 0.9606
+50 0.6668
+60 0.8653
+70 0.9606
+90 0.6668
+
+-- !chosen_content_score --
+10 0.6668
+100 0.8653
+110 0.9606
+130 0.6668
+140 0.8653
+150 0.9606
+170 0.6668
+180 0.8653
+190 0.9606
+20 0.8653
+210 0.6668
+220 0.8653
+230 0.9606
+250 0.6668
+260 0.8653
+270 0.9606
+290 0.6668
+30 0.9606
+300 0.8653
+310 0.9606
+330 0.6668
+340 0.8653
+350 0.9606
+370 0.6668
+380 0.8653
+390 0.9606
+50 0.6668
+60 0.8653
+70 0.9606
+90 0.6668
+
+-- !dense_variant_score --
+10 0.6668
+100 0.8653
+110 0.9606
+130 0.6668
+140 0.8653
+150 0.9606
+170 0.6668
+180 0.8653
+190 0.9606
+20 0.8653
+210 0.6668
+220 0.8653
+230 0.9606
+250 0.6668
+260 0.8653
+270 0.9606
+290 0.6668
+30 0.9606
+300 0.8653
+310 0.9606
+330 0.6668
+340 0.8653
+350 0.9606
+370 0.6668
+380 0.8653
+390 0.9606
+50 0.6668
+60 0.8653
+70 0.9606
+90 0.6668
+
+-- !chosen_variant_score --
+10 0.6668
+100 0.8653
+110 0.9606
+130 0.6668
+140 0.8653
+150 0.9606
+170 0.6668
+180 0.8653
+190 0.9606
+20 0.8653
+210 0.6668
+220 0.8653
+230 0.9606
+250 0.6668
+260 0.8653
+270 0.9606
+290 0.6668
+30 0.9606
+300 0.8653
+310 0.9606
+330 0.6668
+340 0.8653
+350 0.9606
+370 0.6668
+380 0.8653
+390 0.9606
+50 0.6668
+60 0.8653
+70 0.9606
+90 0.6668
+
+-- !chosen_phrase --
+10
+100
+110
+130
+140
+150
+170
+180
+190
+20
+210
+220
+230
+250
+260
+270
+290
+30
+300
+310
+330
+340
+350
+370
+380
+390
+50
+60
+70
+90
+
+-- !chosen_norms_are_smaller --
+idx_content true
+idx_v_s true
+
diff --git
a/regression-test/suites/inverted_index_p0/storage_format/test_storage_format_snii_sparse_norms.groovy
b/regression-test/suites/inverted_index_p0/storage_format/test_storage_format_snii_sparse_norms.groovy
new file mode 100644
index 00000000000..fa49cc14dfd
--- /dev/null
+++
b/regression-test/suites/inverted_index_p0/storage_format/test_storage_format_snii_sparse_norms.groovy
@@ -0,0 +1,119 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// SNII keeps BM25 norms for the non-NULL rows only when that form is smaller.
The same rows are
+// written once with dense norms forced and once with the writer's own choice:
both tables return
+// the same rows and scores, and the second keeps fewer norm bytes.
+suite("test_storage_format_snii_sparse_norms", "p0,nonConcurrent") {
+ String dbName = context.config.getDbNameByFile(context.file)
+ sql """ set enable_match_without_inverted_index = false """
+ sql """ set debug_variant_enable_typed_paths_to_sparse = false """
+ sql """ set debug_variant_enable_doc_mode = false """
+
+ def createAndLoad = { String tableName ->
+ sql "DROP TABLE IF EXISTS ${tableName}"
+ sql """
+ CREATE TABLE ${tableName} (
+ id INT,
+ content TEXT,
+ v variant<
+ 's_*' : text,
+ PROPERTIES("variant_max_subcolumns_count"="0")
+ >,
+ INDEX idx_content (content) USING INVERTED PROPERTIES(
+ "parser"="english",
+ "support_phrase"="true"
+ ),
+ INDEX idx_v_s (v) USING INVERTED PROPERTIES(
+ "parser"="english",
+ "support_phrase"="true",
+ "field_pattern"="s_*"
+ )
+ ) ENGINE=OLAP DUPLICATE KEY(id)
+ DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES (
+ "replication_allocation" = "tag.location.default: 1",
+ "disable_auto_compaction" = "true",
+ "inverted_index_storage_format" = "SNII"
+ )
+ """
+ // One row in ten holds text of one to four tokens; the other rows are
NULL on both indexes.
+ sql """
+ INSERT INTO ${tableName}
+ SELECT number,
+ if(number % 10 = 0, concat('alpha', repeat(' beta', (number
DIV 10) % 4)), NULL),
+ if(number % 10 = 0,
+ parse_to_variant(concat('{"s_note":"alpha',
+ repeat(' beta', (number DIV 10)
% 4), '"}')),
+ parse_to_variant('{"other":"gamma"}'))
+ FROM numbers("number" = "400")
+ """
+ sql " sync "
+ }
+
+ def denseNormsPoint = "LogicalIndexWriter::build_norms_section.dense_norms"
+ try {
+ GetDebugPoint().enableDebugPointForAllBEs(denseNormsPoint)
+ createAndLoad("test_snii_sparse_norms_dense")
+ } finally {
+ GetDebugPoint().disableDebugPointForAllBEs(denseNormsPoint)
+ }
+ createAndLoad("test_snii_sparse_norms_chosen")
+
+ // the norms move the scores (rows hold one to four tokens), and both
forms give the same ones
+ order_qt_dense_content_score """
+ select id, round(score(), 4) from test_snii_sparse_norms_dense
+ where content match_any "beta" order by score() desc limit 100
+ """
+ order_qt_chosen_content_score """
+ select id, round(score(), 4) from test_snii_sparse_norms_chosen
+ where content match_any "beta" order by score() desc limit 100
+ """
+ order_qt_dense_variant_score """
+ select id, round(score(), 4) from test_snii_sparse_norms_dense
+ where cast(v["s_note"] as string) match_any "beta" order by score()
desc limit 100
+ """
+ order_qt_chosen_variant_score """
+ select id, round(score(), 4) from test_snii_sparse_norms_chosen
+ where cast(v["s_note"] as string) match_any "beta" order by score()
desc limit 100
+ """
+ order_qt_chosen_phrase """
+ select id from test_snii_sparse_norms_chosen where content
match_phrase "alpha beta"
+ """
+
+ // the norms are counted in stats_bytes of the index that owns them
+ def statsBytes = { String tableName ->
+ return """
+ SELECT index_name, SUM(stats_bytes) AS stats_bytes
+ FROM index_disk_usage("database" = "${dbName}", "table" =
"${tableName}")
+ WHERE structure = 'TERM'
+ GROUP BY index_name
+ """
+ }
+ def sizes = sql """
+ SELECT d.index_name, d.stats_bytes, c.stats_bytes
+ FROM (${statsBytes("test_snii_sparse_norms_dense")}) d
+ JOIN (${statsBytes("test_snii_sparse_norms_chosen")}) c ON
d.index_name = c.index_name
+ ORDER BY d.index_name
+ """
+ logger.info("SNII stats bytes per index (dense forced, writer's choice):
${sizes}")
+ order_qt_chosen_norms_are_smaller """
+ SELECT d.index_name, c.stats_bytes < d.stats_bytes
+ FROM (${statsBytes("test_snii_sparse_norms_dense")}) d
+ JOIN (${statsBytes("test_snii_sparse_norms_chosen")}) c ON
d.index_name = c.index_name
+ """
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]