This is an automated email from the ASF dual-hosted git repository.

yiguolei pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/branch-4.2 by this push:
     new 2e68f5cb05c branch-4.2: [opt](inverted index) Write SNII norms in the 
smaller form by default #70968 (#71139)
2e68f5cb05c is described below

commit 2e68f5cb05c853f1b8d630873644c7b1809b61a3
Author: github-actions[bot] 
<41898282+github-actions[bot]@users.noreply.github.com>
AuthorDate: Wed Dec 2 10:11:33 2026 +0800

    branch-4.2: [opt](inverted index) Write SNII norms in the smaller form by 
default #70968 (#71139)
    
    Cherry-picked from #70968
    
    Co-authored-by: Jack <[email protected]>
---
 .../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, &section));
     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 f81ae6c6279..3bec7e2ea1e 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
@@ -939,9 +939,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 e3f440ec70d..ab11a33d549 100644
--- a/be/test/storage/index/index_disk_usage_test.cpp
+++ b/be/test/storage/index/index_disk_usage_test.cpp
@@ -704,10 +704,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 587ecadc05c..85557612e2b 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/".
 
@@ -51,6 +52,7 @@
 #include "storage/types.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"
 
@@ -75,10 +77,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},
 };
@@ -208,6 +214,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 92aa0c4cb60..1150f43b68f 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
@@ -42,6 +42,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 {
@@ -257,6 +258,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) {
@@ -318,8 +332,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
@@ -381,6 +399,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) {
@@ -390,6 +412,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]

Reply via email to