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 687ff174476 [opt](storage) Consume compressed row-id mappings in 
CLucene compaction (#70890)
687ff174476 is described below

commit 687ff174476fb49ae722bd5b593e6074daa5c109
Author: bobhan1 <[email protected]>
AuthorDate: Wed Nov 25 10:11:14 2026 +0800

    [opt](storage) Consume compressed row-id mappings in CLucene compaction 
(#70890)
    
    ### Background
    
    Compaction records source-to-destination row locations for delete-bitmap
    conversion and inverted-index merging. #70350 added compressed row-id
    storage with a 500 MiB selection threshold. CLucene index compaction
    still consumes a dense matrix, so its presence prevents compressed
    selection.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #70350 (compressed storage), #69313 (norms compatibility),
    apache/doris-thirdparty#438 (borrowed mapping API)
    PR Type: Performance
    
    Problem Summary:
    
    Large compactions with CLucene indexes retain dense row-id arrays even
    when compression is enabled. Upgrade CLucene to its merged lookup API
    and connect it to both RowIdConversion representations without expanding
    a segment. Most additions are tests. Eligible compactions now follow the
    existing compression threshold; configuration defaults and successful
    index results remain unchanged.
    
    ### Details
    
    - **Change map:** 131 production lines (102 for the borrowed adapter, 29
    for selection/integration), 280 test lines, two CMake removals and a
    two-line gitlink change. The dependency moves `f2864e07f08` to
    `bb3b6ef0c32`: apache/doris-thirdparty#438 adds lookup support,
    apache/doris-thirdparty#421 replaces TurboPFor,
    apache/doris-thirdparty#426 fixes macOS CI, and
    apache/doris-thirdparty#420's existing token-count fix is preserved. Its
    65-file diff is +1,819/-26,647 lines, dominated by removing the old
    codec.
    - **Why it was slow:** CLucene forces the eight-byte-per-source-row
    dense representation, then copies the entire matrix into IndexWriter.
    The compressed representation cannot reduce either allocation on this
    path.
    - **Optimization:** Borrow source views through a CLucene adapter, cache
    at most one decoded block per source and share a decode workspace. Reuse
    #70350's codec. Mapping failures propagate as CLuceneError instead of
    becoming deleted postings; dense callers also avoid the writer copy.
    - **Results:** Local Release base-compaction A/B at `9404aa52617`, with
    335,544,320 physical input rows and a V2 untokenized string index
    containing 64 keyword values. Eight interleaved source segments each
    contain 41,943,040 rows (about 696 MiB of data plus 42 MiB of indexes);
    both modes produce six output segments. Hardware: Intel Xeon Platinum
    8457C, 192 logical CPUs; one local-storage FE/BE, Clang 20.1.8, `-O3`,
    jemalloc, no ASAN.
    
      | Metric | DENSE (borrowed) | COMPRESSED (borrowed) |
      |---|---:|---:|
      | Finalized row-id mapping storage | 2.50 GiB | 157.07 MiB |
      | Compaction task tracker peak | 4.41 GiB | 2.06 GiB |
      | Sampled BE process RSS peak | 17.84 GiB | 15.66 GiB |
      | Total compaction wall time | 232.56 s | 277.07 s |
      | Native inverted-index merge wall time | 65.36 s | 104.29 s |
      | Native inverted-index merge thread CPU | 64.63 s | 103.61 s |
    
    Mapping storage falls 93.86%, task peak falls 53.20%, and total time
    rises 19.14% (+44.51 s). Same Release binary, frozen input snapshot,
    warm caches and default 500 MiB threshold; one observation per mode on a
    shared host. The DENSE baseline already omits the writer copy. Mapping
    storage includes all 81,920 block entries and payloads, excluding
    workspaces/cursors and allocator overhead. RSS includes process caches
    and background work; sampling is every 100 ms. Task time excludes
    scheduling and validation.
    
    - **Applicability and cost:** `enable_compressed_rowid_conversion`
    remains enabled by default. Compression requires estimated dense memory
    to exceed `compressed_rowid_conversion_threshold_bytes` (500 MiB); debug
    dumps, cluster keys and sequence maps retain their exclusions. Each
    lookup adds virtual dispatch. Sparse postings and term rewinds can
    decode a 4096-row block repeatedly. Separate smaller unordered
    high-cardinality tests showed substantially larger time overhead; the
    64-term result is workload-specific. SNII selection and budgets are
    unchanged.
    
    ### Testing
    
    Local Clang 20.1.8 ASAN, with the official merged dependency:
    
    ```sh
    bash run-be-ut.sh --run 
--filter='CluceneRowIdMappingTest.*:*TestRowIdConversion*:CompressedRowIdMapTest.*:IndexCompactionTest.*:IndexCompactionWriteIndexTest.*:SniiRowIdConversionTest.*'
 -j100
    ```
    
    78/78 tests passed across seven suites; none skipped.
    
    Coverage includes source/block rewinds, non-contiguous physical segment
    IDs, missing/invalid rows, lookup errors, legacy dense callers, and
    postings/positions/norms/token/null equivalence. Duplicate Key and MoW
    compaction cases assert COMPRESSED mode and compare with raw index
    rebuilds. The #69313 fallback regression remains intact.
    
    Independent CLucene ASAN/LSAN tests passed 31/31, including PFOR
    golden-data/legacy-file compatibility. The merged dependency has exactly
    the tested source tree.
    
    Local Release FE/BE testing additionally completed 12 base compactions
    across CLucene keyword, English full-text/MoW and SNII cases. Input-file
    SHA-256, row counts, full-row aggregate/hash checks, index/null/MATCH
    queries and post-compaction BM25 comparisons passed. Validation sessions
    disabled SQL/query result caches.
    
    ### Notes for Reviewers
    
    The old and upstream apache/doris-thirdparty#420 implementations and
    regression tests match despite their different commit history. Two
    obsolete `ic` references are removed because apache/doris-thirdparty#421
    removed that build target. The test helper now follows production
    mapping selection/finalization.
    
    ### Release note
    
    Eligible compactions with CLucene indexes can use the configured
    compressed row-id mapping instead of always allocating a dense map.
    
    ### Check List (For Author)
    
    - Behavior changed: No
    - Does this need documentation: No
    - Pre-submission status: Ready
    
    ### AI Disclosure
    
    - Tool: OpenAI Codex (GPT-6)
    - Generated: implementation, tests and description
    - Human review: not stated
---
 be/CMakeLists.txt                                  |   2 -
 be/src/storage/compaction/compaction.cpp           |  14 +-
 be/src/storage/compaction/compaction.h             |   2 +-
 .../inverted/clucene/inverted_index_compaction.cpp |  10 +-
 .../inverted/clucene/inverted_index_compaction.h   |   3 +-
 .../index/inverted/clucene/rowid_conversion.cpp    |  53 +++++
 ...erted_index_compaction.h => rowid_conversion.h} |  43 ++--
 .../clucene/compaction/index_compaction_test.cpp   |  34 ++-
 .../compaction/util/index_compaction_utils.h       |  11 +-
 .../inverted/clucene/rowid_conversion_test.cpp     | 230 +++++++++++++++++++++
 be/test/storage/rowid_conversion_test.cpp          |   5 +-
 contrib/clucene                                    |   2 +-
 12 files changed, 370 insertions(+), 39 deletions(-)

diff --git a/be/CMakeLists.txt b/be/CMakeLists.txt
index 7dbe60b6594..450ab4de8b0 100644
--- a/be/CMakeLists.txt
+++ b/be/CMakeLists.txt
@@ -324,7 +324,6 @@ endif()
 target_compile_options(clucene-core-static PRIVATE ${clucene_options})
 target_compile_options(clucene-shared-static PRIVATE ${clucene_options})
 target_compile_options(clucene-contribs-lib PRIVATE ${clucene_options})
-target_compile_options(ic PRIVATE ${clucene_options})
 
 install(DIRECTORY
     ${CONTRIB_PATH}/clucene/src/contribs-lib/CLucene/analysis/jieba/dict
@@ -775,7 +774,6 @@ if (USE_UNWIND)
 endif()
 
 set(DORIS_DEPENDENCIES ${DORIS_DEPENDENCIES} orc)
-set(DORIS_DEPENDENCIES ${DORIS_DEPENDENCIES} ic)
 set(DORIS_DEPENDENCIES ${DORIS_DEPENDENCIES} clucene-core-static)
 set(DORIS_DEPENDENCIES ${DORIS_DEPENDENCIES} clucene-shared-static)
 set(DORIS_DEPENDENCIES ${DORIS_DEPENDENCIES} h3)
diff --git a/be/src/storage/compaction/compaction.cpp 
b/be/src/storage/compaction/compaction.cpp
index 5b630d79b64..5c6940f4267 100644
--- a/be/src/storage/compaction/compaction.cpp
+++ b/be/src/storage/compaction/compaction.cpp
@@ -476,18 +476,17 @@ void Compaction::prepare_rowid_conversion(const 
RowsetWriterContext& ctx) {
                                 _tablet->enable_unique_key_merge_on_write());
     if (!needs_mapping) return;
 
-    auto mode = should_compress_rowid_conversion(ctx) ? 
RowIdConversion::Mode::COMPRESSED
-                                                      : 
RowIdConversion::Mode::DENSE;
+    auto mode = should_compress_rowid_conversion() ? 
RowIdConversion::Mode::COMPRESSED
+                                                   : 
RowIdConversion::Mode::DENSE;
     _rowid_conversion->set_mode(mode);
     _stats.rowid_conversion = _rowid_conversion.get();
     _profile->add_info_string("RowIdConversion",
                               mode == RowIdConversion::Mode::COMPRESSED ? 
"COMPRESSED" : "DENSE");
 }
 
-bool Compaction::should_compress_rowid_conversion(const RowsetWriterContext& 
ctx) const {
-    // CLucene and the legacy debug dump consume a dense matrix.
-    if (!config::enable_compressed_rowid_conversion ||
-        !ctx.columns_to_do_index_compaction.empty() || 
config::debug_inverted_index_compaction) {
+bool Compaction::should_compress_rowid_conversion() const {
+    // The legacy debug dump still consumes a dense matrix.
+    if (!config::enable_compressed_rowid_conversion || 
config::debug_inverted_index_compaction) {
         return false;
     }
     // Cluster-key and sequence-map readers can revisit source rows, whereas 
this
@@ -1577,8 +1576,7 @@ Status Compaction::do_inverted_index_compaction() {
                     dest_index_dirs[dest_segment_pos] = res.value().get();
                 }
                 auto st = compact_column(index_meta->index_id(), src_idx_dirs, 
dest_index_dirs,
-                                         index_tmp_path.native(),
-                                         
_stats.rowid_conversion->get_rowid_conversion_map(),
+                                         index_tmp_path.native(), 
*_stats.rowid_conversion,
                                          dest_segment_num_rows);
                 if (!st.ok()) {
                     error_handler(index_meta->index_id(), column_uniq_id);
diff --git a/be/src/storage/compaction/compaction.h 
b/be/src/storage/compaction/compaction.h
index 18c0d650462..d5ddfca3f81 100644
--- a/be/src/storage/compaction/compaction.h
+++ b/be/src/storage/compaction/compaction.h
@@ -121,7 +121,7 @@ protected:
 
     // Select storage once, before any source segment registers its rows.
     void prepare_rowid_conversion(const RowsetWriterContext& ctx);
-    bool should_compress_rowid_conversion(const RowsetWriterContext& ctx) 
const;
+    bool should_compress_rowid_conversion() const;
 
     Status execute_merge_input_rowsets(MergeInputRowsetsContext* context);
 
diff --git 
a/be/src/storage/index/inverted/clucene/inverted_index_compaction.cpp 
b/be/src/storage/index/inverted/clucene/inverted_index_compaction.cpp
index 2e994702d9b..9abfc46f78f 100644
--- a/be/src/storage/index/inverted/clucene/inverted_index_compaction.cpp
+++ b/be/src/storage/index/inverted/clucene/inverted_index_compaction.cpp
@@ -21,6 +21,7 @@
 #include "storage/index/index_common.h"
 #include "storage/index/index_file_writer.h"
 #include "storage/index/index_fs_directory.h"
+#include "storage/index/inverted/clucene/rowid_conversion.h"
 #include "storage/tablet/tablet_schema.h"
 #include "util/debug_points.h"
 
@@ -29,7 +30,7 @@ Status compact_column(
         int64_t index_id,
         std::vector<std::unique_ptr<DorisCompoundReader, DirectoryDeleter>>& 
src_index_dirs,
         std::vector<lucene::store::Directory*>& dest_index_dirs, 
std::string_view tmp_path,
-        const std::vector<std::vector<std::pair<uint32_t, uint32_t>>>& 
trans_vec,
+        const RowIdConversion& rowid_conversion,
         const std::vector<uint32_t>& dest_segment_num_rows) {
     DBUG_EXECUTE_IF("index_compaction_compact_column_throw_error", {
         if (index_id % 2 == 0) {
@@ -43,6 +44,9 @@ Status compact_column(
         }
     })
 
+    // Both modes borrow conversion storage. Keep the adapter alive through 
writer
+    // close() and exception cleanup by constructing it before the writer.
+    CluceneRowIdMapping mapping(rowid_conversion);
     bool can_use_ram_dir = true;
     std::unique_ptr<lucene::store::Directory, DirectoryDeleter> dir(
             
DorisFSDirectoryFactory::getDirectory(io::global_local_filesystem(), 
tmp_path.data(),
@@ -57,12 +61,12 @@ Status compact_column(
         _CLTHROWA(CL_ERR_IO,
                   "debug point: compact_column_create_index_writer_error in 
index compaction");
     })
-    DCHECK_EQ(src_index_dirs.size(), trans_vec.size());
+    DCHECK_EQ(src_index_dirs.size(), mapping.sourceCount());
     std::vector<lucene::store::Directory*> 
tmp_src_index_dirs(src_index_dirs.size());
     for (size_t i = 0; i < tmp_src_index_dirs.size(); ++i) {
         tmp_src_index_dirs[i] = src_index_dirs[i].get();
     }
-    index_writer->indexCompaction(tmp_src_index_dirs, dest_index_dirs, 
trans_vec,
+    index_writer->indexCompaction(tmp_src_index_dirs, dest_index_dirs, mapping,
                                   dest_segment_num_rows);
     DBUG_EXECUTE_IF("compact_column_indexCompaction_error", {
         _CLTHROWA(CL_ERR_IO,
diff --git a/be/src/storage/index/inverted/clucene/inverted_index_compaction.h 
b/be/src/storage/index/inverted/clucene/inverted_index_compaction.h
index 8bd26436cb3..d100c8e6339 100644
--- a/be/src/storage/index/inverted/clucene/inverted_index_compaction.h
+++ b/be/src/storage/index/inverted/clucene/inverted_index_compaction.h
@@ -27,6 +27,7 @@
 #include "storage/index/index_compound_reader.h"
 
 namespace doris {
+class RowIdConversion;
 class TabletIndex;
 namespace segment_v2 {
 class IndexFileWriter;
@@ -36,7 +37,7 @@ Status compact_column(
         int64_t index_id,
         std::vector<std::unique_ptr<DorisCompoundReader, DirectoryDeleter>>& 
src_index_dirs,
         std::vector<lucene::store::Directory*>& dest_index_dirs, 
std::string_view tmp_path,
-        const std::vector<std::vector<std::pair<uint32_t, uint32_t>>>& 
trans_vec,
+        const RowIdConversion& rowid_conversion,
         const std::vector<uint32_t>& dest_segment_num_rows);
 } // namespace segment_v2
 } // namespace doris
diff --git a/be/src/storage/index/inverted/clucene/rowid_conversion.cpp 
b/be/src/storage/index/inverted/clucene/rowid_conversion.cpp
new file mode 100644
index 00000000000..1b8d5434401
--- /dev/null
+++ b/be/src/storage/index/inverted/clucene/rowid_conversion.cpp
@@ -0,0 +1,53 @@
+// 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.
+
+#include "storage/index/inverted/clucene/rowid_conversion.h"
+
+#include <CLucene.h>
+
+#include "common/cast_set.h"
+#include "storage/rowid_conversion.h"
+
+namespace doris::segment_v2 {
+
+CluceneRowIdMapping::CluceneRowIdMapping(const RowIdConversion& conversion) {
+    _sources.reserve(conversion.source_count());
+    for (size_t source = 0; source < conversion.source_count(); ++source) {
+        _sources.emplace_back(conversion.source(cast_set<uint32_t>(source)));
+    }
+}
+
+CluceneRowIdMapping::Destination CluceneRowIdMapping::get(uint32_t source, 
uint32_t doc) const {
+    if (source >= _sources.size()) {
+        _CLTHROWA(CL_ERR_IO, "CLucene row-id mapping source is out of range");
+    }
+    const auto& entry = _sources[source];
+    // Source views use the missing sentinel for out-of-range probes. A posting
+    // outside its physical source instead indicates a malformed index/mapping.
+    if (doc >= entry.mapping.size()) {
+        _CLTHROWA(CL_ERR_IO, "CLucene row-id mapping document is out of 
range");
+    }
+    Destination destination;
+    auto status = entry.mapping.get(doc, entry.cursor, _workspace, 
&destination);
+    if (!status.ok()) {
+        // A decode/allocation failure must abort index compaction, never drop 
a posting.
+        _CLTHROWA(CL_ERR_IO, status.to_string_no_stack().c_str());
+    }
+    return destination;
+}
+
+} // namespace doris::segment_v2
diff --git a/be/src/storage/index/inverted/clucene/inverted_index_compaction.h 
b/be/src/storage/index/inverted/clucene/rowid_conversion.h
similarity index 50%
copy from be/src/storage/index/inverted/clucene/inverted_index_compaction.h
copy to be/src/storage/index/inverted/clucene/rowid_conversion.h
index 8bd26436cb3..e5b56e8faaa 100644
--- a/be/src/storage/index/inverted/clucene/inverted_index_compaction.h
+++ b/be/src/storage/index/inverted/clucene/rowid_conversion.h
@@ -14,29 +14,36 @@
 // KIND, either express or implied.  See the License for the
 // specific language governing permissions and limitations
 // under the License.
-#pragma once
 
-#include <CLucene.h>
+#pragma once
 
-#include <cstdint>
-#include <string_view>
-#include <vector>
+#include <CLucene/index/DocIdMapping.h>
 
-#include "common/status.h"
-#include "storage/index/index_common.h"
-#include "storage/index/index_compound_reader.h"
+#include "core/custom_allocator.h"
+#include "storage/compressed_rowid_map.h"
 
 namespace doris {
-class TabletIndex;
+class RowIdConversion;
+
 namespace segment_v2 {
-class IndexFileWriter;
-class IndexFileReader;
-
-Status compact_column(
-        int64_t index_id,
-        std::vector<std::unique_ptr<DorisCompoundReader, DirectoryDeleter>>& 
src_index_dirs,
-        std::vector<lucene::store::Directory*>& dest_index_dirs, 
std::string_view tmp_path,
-        const std::vector<std::vector<std::pair<uint32_t, uint32_t>>>& 
trans_vec,
-        const std::vector<uint32_t>& dest_segment_num_rows);
+
+class CluceneRowIdMapping final : public lucene::index::DocIdMapping {
+public:
+    explicit CluceneRowIdMapping(const RowIdConversion& conversion);
+    size_t sourceCount() const override { return _sources.size(); }
+    Destination get(uint32_t source, uint32_t doc) const override;
+
+private:
+    struct Source {
+        explicit Source(RowIdConversionSource view) : mapping(view) {}
+        RowIdConversionSource mapping;
+        mutable CompressedRowIdMap::Cursor cursor;
+    };
+    DorisVector<Source> _sources;
+    // Compaction is synchronous on one thread. A term may interleave sources 
or
+    // revisit earlier blocks: keep one block per source and share the Zstd 
workspace.
+    mutable CompressedRowIdMap::DecodeWorkspace _workspace;
+};
+
 } // namespace segment_v2
 } // namespace doris
diff --git 
a/be/test/storage/index/inverted/clucene/compaction/index_compaction_test.cpp 
b/be/test/storage/index/inverted/clucene/compaction/index_compaction_test.cpp
index 6f3e7d93e7d..9dcb37bf9e5 100644
--- 
a/be/test/storage/index/inverted/clucene/compaction/index_compaction_test.cpp
+++ 
b/be/test/storage/index/inverted/clucene/compaction/index_compaction_test.cpp
@@ -591,9 +591,26 @@ protected:
         EXPECT_EQ(ctx.columns_to_do_index_compaction, native_columns);
     }
 
+    void _run_compressed_wiki_test(KeysType keys) {
+        const bool old_enabled = config::enable_compressed_rowid_conversion;
+        const auto old_threshold = 
config::compressed_rowid_conversion_threshold_bytes;
+        const bool old_debug = config::debug_inverted_index_compaction;
+        Defer restore {[&] {
+            config::enable_compressed_rowid_conversion = old_enabled;
+            config::compressed_rowid_conversion_threshold_bytes = 
old_threshold;
+            config::debug_inverted_index_compaction = old_debug;
+        }};
+        config::enable_compressed_rowid_conversion = true;
+        config::compressed_rowid_conversion_threshold_bytes = 0;
+        config::debug_inverted_index_compaction = false;
+        _build_wiki_tablet(keys, InvertedIndexStorageFormatPB::V2);
+        _run_normal_wiki_test(false, "", 50, keys == KeysType::UNIQUE_KEYS ? 2 
: 3, true);
+    }
+
     void _run_normal_wiki_test(bool with_delete = false, const std::string& 
delete_pred = "",
                                int64_t max_rows_per_segment = 100000,
-                               int output_rowset_segment_number = 1) {
+                               int output_rowset_segment_number = 1,
+                               bool check_compressed_mapping = false) {
         
EXPECT_TRUE(io::global_local_filesystem()->delete_directory(_tablet->tablet_path()).ok());
         
EXPECT_TRUE(io::global_local_filesystem()->create_directory(_tablet->tablet_path()).ok());
         std::string data_file1 =
@@ -630,9 +647,14 @@ protected:
             rowsets.push_back(delete_rowset);
             EXPECT_TRUE(rowsets.size() == (data_files.size() + 1));
         }
-        auto custom_check_index = [this, output_rowset_segment_number](
+        auto custom_check_index = [this, output_rowset_segment_number, 
check_compressed_mapping](
                                           const BaseCompaction& compaction,
                                           const RowsetWriterContext& ctx) {
+            if (check_compressed_mapping) {
+                ASSERT_NE(compaction._stats.rowid_conversion, nullptr);
+                EXPECT_EQ(compaction._stats.rowid_conversion->mode(),
+                          RowIdConversion::Mode::COMPRESSED);
+            }
             auto keys_type = _tablet_schema->keys_type();
             if (keys_type == KeysType::UNIQUE_KEYS) {
                 
EXPECT_EQ(compaction._cur_tablet_schema->inverted_indexes().size(),
@@ -1674,6 +1696,14 @@ TEST_F(IndexCompactionTest, 
tes_wikipedia_mow_v2_multiple_dest_segments) {
     _run_normal_wiki_test(false, "", 50, 2);
 }
 
+TEST_F(IndexCompactionTest, compressed_rowid_conversion_dup_matches_rebuild) {
+    _run_compressed_wiki_test(KeysType::DUP_KEYS);
+}
+
+TEST_F(IndexCompactionTest, compressed_rowid_conversion_mow_matches_rebuild) {
+    _run_compressed_wiki_test(KeysType::UNIQUE_KEYS);
+}
+
 TEST_F(IndexCompactionTest, tes_wikipedia_dup_v2_multiple_src_lucene_segments) 
{
     config::inverted_index_max_buffered_docs = 100;
     _build_wiki_tablet(KeysType::DUP_KEYS, InvertedIndexStorageFormatPB::V2);
diff --git 
a/be/test/storage/index/inverted/clucene/compaction/util/index_compaction_utils.h
 
b/be/test/storage/index/inverted/clucene/compaction/util/index_compaction_utils.h
index 43b8db4608c..602527e3d9f 100644
--- 
a/be/test/storage/index/inverted/clucene/compaction/util/index_compaction_utils.h
+++ 
b/be/test/storage/index/inverted/clucene/compaction/util/index_compaction_utils.h
@@ -454,11 +454,20 @@ class IndexCompactionUtils {
             
compaction._output_rs_writer->set_segment_start_id(output_segment_start_id);
         }
 
-        compaction._stats.rowid_conversion = 
compaction._rowid_conversion.get();
+        // These fixtures contain no changelog-only rowsets. Follow the 
production
+        // storage selection instead of forcing the default dense 
representation.
+        compaction._data_input_rowsets = compaction._input_rowsets;
+        compaction.prepare_rowid_conversion(ctx);
         RETURN_IF_ERROR(Merger::vertical_merge_rowsets(
                 tablet, compaction.compaction_type(), 
*(compaction._cur_tablet_schema),
                 input_rs_readers, compaction._output_rs_writer.get(), 
max_rows_per_segment - 1, 5,
                 &compaction._stats));
+        if (compaction._stats.rowid_conversion != nullptr &&
+            compaction._stats.rowid_conversion->mode() == 
RowIdConversion::Mode::COMPRESSED) {
+            std::vector<uint32_t> destination_rows;
+            
RETURN_IF_ERROR(compaction._output_rs_writer->get_segment_num_rows(&destination_rows));
+            
RETURN_IF_ERROR(compaction._stats.rowid_conversion->finalize(destination_rows));
+        }
 
         const auto& dst_writer =
                 
dynamic_cast<BaseBetaRowsetWriter*>(compaction._output_rs_writer.get());
diff --git a/be/test/storage/index/inverted/clucene/rowid_conversion_test.cpp 
b/be/test/storage/index/inverted/clucene/rowid_conversion_test.cpp
new file mode 100644
index 00000000000..dfe0b69c333
--- /dev/null
+++ b/be/test/storage/index/inverted/clucene/rowid_conversion_test.cpp
@@ -0,0 +1,230 @@
+// 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.
+#include "storage/index/inverted/clucene/rowid_conversion.h"
+
+#include <CLucene.h>
+#include <gtest/gtest.h>
+
+#include <array>
+#include <chrono>
+#include <iostream>
+#include <map>
+#include <roaring/roaring.hh>
+#include <string>
+#include <vector>
+
+#include "common/cast_set.h"
+#include "storage/rowid_conversion.h"
+
+namespace doris::segment_v2 {
+namespace {
+using namespace lucene::index;
+using namespace lucene::store;
+
+// Compaction closes its output directories. Keep RAM files available for 
checking;
+// RAMDirectory's destructor still releases them when these test objects leave 
scope.
+class RetainedRAMDirectory : public RAMDirectory {
+public:
+    void close() override {}
+};
+
+Status prepare_mapping(RowIdConversion& map, uint32_t rows, 
std::vector<uint32_t>* destinations) {
+    RowsetId rowset;
+    rowset.init(17);
+    RETURN_IF_ERROR(map.init_segment_map(rowset, {7, 42}, {rows, rows}));
+    std::vector<RowLocation> live;
+    for (uint32_t row = 0; row < rows; ++row) {
+        if (row % 13 == 0) continue;
+        for (uint32_t segment : {7, 42}) live.emplace_back(rowset, segment, 
row);
+    }
+    auto total = cast_set<uint32_t>(live.size());
+    *destinations = {total / 2, total - total / 2};
+    RETURN_IF_ERROR(map.add(live, *destinations));
+    return map.finalize(*destinations);
+}
+
+void write_source(RAMDirectory& dir, uint32_t rows) {
+    lucene::analysis::SimpleAnalyzer<char> analyzer;
+    lucene::util::SStringReader<char> body_reader;
+    lucene::util::SStringReader<char> title_reader;
+    lucene::document::Document doc;
+    const auto flags = static_cast<int32_t>(lucene::document::Field::STORE_NO) 
|
+                       
static_cast<int32_t>(lucene::document::Field::INDEX_TOKENIZED);
+    auto* body = _CLNEW lucene::document::Field(_T("body"), flags);
+    auto* title = _CLNEW lucene::document::Field(_T("title"), flags);
+    body->setOmitTermFreqAndPositions(false);
+    title->setOmitTermFreqAndPositions(false);
+    doc.add(*body);
+    doc.add(*title);
+    IndexWriter writer(&dir, &analyzer, true);
+    writer.setMaxBufferedDocs(-1);
+    writer.setRAMBufferSizeMB(512);
+    writer.setUseCompoundFile(false);
+    for (uint32_t row = 0; row < rows; ++row) {
+        const std::string text = row % 2 == 0 ? "alpha alpha omega" : "beta 
omega";
+        const std::string heading = "heading";
+        body_reader.init(text.data(), cast_set<int32_t>(text.size()), false);
+        title_reader.init(heading.data(), cast_set<int32_t>(heading.size()), 
false);
+        body->setValue(analyzer.tokenStream(body->name(), &body_reader), true);
+        title->setValue(analyzer.tokenStream(title->name(), &title_reader), 
true);
+        writer.addDocument(&doc);
+    }
+    writer.close();
+    roaring::Roaring nulls;
+    for (uint32_t row = 0; row < rows; row += 17) nulls.add(row);
+    std::vector<char> bytes(nulls.getSizeInBytes(false));
+    nulls.write(bytes.data(), false);
+    auto* output = dir.createOutput(IndexWriter::NULL_BITMAP_FILE_NAME);
+    output->writeBytes(reinterpret_cast<const uint8_t*>(bytes.data()),
+                       cast_set<int32_t>(bytes.size()));
+    output->close();
+    _CLDELETE(output);
+}
+
+struct IndexSnapshot {
+    int32_t documents;
+    std::map<std::wstring, std::vector<int32_t>> postings;
+    std::array<std::vector<uint8_t>, 2> norms;
+    std::array<uint64_t, 2> token_counts;
+    std::vector<uint32_t> nulls;
+};
+
+IndexSnapshot read_index(RAMDirectory& dir) {
+    IndexSnapshot snapshot;
+    auto* reader = IndexReader::open(&dir);
+    snapshot.documents = reader->maxDoc();
+    auto* terms = reader->terms();
+    while (terms->next()) {
+        auto* term = terms->term();
+        auto* positions = reader->termPositions(term);
+        auto& values = snapshot.postings[std::wstring(term->field()) + L":" + 
term->text()];
+        while (positions->next()) {
+            values.push_back(positions->doc());
+            const int32_t frequency = positions->freq();
+            values.push_back(frequency);
+            for (int32_t i = 0; i < frequency; ++i) 
values.push_back(positions->nextPosition());
+        }
+        positions->close();
+        _CLDELETE(positions);
+        _CLDECDELETE(term);
+    }
+    terms->close();
+    _CLDELETE(terms);
+    size_t field = 0;
+    for (const auto* name : {_T("body"), _T("title")}) {
+        const auto* norms = reader->norms(name);
+        snapshot.norms[field].assign(norms, norms + snapshot.documents);
+        snapshot.token_counts[field] = reader->sumTotalTermFreq(name).value();
+        ++field;
+    }
+    reader->close();
+    _CLDELETE(reader);
+    auto* input = static_cast<lucene::store::Directory&>(dir).openInput(
+            IndexWriter::NULL_BITMAP_FILE_NAME);
+    std::vector<uint8_t> bytes(input->length());
+    input->readBytes(bytes.data(), cast_set<int32_t>(bytes.size()));
+    auto nulls = roaring::Roaring::read(reinterpret_cast<const 
char*>(bytes.data()), false);
+    for (auto row : nulls) snapshot.nulls.push_back(row);
+    input->close();
+    _CLDELETE(input);
+    return snapshot;
+}
+} // namespace
+
+TEST(CluceneRowIdMappingTest, DenseAndCompressedSeekAcrossSourcesAndBlocks) {
+    constexpr uint32_t rows = 2 * CompressedRowIdMap::BLOCK_ROWS + 7;
+    RowIdConversion dense;
+    RowIdConversion compressed(RowIdConversion::Mode::COMPRESSED);
+    std::vector<uint32_t> destinations;
+    ASSERT_TRUE(prepare_mapping(dense, rows, &destinations).ok());
+    ASSERT_TRUE(prepare_mapping(compressed, rows, &destinations).ok());
+    CluceneRowIdMapping expected(dense);
+    CluceneRowIdMapping actual(compressed);
+    ASSERT_EQ(actual.sourceCount(), 2);
+    const std::array<uint32_t, 9> probes {4095, 4096, rows - 1, 1, 4097, 0, 
8192, 13, 2};
+    for (auto row : probes) {
+        for (uint32_t source : {0, 1}) {
+            EXPECT_EQ(actual.get(source, row), expected.get(source, row));
+        }
+    }
+    for (const auto& source : actual._sources) {
+        EXPECT_LE(source.cursor.memory_usage(), CompressedRowIdMap::BLOCK_ROWS 
* sizeof(uint64_t));
+    }
+    for (auto* mapping : {&expected, &actual}) {
+        EXPECT_THROW((void)mapping->get(2, 0), CLuceneError);
+        EXPECT_THROW((void)mapping->get(0, rows), CLuceneError);
+        EXPECT_EQ(mapping->get(0, 13), (DocIdMapping::Destination {UINT32_MAX, 
UINT32_MAX}));
+        auto start = std::chrono::steady_clock::now();
+        for (uint32_t row = 0; row < rows; ++row) {
+            for (uint32_t source : {0, 1}) (void)mapping->get(source, row);
+        }
+        auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(
+                               std::chrono::steady_clock::now() - start)
+                               .count();
+        std::cout << "CLucene row-id lookup mode="
+                  << (mapping == &expected ? "DENSE" : "COMPRESSED") << " 
rows=" << 2 * rows
+                  << " ns/lookup=" << elapsed / (2 * rows) << " (UT 
diagnostic)" << std::endl;
+    }
+}
+
+TEST(CluceneRowIdMappingTest, LookupErrorsAreNotDeletedDocuments) {
+    RowIdConversion incomplete(RowIdConversion::Mode::COMPRESSED);
+    RowsetId rowset;
+    rowset.init(19);
+    ASSERT_TRUE(incomplete.init_segment_map(rowset, {42}, {1}).ok());
+    CluceneRowIdMapping mapping(incomplete);
+    EXPECT_THROW((void)mapping.get(0, 0), CLuceneError);
+}
+
+TEST(CluceneRowIdMappingTest, CompactionMatchesDensePostingsNormsAndNulls) {
+    constexpr uint32_t rows = CompressedRowIdMap::BLOCK_ROWS + 3;
+    RetainedRAMDirectory source0;
+    RetainedRAMDirectory source1;
+    write_source(source0, rows);
+    write_source(source1, rows);
+    RowIdConversion dense;
+    RowIdConversion compressed(RowIdConversion::Mode::COMPRESSED);
+    std::vector<uint32_t> destinations;
+    ASSERT_TRUE(prepare_mapping(dense, rows, &destinations).ok());
+    ASSERT_TRUE(prepare_mapping(compressed, rows, &destinations).ok());
+    RetainedRAMDirectory dense0, dense1, compressed0, compressed1;
+    std::vector<Directory*> sources {&source0, &source1};
+    auto compact = [&](const RowIdConversion& conversion, 
std::vector<Directory*> outputs) {
+        CluceneRowIdMapping mapping(conversion);
+        lucene::analysis::SimpleAnalyzer<char> analyzer;
+        RAMDirectory scratch;
+        IndexWriter writer(&scratch, &analyzer, true);
+        writer.indexCompaction(sources, outputs, mapping, destinations);
+        writer.close();
+    };
+    compact(dense, {&dense0, &dense1});
+    compact(compressed, {&compressed0, &compressed1});
+    size_t segment = 0;
+    for (auto dirs :
+         {std::make_pair(&dense0, &compressed0), std::make_pair(&dense1, 
&compressed1)}) {
+        const auto expected = read_index(*dirs.first);
+        const auto actual = read_index(*dirs.second);
+        EXPECT_EQ(actual.documents, destinations[segment++]);
+        EXPECT_EQ(actual.documents, expected.documents);
+        EXPECT_EQ(actual.postings, expected.postings);
+        EXPECT_EQ(actual.norms, expected.norms);
+        EXPECT_EQ(actual.token_counts, expected.token_counts);
+        EXPECT_EQ(actual.nulls, expected.nulls);
+    }
+}
+
+} // namespace doris::segment_v2
diff --git a/be/test/storage/rowid_conversion_test.cpp 
b/be/test/storage/rowid_conversion_test.cpp
index 188fd064dfe..de9d220ac7c 100644
--- a/be/test/storage/rowid_conversion_test.cpp
+++ b/be/test/storage/rowid_conversion_test.cpp
@@ -608,8 +608,9 @@ TEST_F(TestRowIdConversion, 
CompressionSelectionPreservesConsumerAndOrderingCons
         ctx.snii_indexes_to_do_compaction.emplace(2, 1);
         select(ctx, true, Mode::COMPRESSED); // Duplicate Key postings also 
consume the mapping.
         ctx.columns_to_do_index_compaction.insert(2);
-        select(ctx, true, Mode::DENSE); // Any CLucene consumer requires the 
entire dense matrix.
-        ctx.columns_to_do_index_compaction.clear();
+        select(ctx, true, Mode::COMPRESSED); // CLucene borrows the same 
source mapping.
+        ctx.snii_indexes_to_do_compaction.clear();
+        select(ctx, true, Mode::COMPRESSED); // CLucene-only Duplicate Key 
compaction.
         config::debug_inverted_index_compaction = true;
         select(ctx, true, Mode::DENSE);
         config::debug_inverted_index_compaction = false;
diff --git a/contrib/clucene b/contrib/clucene
index f2864e07f08..bb3b6ef0c32 160000
--- a/contrib/clucene
+++ b/contrib/clucene
@@ -1 +1 @@
-Subproject commit f2864e07f08583b5cc948e87e82294fd0fd5de16
+Subproject commit bb3b6ef0c3216f2913efb3d5fae0604a6d365bfd


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to