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

bobhan1 pushed a commit to branch clucene
in repository https://gitbox.apache.org/repos/asf/doris-thirdparty.git


The following commit(s) were added to refs/heads/clucene by this push:
     new bb3b6ef0c32 [opt](index) Support borrowed document mappings in index 
compaction (#438)
bb3b6ef0c32 is described below

commit bb3b6ef0c3216f2913efb3d5fae0604a6d365bfd
Author: bobhan1 <[email protected]>
AuthorDate: Mon Nov 23 19:29:55 2026 +0800

    [opt](index) Support borrowed document mappings in index compaction (#438)
    
    * [opt](index) Support borrowed document mappings in index compaction
    
    ### Background
    
    Index compaction translates source document IDs into destination 
index/document pairs. Its dense matrix parameter is copied into IndexWriter, 
preventing callers from supplying bounded compressed mappings.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: apache/doris#70350 (provides the compressed row-id storage for 
the future Doris adapter)
    PR Type: Performance
    
    Problem Summary:
    
    Add a caller-owned DocIdMapping interface and an indexCompaction overload 
that borrows it during synchronous compaction. Route postings, both norms paths 
and null bitmaps through the interface without depending on Doris headers. 
Preserve the existing dense overload and setTransVec test entry through an 
owned dense adapter.
    
    ### Details
    
    - Why it was slow: Callers must expand or copy all source row pairs to use 
the old dense entry.
    - Optimization: The new entry performs fallible point lookups through the 
borrowed provider. Term changes may revisit lower source document IDs. Missing 
pairs preserve the existing UINT32_MAX sentinel, and lookup errors propagate as 
CLuceneError. The borrowed pointer is reset on success and exception. RAII owns 
queued/active iterators, destination writers and segment metadata, and 
norms/null outputs are closed in the existing finally block when a lookup 
fails. Diagnostic source locati [...]
    - Results: Independent ASAN IndexCompaction tests pass 9/9 with leak 
detection enabled. New tests compare postings/positions, norm bytes, token 
totals and null row IDs to the dense entry and cover rewinds, diagnostic output 
and injected lookup failures in norms, postings and null-only remapping. These 
tests are correctness checks, not throughput measurements.
    - Applicability and cost: One virtual lookup per translated source 
document. Mapping representation, lookup cache and its lifetime belong to the 
caller. The old dense entry retains its ownership/copying behavior for source 
compatibility; clients adopt the new overload to avoid that copy. IndexWriter 
layout changes require clients to rebuild.
    
    ### Testing
    
    Standalone CMake ASAN build with Clang 20.1.8; cmake --build 
/tmp/clucene-rowid-20261119-build --target cl_test --parallel 100. Running 
bin/cl_test -t IndexCompaction passes 9/9, including the seven existing tests. 
All three mapping-failure phases exposed leaks before the ownership fix and 
pass with it. No ASAN/LSAN suppressions were added. Doris adapter integration 
is being validated locally before submitting this PR.
    
    ### Release note
    
    Index compaction can borrow a document-ID mapping provider without 
requiring a dense matrix.
    
    ### Check List (For Author)
    
    - Behavior changed: No for the legacy dense entry; the new provider 
overload is additive.
    - Does this need documentation: No; interface ownership and lookup 
semantics are documented in the header.
    - Pre-submission status: Partially verified: standalone tests pass; 
coordinated Doris validation is pending.
    
    ### AI Disclosure
    
    - Tool: OpenAI Codex
    - Generated: Implementation, tests and description.
    - Human review: Pending.
    
    * [opt](index) Borrow dense compaction mappings without copying rows
    
    ### Background
    
    Index compaction performs synchronous source-to-destination lookups. The 
provider overload borrows its mapping, but the legacy dense overload still 
copies the full row matrix before building an owned adapter.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #438
    PR Type: Performance
    
    Problem Summary:
    
    Borrow the dense matrix through a const reference and a stack adapter, then 
delegate to the existing provider overload. Both entries now reset the writer's 
borrowed pointer on normal return and exception. The dense caller only needs to 
retain its rows until the synchronous call returns.
    
    ### Details
    
    - Why it was slow: Passing a dense matrix by value duplicates an 8-byte 
pair per source row. Keeping the duplicate is unnecessary because all map reads 
finish inside indexCompaction.
    - Optimization: The dense adapter stores a reference. Production calls 
allocate neither another matrix nor a heap adapter. The test-only setter owns a 
small borrowed view and rejects temporary vectors so its subsequent helper 
calls cannot use an already-destroyed temporary.
    - Results: The new borrowing regression fails on the previous 
implementation and passes after the change. The independent ASAN/LSAN selection 
passes 21/21 tests. No new Release throughput or large-compaction measurement 
is claimed.
    - Applicability and cost: Applies to the legacy dense API, including 
tool/test callers. The provider API and on-disk results are unchanged. The 
dense function signature changes and clients must rebuild; ordinary synchronous 
call sites remain source-compatible. A vector supplied to the test-only setter 
must survive its helper lookups.
    
    ### Testing
    
    Rebuilt cl_test with the existing Clang 20.1.8 ASAN configuration and ran 
./cl_test -v -p IndexCompaction IndexCompress IndexCompressV3 
testBlockMaxScoreV3: 21/21 passed, including new dense aliasing and lifetime 
cases. Scoped lvalue and temporary mappings are destroyed before writer.close() 
on both normal and exception paths. Dense/provider equivalence and injected 
lookup-error cleanup remain covered. Whitespace checks pass; Doris integration 
validation follows on the coordinated branch.
    
    ### Release note
    
    Dense index compaction no longer copies the complete document-ID 
translation matrix.
    
    ### Check List (For Author)
    
    - Behavior changed: No
    - Does this need documentation: No; the borrowed lifetime is stated next to 
the API.
    - Pre-submission status: Partially verified: native tests pass; the 
coordinated Doris build is pending.
    
    ### AI Disclosure
    
    - Tool: OpenAI Codex (GPT-6)
    - Generated: Implementation, tests and description.
    - Human review: Pending.
    
    * [refactor](index) Keep compaction test mappings caller-owned
    
    * [refactor](index) Reuse finally cleanup for borrowed mapping
---
 src/core/CLucene/index/DocIdMapping.h  |  40 ++++++
 src/core/CLucene/index/IndexWriter.cpp | 185 +++++++++++++-----------
 src/core/CLucene/index/IndexWriter.h   |  28 ++--
 src/test/index/TestIndexCompaction.cpp | 248 ++++++++++++++++++++++++++++++++-
 4 files changed, 403 insertions(+), 98 deletions(-)

diff --git a/src/core/CLucene/index/DocIdMapping.h 
b/src/core/CLucene/index/DocIdMapping.h
new file mode 100644
index 00000000000..5d8d52ffbab
--- /dev/null
+++ b/src/core/CLucene/index/DocIdMapping.h
@@ -0,0 +1,40 @@
+// 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
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <utility>
+
+#include "CLucene/SharedHeader.h"
+
+CL_NS_DEF(index)
+
+// Borrowed by IndexWriter for synchronous compaction. Sources/destinations are
+// directory positions, not physical segment IDs. Terms may revisit lower doc 
IDs.
+class CLUCENE_EXPORT DocIdMapping {
+public:
+    using Destination = std::pair<uint32_t, uint32_t>;
+    virtual ~DocIdMapping() = default;
+    virtual size_t sourceCount() const = 0;
+    // UINT32_MAX in both fields means deleted. Lookup failures must throw
+    // CLuceneError; treating a failure as a deleted document loses index 
entries.
+    virtual Destination get(uint32_t source, uint32_t doc) const = 0;
+};
+
+CL_NS_END
diff --git a/src/core/CLucene/index/IndexWriter.cpp 
b/src/core/CLucene/index/IndexWriter.cpp
index 8f9e950331a..1d7210db619 100644
--- a/src/core/CLucene/index/IndexWriter.cpp
+++ b/src/core/CLucene/index/IndexWriter.cpp
@@ -114,7 +114,6 @@ void IndexWriter::deinit(bool releaseWriteLock) throw() {
 IndexWriter::~IndexWriter() {
     deinit();
 
-    _trans_vec.clear();
     readers.clear();
     if (fieldInfos != nullptr) {
         _CLDELETE(fieldInfos);
@@ -1209,13 +1208,53 @@ void IndexWriter::resetMergeExceptions() {
     mergeGen++;
 }
 
-void IndexWriter::indexCompaction(std::vector<lucene::store::Directory *> 
&src_dirs,
-                                  std::vector<lucene::store::Directory *> 
dest_dirs,
-                                  std::vector<std::vector<std::pair<uint32_t, 
uint32_t>>> trans_vec,
+namespace {
+struct CompactionDeleter {
+    template <typename T>
+    void operator()(T* value) const {
+        _CLDELETE(value);
+    }
+};
+
+class DenseDocIdMapping final : public DocIdMapping {
+public:
+    explicit DenseDocIdMapping(const std::vector<std::vector<Destination>>& 
values)
+            : _values(values) {}
+    size_t sourceCount() const override { return _values.size(); }
+    Destination get(uint32_t source, uint32_t doc) const override { return 
_values[source][doc]; }
+
+private:
+    const std::vector<std::vector<Destination>>& _values;
+};
+} // namespace
+
+void IndexWriter::indexCompaction(
+        std::vector<lucene::store::Directory*>& src_dirs,
+        std::vector<lucene::store::Directory*> dest_dirs,
+        const std::vector<std::vector<std::pair<uint32_t, uint32_t>>>& 
trans_vec,
+        std::vector<uint32_t> dest_index_docs) {
+    DenseDocIdMapping mapping(trans_vec);
+    indexCompaction(src_dirs, std::move(dest_dirs), mapping, 
std::move(dest_index_docs));
+}
+
+void IndexWriter::indexCompaction(std::vector<lucene::store::Directory*>& 
src_dirs,
+                                  std::vector<lucene::store::Directory*> 
dest_dirs,
+                                  const DocIdMapping& mapping,
                                   std::vector<uint32_t> dest_index_docs) {
+    _docIdMapping = &mapping;
+    try {
+        indexCompactionImpl(src_dirs, dest_dirs, dest_index_docs);
+    }
+    _CLFINALLY(_docIdMapping = nullptr;);
+}
+
+void IndexWriter::indexCompactionImpl(std::vector<lucene::store::Directory*>& 
src_dirs,
+                                      const 
std::vector<lucene::store::Directory*>& dest_dirs,
+                                      const std::vector<uint32_t>& 
dest_index_docs) {
     CND_CONDITION(src_dirs.size() > 0, "Source directory not found.");
     CND_CONDITION(dest_dirs.size() > 0, "Destination directory not found.");
-    this->_trans_vec = std::move(trans_vec);
+    CND_CONDITION(src_dirs.size() == _docIdMapping->sourceCount(),
+                  "Document mapping source count differs from source 
directories.");
 
     // create segment readers
     int numIndices = src_dirs.size();
@@ -1272,12 +1311,11 @@ void 
IndexWriter::indexCompaction(std::vector<lucene::store::Directory *> &src_d
     }
 
     // init new segment infos
-    std::vector<SegmentInfo *> newSegmentInfos;
-    SegmentInfo *newSegment = nullptr;
+    std::vector<std::unique_ptr<SegmentInfo, CompactionDeleter>> 
newSegmentInfos;
     std::string docStoreSegment;
     docStoreSegment.clear();
 
-    std::vector<lucene::index::IndexWriter *> destIndexWriterList;
+    std::vector<std::unique_ptr<IndexWriter, CompactionDeleter>> 
destIndexWriterList;
     std::vector<lucene::store::IndexOutput *> nullBitmapIndexOutputList;
     std::vector<lucene::store::IndexOutput *> normsOutputList;
 
@@ -1338,7 +1376,7 @@ void 
IndexWriter::indexCompaction(std::vector<lucene::store::Directory *> &src_d
             }
         }
 
-        // Build destFieldNormsMapValues from srcFieldNormsMapValues using 
_trans_vec
+        // Build destFieldNormsMapValues from srcFieldNormsMapValues using the 
document mapping
         std::vector<std::map<std::wstring, std::vector<uint8_t>>> 
destFieldNormsMapValues(
                 numDestIndexes);
         if (hasNorms) {
@@ -1373,7 +1411,7 @@ void 
IndexWriter::indexCompaction(std::vector<lucene::store::Directory *> &src_d
             for (int srcIdx = 0; srcIdx < numIndices; srcIdx++) {
                 for (const auto& [fieldName, srcNorms] : 
srcFieldNormsMapValues[srcIdx]) {
                     for (size_t srcDocId = 0; srcDocId < srcNorms.size(); 
srcDocId++) {
-                        auto [destIdx, destDocId] = 
_trans_vec[srcIdx][srcDocId];
+                        auto [destIdx, destDocId] = _docIdMapping->get(srcIdx, 
srcDocId);
                         if (destIdx != UINT32_MAX && destDocId != UINT32_MAX) {
                             
destFieldNormsMapValues[destIdx][fieldName][destDocId] =
                                     srcNorms[srcDocId];
@@ -1387,17 +1425,18 @@ void 
IndexWriter::indexCompaction(std::vector<lucene::store::Directory *> &src_d
         for (int j = 0; j < numDestIndexes; j++) {
             auto dest_dir = dest_dirs[j];
             /// create dest index writers
-            auto index_writer = _CLNEW IndexWriter(dest_dir, analyzer, true, 
true);
-            destIndexWriterList.push_back(index_writer);
+            std::unique_ptr<IndexWriter, CompactionDeleter> writer(
+                    _CLNEW IndexWriter(dest_dir, analyzer, true, true));
+            auto* index_writer = writer.get();
+            destIndexWriterList.push_back(std::move(writer));
 
             std::string segment = index_writer->newSegmentName();
             // create segment info
-            newSegment = _CLNEW SegmentInfo(segment.c_str(),
-                                            (int) dest_index_docs[j],
-                                            dest_dir, false, true,
-                                            0, docStoreSegment.c_str(),
-                                            false);
-            newSegmentInfos.push_back(newSegment);
+            std::unique_ptr<SegmentInfo, CompactionDeleter> new_segment(
+                    _CLNEW SegmentInfo(segment.c_str(), 
(int)dest_index_docs[j], dest_dir, false,
+                                       true, 0, docStoreSegment.c_str(), 
false));
+            auto* newSegment = new_segment.get();
+            newSegmentInfos.push_back(std::move(new_segment));
 
             /// write fields
             writeFields(dest_dir, segment);
@@ -1480,30 +1519,31 @@ void 
IndexWriter::indexCompaction(std::vector<lucene::store::Directory *> &src_d
                     r->close();
                     _CLDELETE(r);
                 }
-                 } readers.clear(););
+            } readers.clear();
             for (auto* norms_out
                  : normsOutputList) {
                 if (norms_out != nullptr) {
                     norms_out->close();
                     _CLDELETE(norms_out);
                 }
-         } normsOutputList.clear();
+            } normsOutputList.clear();
             for (auto* null_bitmap_out
                  : nullBitmapIndexOutputList) {
                 if (null_bitmap_out != nullptr) {
                     null_bitmap_out->close();
                     _CLDELETE(null_bitmap_out);
                 }
-            } nullBitmapIndexOutputList.clear();
+            } nullBitmapIndexOutputList.clear(););
 
     // update segment infos of dest index_writer in memory
     // close dest index writer
     for (int i = 0; i < numDestIndexes; i++) {
-        auto index_writer = destIndexWriterList[i];
-        index_writer->getSegmentInfos()->setElementAt(newSegmentInfos[i], 0);
+        auto* index_writer = destIndexWriterList[i].get();
+        
index_writer->getSegmentInfos()->setElementAt(newSegmentInfos[i].get(), 0);
+        newSegmentInfos[i].release();
         // close
         index_writer->close();
-        _CLDELETE(index_writer);
+        destIndexWriterList[i].reset();
     }
     destIndexWriterList.clear();
 
@@ -1676,7 +1716,11 @@ protected:
 void IndexWriter::mergeTerms(bool hasProx, bool hasNorms, IndexVersion 
indexVersion,
         const std::vector<std::map<std::wstring, std::vector<uint8_t>>>& 
destFieldNormsMapValues,
         std::vector<std::map<std::wstring, uint64_t>>& destFieldTokenCounts) {
-    auto queue = _CLNEW SegmentMergeQueue(readers.size());
+    // Mapping failures can unwind from any posting. Keep queued and active
+    // source iterators owned until they are explicitly transferred back.
+    std::unique_ptr<SegmentMergeQueue, CompactionDeleter> queue(
+            _CLNEW SegmentMergeQueue(readers.size()));
+    using SourcePtr = std::unique_ptr<SegmentMergeInfo, CompactionDeleter>;
     auto numSrcIndexes = readers.size();
     //std::vector<TermPositions *> postingsList(numSrcIndexes);
 
@@ -1688,23 +1732,21 @@ void IndexWriter::mergeTerms(bool hasProx, bool 
hasNorms, IndexVersion indexVers
     for (int i = 0; i < numSrcIndexes; ++i) {
         reader = readers[i];
 
-        TermEnum *termEnum = reader->terms();
-        smi = _CLNEW SegmentMergeInfo(base, termEnum, reader, i);
-
+        std::unique_ptr<TermEnum, CompactionDeleter> terms(reader->terms());
+        SourcePtr source(_CLNEW SegmentMergeInfo(base, terms.get(), reader, 
i));
+        terms.release();
         base += reader->numDocs();
-        if (smi->next()) {
-            queue->put(smi);
-        } else {
-            smi->close();
-            _CLDELETE(smi);
+        if (source->next()) {
+            queue->put(source.get());
+            source.release();
         }
     }
-    auto **match = _CL_NEWARRAY(SegmentMergeInfo *, readers.size());
+    std::vector<SourcePtr> match(readers.size());
 
     while (queue->size() > 0) {
         int32_t matchSize = 0;
 
-        match[matchSize++] = queue->pop();
+        match[matchSize++].reset(queue->pop());
         Term *smallestTerm = match[0]->term;
         SegmentMergeInfo *top = queue->top();
         if (infoStream != nullptr) {
@@ -1722,20 +1764,21 @@ void IndexWriter::mergeTerms(bool hasProx, bool 
hasNorms, IndexVersion indexVers
             }
         }
         while (top != nullptr && smallestTerm->equals(top->term)) {
-            match[matchSize++] = queue->pop();
+            match[matchSize++].reset(queue->pop());
             top = queue->top();
         }
 
         std::vector<std::vector<uint32_t>> docDeltaBuffers(numDestIndexes);
         std::vector<std::vector<uint32_t>> freqBuffers(numDestIndexes);
         std::vector<std::vector<uint32_t>> posBuffers(numDestIndexes);
-        auto destPostingQueues = _CLNEW postingQueue(matchSize);
         std::vector<DestDoc> destDocs(matchSize);
+        std::unique_ptr<postingQueue, CompactionDeleter> destPostingQueues(
+                _CLNEW postingQueue(matchSize));
 
         auto processPostings = [&](TermPositions* postings, DestDoc* destDoc, 
int srcIdx) {
             while (postings->next()) {
                 int srcDoc = postings->doc();
-                std::pair<int32_t, uint32_t> p = 
_trans_vec[smi->readerIndex][srcDoc];
+                auto p = _docIdMapping->get(smi->readerIndex, srcDoc);
                 destDoc->destIdx = p.first;
                 destDoc->destDocId = p.second;
                 destDoc->srcIdx = srcIdx;
@@ -1768,7 +1811,7 @@ void IndexWriter::mergeTerms(bool hasProx, bool hasNorms, 
IndexVersion indexVers
         };
 
         for (int i = 0; i < matchSize; ++i) {
-            smi = match[i];
+            smi = match[i].get();
             auto* postings = smi->getPositions();
             postings->seek(smi->termEnum);
             processPostings(postings, &destDocs[i], i);
@@ -1792,23 +1835,15 @@ void IndexWriter::mergeTerms(bool hasProx, bool 
hasNorms, IndexVersion indexVers
                     termTokenCounts[destIdx] += destFreq;
                 }
                 if (infoStream != nullptr) {
-                    for (int i = 0; i < _trans_vec.size(); ++i) {
-                        // find pair < destIdx, destDocId > in _trans_vec[i] 
to get the index of the pair
-                        auto it = std::find_if(_trans_vec[i].begin(), 
_trans_vec[i].end(),
-                                               [destIdx, destDocId](const 
std::pair<uint32_t, uint32_t>& pair) {
-                                                   return pair.first == 
destIdx && pair.second == destDocId;
-                                               });
-
-                        // Check if the pair was found
-                        if (it != _trans_vec[i].end()) {
-                            // Calculate the index of the pair
-                            size_t index = 
std::distance(_trans_vec[i].begin(), it);
-                            std::stringstream ss;
-                            ss << "Found pair at srcIdxId:" << i << ", 
srcDocId: " << index << ", destIdxId: " << destIdx
-                               << ", destDocId: " << destDocId << ", destFreq: 
" << destDoc->destFreq;
-                            message(ss.str());
-                        }
-                    }
+                    // The queued posting already identifies its source. Avoid 
a
+                    // full reverse scan of the mapping just to print a debug 
line.
+                    auto* source = match[destDoc->srcIdx].get();
+                    std::stringstream ss;
+                    ss << "Found pair at srcIdxId:" << source->readerIndex
+                       << ", srcDocId: " << source->getPositions()->doc()
+                       << ", destIdxId: " << destIdx << ", destDocId: " << 
destDocId
+                       << ", destFreq: " << destDoc->destFreq;
+                    message(ss.str());
                 }
 
                 auto freqOut = freqOutputList[destIdx];
@@ -1882,15 +1917,12 @@ void IndexWriter::mergeTerms(bool hasProx, bool 
hasNorms, IndexVersion indexVers
                     freqBuffer.push_back(destFreq);
                 }
 
-                smi = match[destDoc->srcIdx];
+                smi = match[destDoc->srcIdx].get();
                 processPostings(smi->getPositions(), destDoc, destDoc->srcIdx);
             }
         }
-        if (destPostingQueues != nullptr) {
-            destPostingQueues->close();
-            _CLDELETE(destPostingQueues);
-        }
-        
+        destPostingQueues.reset();
+
         if (infoStream != nullptr) {
             std::stringstream ss;
             for (const auto& df : dfs) {
@@ -1966,27 +1998,16 @@ void IndexWriter::mergeTerms(bool hasProx, bool 
hasNorms, IndexVersion indexVers
         }
 
         while (matchSize > 0) {
-            smi = match[--matchSize];
-
-            // Move to the next term in the enumeration of SegmentMergeInfo smi
-            if (smi->next()) {
-                // There still are some terms so restore smi in the queue
-                queue->put(smi);
-
+            auto& source = match[matchSize - 1];
+            if (source->next()) {
+                queue->put(source.get());
+                source.release();
             } else {
-                // Done with a segment
-                // No terms anymore so close this SegmentMergeInfo instance
-                smi->close();
-                _CLDELETE(smi);
+                source.reset();
             }
+            --matchSize;
         }
     }
-
-    _CLDELETE_ARRAY(match);
-    if (queue != NULL) {
-        queue->close();
-        _CLDELETE(queue);
-    }
 }
 
 void IndexWriter::mergeNorms(std::vector<uint32_t> dest_index_docs,
@@ -2016,8 +2037,7 @@ void IndexWriter::mergeNorms(std::vector<uint32_t> 
dest_index_docs,
                 auto& srcFieldNorms = srcFieldNormsMap[fieldName];
                 // construct srcFieldNorms to destFieldNorms
                 for (int srcDocId = 0; srcDocId < srcFieldNorms.size(); 
srcDocId++) {
-                    auto destIdx = _trans_vec[srcIndex][srcDocId].first;
-                    auto destDocId = _trans_vec[srcIndex][srcDocId].second;
+                    auto [destIdx, destDocId] = _docIdMapping->get(srcIndex, 
srcDocId);
                     if (destIdx == UINT32_MAX || destDocId == UINT32_MAX) {
                         continue;
                     }
@@ -2070,8 +2090,7 @@ void 
IndexWriter::mergeNullBitmap(std::vector<std::vector<uint32_t>> srcNullBitm
             continue;
         }
         for (const auto& srcDocId : indexSrcBitmapValues) {
-            auto destIdx = _trans_vec[i][srcDocId].first;
-            auto destDocId = _trans_vec[i][srcDocId].second;
+            auto [destIdx, destDocId] = _docIdMapping->get(i, srcDocId);
             // <UINT32_MAX, UINT32_MAX> indicates current row not exist in 
Doris dest segment.
             // So we ignore this doc here.
             if (destIdx == UINT32_MAX || destDocId == UINT32_MAX) {
diff --git a/src/core/CLucene/index/IndexWriter.h 
b/src/core/CLucene/index/IndexWriter.h
index 56a9d7157d9..41ff61f6838 100644
--- a/src/core/CLucene/index/IndexWriter.h
+++ b/src/core/CLucene/index/IndexWriter.h
@@ -8,9 +8,10 @@
 #define _lucene_index_IndexWriter_
 
 #include "CLucene/clucene-config.h"
+#include "CLucene/index/DocIdMapping.h"
 #include "CLucene/index/IndexVersion.h"
-#include "CLucene/util/VoidList.h"
 #include "CLucene/util/Array.h"
+#include "CLucene/util/VoidList.h"
 
 CL_CLASS_DEF(search,Similarity)
 CL_CLASS_DEF(store,Lock)
@@ -282,7 +283,7 @@ class CLUCENE_EXPORT IndexWriter:LUCENE_BASE {
   mutable bool hitOOM;
 
   // index compaction params
-  std::vector<std::vector<std::pair<uint32_t, uint32_t>>> _trans_vec;
+  const DocIdMapping* _docIdMapping = nullptr;
   // dest indexes numbers
   int32_t numDestIndexes;
   std::vector<IndexReader*> readers;
@@ -308,7 +309,7 @@ public:
      * Compact src indices to dest indices, depend on doc id translation vector
      * @param src_dirs source indices directories to read data
      * @param dest_dirs destination indices directories to write new indices
-     * @param trans_vec translation vector
+     * @param trans_vec translation vector, borrowed until this synchronous 
call returns
      * the first level vector:
      *     index indicates index of source index, which is same order of 
src_dirs
      * the second level vector:
@@ -320,9 +321,21 @@ public:
      */
     void indexCompaction(std::vector<lucene::store::Directory*>& src_dirs,
                             std::vector<lucene::store::Directory*> dest_dirs,
-                            std::vector<std::vector<std::pair<uint32_t, 
uint32_t>>> trans_vec,
+                            const std::vector<std::vector<std::pair<uint32_t, 
uint32_t>>>& trans_vec,
                             std::vector<uint32_t> dest_index_docs);
 
+    // The mapping is borrowed and must outlive this synchronous call. No dense
+    // matrix is materialized or copied by this overload.
+    void indexCompaction(std::vector<lucene::store::Directory*>& src_dirs,
+                         std::vector<lucene::store::Directory*> dest_dirs,
+                         const DocIdMapping& mapping, std::vector<uint32_t> 
dest_index_docs);
+
+private:
+    void indexCompactionImpl(std::vector<lucene::store::Directory*>& src_dirs,
+                             const std::vector<lucene::store::Directory*>& 
dest_dirs,
+                             const std::vector<uint32_t>& dest_index_docs);
+
+public:
     // create new fields info
     void mergeFields(bool hasProx, IndexVersion indexVersion);
     // write fields info file
@@ -347,10 +360,9 @@ public:
     void setNumDestIndexes(int32_t num_dest_indexes) {
         numDestIndexes = num_dest_indexes;
     }
-    // only for tests
-    void setTransVec(std::vector<std::vector<std::pair<uint32_t, uint32_t>>> 
trans_vec) {
-      _trans_vec = std::move(trans_vec);
-    }
+    // Only for tests. The caller owns mapping through subsequent helper 
lookups.
+    void setDocIdMapping(const DocIdMapping& mapping) { _docIdMapping = 
&mapping; }
+    void setDocIdMapping(const DocIdMapping&&) = delete;
 
        // Release the write lock, if needed.
        SegmentInfos* segmentInfos;
diff --git a/src/test/index/TestIndexCompaction.cpp 
b/src/test/index/TestIndexCompaction.cpp
index 18e7ff2f4ee..637ccf07869 100644
--- a/src/test/index/TestIndexCompaction.cpp
+++ b/src/test/index/TestIndexCompaction.cpp
@@ -15,18 +15,47 @@
 // specific language governing permissions and limitations
 // under the License
 
+#include <algorithm>
 #include <cstdint>
 #include <iostream>
+#include <sstream>
 #include <utility>
 #include <vector>
-#include "CLucene/debug/mem.h"
-#include "test.h"
-#include "store/MockRAMDirectory.h"
+
+#include "CLucene.h"
 #include "CLucene/debug/error.h"
+#include "CLucene/debug/mem.h"
 #include "CLucene/index/IndexWriter.h"
 #include "CLucene/store/IndexInput.h"
 #include "CLucene/store/IndexOutput.h"
 #include "roaring/roaring.hh"
+#include "store/MockRAMDirectory.h"
+#include "test.h"
+
+namespace {
+using DenseMapping = std::vector<std::vector<DocIdMapping::Destination>>;
+
+class BorrowedTestMapping final : public DocIdMapping {
+public:
+    explicit BorrowedTestMapping(const DenseMapping& values, bool fail = false)
+            : values_(values), last_(values.size(), UINT32_MAX), fail_(fail) {}
+    size_t sourceCount() const override { return values_.size(); }
+    Destination get(uint32_t source, uint32_t doc) const override {
+        if (fail_) _CLTHROWA(CL_ERR_IO, "injected document mapping failure");
+        if (last_[source] != UINT32_MAX && doc < last_[source]) revisited = 
true;
+        last_[source] = doc;
+        ++lookups;
+        return values_[source][doc];
+    }
+    mutable size_t lookups = 0;
+    mutable bool revisited = false;
+
+private:
+    const DenseMapping& values_;
+    mutable std::vector<uint32_t> last_;
+    bool fail_;
+};
+} // namespace
 
 void _setupSourceNullBitmapValues(std::vector<std::vector<uint32_t>> 
&srcNullBitmapValues) {
     srcNullBitmapValues.push_back(std::vector<uint32_t>{1, 2, 3});
@@ -119,9 +148,10 @@ void TestMergeNullBitmapWriteNullBitmap(CuTest *tc) {
     nullBitmapIndexOutputList.push_back(dest_output_index1);
     nullBitmapIndexOutputList.push_back(dest_output_index2);
 
+    BorrowedTestMapping mapping(trans_vec);
     try {
         index_writer->setNumDestIndexes(2);
-        index_writer->setTransVec(trans_vec);
+        index_writer->setDocIdMapping(mapping);
         index_writer->mergeNullBitmap(srcNullBitmapValues, 
nullBitmapIndexOutputList);
     } catch (const std::exception& ex) {
         std::cout << "Caught exception: " << ex.what() << std::endl;
@@ -173,9 +203,10 @@ void TestMergeNullBitmapEmptySrc(CuTest *tc) {
     nullBitmapIndexOutputList.push_back(dest_output_index1);
     nullBitmapIndexOutputList.push_back(dest_output_index2);
 
+    BorrowedTestMapping mapping(trans_vec);
     try {
         index_writer->setNumDestIndexes(2);
-        index_writer->setTransVec(trans_vec);
+        index_writer->setDocIdMapping(mapping);
         index_writer->mergeNullBitmap(srcNullBitmapValues, 
nullBitmapIndexOutputList);
     } catch (const std::exception& ex) {
         std::cout << "Caught exception: " << ex.what() << std::endl;
@@ -231,9 +262,10 @@ void TestMergeNullBitmapEmptyIndexSrcBitmapValues(CuTest 
*tc) {
     nullBitmapIndexOutputList.push_back(dest_output_index1);
     nullBitmapIndexOutputList.push_back(dest_output_index2);
 
+    BorrowedTestMapping mapping(trans_vec);
     try {
         index_writer->setNumDestIndexes(2);
-        index_writer->setTransVec(trans_vec);
+        index_writer->setDocIdMapping(mapping);
         index_writer->mergeNullBitmap(srcNullBitmapValues, 
nullBitmapIndexOutputList);
     } catch (const std::exception& ex) {
         std::cout << "Caught exception: " << ex.what() << std::endl;
@@ -295,9 +327,10 @@ void TestMergeNullBitmapIgnoreDoc(CuTest *tc) {
     nullBitmapIndexOutputList.push_back(dest_output_index1);
     nullBitmapIndexOutputList.push_back(dest_output_index2);
 
+    BorrowedTestMapping mapping(trans_vec);
     try {
         index_writer->setNumDestIndexes(2);
-        index_writer->setTransVec(trans_vec);
+        index_writer->setDocIdMapping(mapping);
         index_writer->mergeNullBitmap(srcNullBitmapValues, 
nullBitmapIndexOutputList);
     } catch (const std::exception& ex) {
         std::cout << "Caught exception: " << ex.what() << std::endl;
@@ -478,6 +511,203 @@ void TestCompactionWithoutFrequencies(CuTest* tc) {
     }
 }
 
+namespace {
+using PostingSnapshot = std::map<std::wstring, std::vector<int32_t>>;
+PostingSnapshot readPostings(IndexReader* reader) {
+    PostingSnapshot result;
+    auto* terms = reader->terms();
+    while (terms->next()) {
+        auto* term = terms->term();
+        auto* postings = reader->termPositions(term);
+        auto& values = result[std::wstring(term->field()) + L":" + 
term->text()];
+        while (postings->next()) {
+            values.push_back(postings->doc());
+            const int32_t freq = postings->freq();
+            values.push_back(freq);
+            for (int32_t i = 0; i < freq; ++i) 
values.push_back(postings->nextPosition());
+        }
+        postings->close();
+        _CLDELETE(postings);
+        _CLDECDELETE(term);
+    }
+    terms->close();
+    _CLDELETE(terms);
+    return result;
+}
+
+void writeNulls(RAMDirectory& dir, std::initializer_list<uint32_t> rows) {
+    roaring::Roaring bitmap;
+    for (auto row : rows) bitmap.add(row);
+    std::vector<char> bytes(bitmap.getSizeInBytes(false));
+    bitmap.write(bytes.data(), false);
+    auto* output = dir.createOutput(IndexWriter::NULL_BITMAP_FILE_NAME);
+    output->writeBytes(reinterpret_cast<const uint8_t*>(bytes.data()), 
bytes.size());
+    output->close();
+    _CLDELETE(output);
+}
+
+roaring::Roaring readNulls(RAMDirectory& dir) {
+    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(), bytes.size());
+    auto bitmap = roaring::Roaring::read(reinterpret_cast<const 
char*>(bytes.data()), false);
+    input->close();
+    _CLDELETE(input);
+    return bitmap;
+}
+} // namespace
+
+void TestHelperBorrowsMapping(CuTest* tc) {
+    RAMDirectory scratch;
+    RAMDirectory destination;
+    lucene::analysis::SimpleAnalyzer<char> analyzer;
+    DenseMapping values {{{0, 0}}};
+    BorrowedTestMapping mapping(values);
+    IndexWriter writer(&scratch, &analyzer, true);
+    writer.setNumDestIndexes(1);
+    writer.setDocIdMapping(mapping);
+    // Changing the caller's storage before a lookup must be visible through 
the view.
+    values[0][0] = {0, 1};
+    auto* output = 
destination.createOutput(IndexWriter::NULL_BITMAP_FILE_NAME);
+    writer.mergeNullBitmap({{0}}, {output});
+    output->close();
+    _CLDELETE(output);
+    writer.close();
+    const auto nulls = readNulls(destination);
+    CuAssert(tc, _T("helper uses the caller-owned mapping"), mapping.lookups 
== 1);
+    CuAssert(tc, _T("mapping borrows the caller's rows"),
+             nulls.cardinality() == 1 && nulls.contains(1));
+}
+
+void TestDenseCompactionMappingLifetime(CuTest* tc) {
+    // Requiring this signature also catches an accidental return to 
pass-by-value.
+    using DenseCompaction = void 
(IndexWriter::*)(std::vector<lucene::store::Directory*>&,
+                                                  
std::vector<lucene::store::Directory*>,
+                                                  const DenseMapping&, 
std::vector<uint32_t>);
+    const auto compact = 
static_cast<DenseCompaction>(&IndexWriter::indexCompaction);
+    for (bool frequencies : {false, true}) {
+        for (bool temporary : {false, true}) {
+            RAMDirectory source;
+            writeNormsIndex(source, {{"alpha alpha", "title"}}, true, 
frequencies);
+            writeNulls(source, {0});
+            MockRAMDirectory destination;
+            destination.setRandomIOExceptionRate(0.0, 0);
+            RAMDirectory scratch;
+            lucene::analysis::SimpleAnalyzer<char> analyzer;
+            IndexWriter writer(&scratch, &analyzer, true);
+            std::vector<lucene::store::Directory*> sources {&source};
+            bool rejected = false;
+            try {
+                if (temporary) {
+                    (writer.*compact)(sources, {&destination}, DenseMapping 
{{{0, 0}}}, {1});
+                } else {
+                    DenseMapping values {{{0, 0}}};
+                    (writer.*compact)(sources, {&destination}, values, {1});
+                }
+            } catch (CLuceneError& error) {
+                CuAssertIntEquals(tc, _T("unsupported norms retain their 
error"),
+                                  CL_ERR_UnsupportedOperation, error.number());
+                rejected = true;
+            }
+            // Both temporary and scoped lvalue rows are gone before 
close/destruction.
+            // ASAN checks that neither successful nor failed compaction 
retains them.
+            writer.close();
+            CuAssertIntEquals(tc, _T("norms need frequencies"), !frequencies, 
rejected);
+            if (!rejected) {
+                auto* reader = IndexReader::open(&destination);
+                const auto tokens = reader->sumTotalTermFreq(_T("body"));
+                const auto postings = readPostings(reader);
+                reader->close();
+                _CLDELETE(reader);
+                CuAssert(tc, _T("dense compaction preserves tokens"), tokens 
== 2);
+                CuAssert(tc, _T("dense compaction preserves positions"),
+                         postings.at(L"body:alpha") == 
std::vector<int32_t>({0, 2, 0, 1}));
+                CuAssert(tc, _T("dense compaction preserves null rows"),
+                         readNulls(destination).contains(0));
+            }
+        }
+    }
+}
+
+void TestBorrowedCompactionMapping(CuTest* tc) {
+    RAMDirectory source0;
+    RAMDirectory source1;
+    writeNormsIndex(source0, {{"alpha alpha", "one"}, {"deleted", "gone"}, 
{"omega", "two"}});
+    writeNormsIndex(source1,
+                    {{"alpha omega", "one two"}, {"omega omega", "three"}, 
{"deleted", "gone"}});
+    writeNulls(source0, {0, 1, 2});
+    writeNulls(source1, {1, 2});
+    DenseMapping values {{{0, 0}, {UINT32_MAX, UINT32_MAX}, {1, 0}},
+                         {{0, 1}, {1, 1}, {UINT32_MAX, UINT32_MAX}}};
+    BorrowedTestMapping mapping(values);
+    MockRAMDirectory dense0, dense1, borrowed0, borrowed1;
+    for (auto* dir : {&dense0, &dense1, &borrowed0, &borrowed1})
+        dir->setRandomIOExceptionRate(0.0, 0);
+    std::vector<lucene::store::Directory*> sources {&source0, &source1};
+    lucene::analysis::SimpleAnalyzer<char> analyzer;
+    RAMDirectory denseScratch;
+    IndexWriter dense(&denseScratch, &analyzer, true);
+    dense.indexCompaction(sources, {&dense0, &dense1}, values, {2, 2});
+    dense.close();
+    RAMDirectory borrowedScratch;
+    std::ostringstream trace;
+    IndexWriter borrowed(&borrowedScratch, &analyzer, true);
+    borrowed.setInfoStream(&trace);
+    borrowed.indexCompaction(sources, {&borrowed0, &borrowed1}, mapping, {2, 
2});
+    borrowed.close();
+    for (auto pair : {std::make_pair(&dense0, &borrowed0), 
std::make_pair(&dense1, &borrowed1)}) {
+        auto* expected = IndexReader::open(pair.first);
+        auto* actual = IndexReader::open(pair.second);
+        CuAssertIntEquals(tc, _T("destination documents"), expected->maxDoc(), 
actual->maxDoc());
+        CuAssert(tc, _T("postings and positions match dense"),
+                 readPostings(expected) == readPostings(actual));
+        for (const auto* field : {_T("body"), _T("title")}) {
+            const auto* a = expected->norms(field);
+            const auto* b = actual->norms(field);
+            CuAssert(tc, _T("norm bytes match dense"), std::equal(a, a + 
expected->maxDoc(), b));
+            CuAssert(tc, _T("token totals match dense"),
+                     expected->sumTotalTermFreq(field) == 
actual->sumTotalTermFreq(field));
+        }
+        expected->close();
+        actual->close();
+        _CLDELETE(expected);
+        _CLDELETE(actual);
+        CuAssert(tc, _T("null row IDs match dense"),
+                 readNulls(*pair.first) == readNulls(*pair.second));
+    }
+    CuAssert(tc, _T("provider was used"), mapping.lookups > 0);
+    CuAssert(tc, _T("term/field changes can rewind a source"), 
mapping.revisited);
+    CuAssert(tc, _T("diagnostic source IDs do not need a reverse map"),
+             trace.str().find("Found pair at srcIdxId:") != std::string::npos);
+}
+
+void TestBorrowedCompactionMappingFailure(CuTest* tc) {
+    // Fail separately in norm remapping, postings and the null-bitmap-only 
path.
+    for (int phase : {0, 1, 2}) {
+        RAMDirectory source;
+        const std::string text = phase == 2 ? "" : "alpha";
+        writeNormsIndex(source, {{text, text}}, phase == 0, true);
+        if (phase == 2) writeNulls(source, {0});
+        MockRAMDirectory destination;
+        destination.setRandomIOExceptionRate(0.0, 0);
+        DenseMapping values {{{0, 0}}};
+        BorrowedTestMapping mapping(values, true);
+        RAMDirectory scratch;
+        lucene::analysis::SimpleAnalyzer<char> analyzer;
+        IndexWriter writer(&scratch, &analyzer, true);
+        std::vector<lucene::store::Directory*> sources {&source};
+        bool rejected = false;
+        try {
+            writer.indexCompaction(sources, {&destination}, mapping, {1});
+        } catch (CLuceneError& error) {
+            CuAssertIntEquals(tc, _T("mapping failure is propagated"), 
CL_ERR_IO, error.number());
+            rejected = true;
+        }
+        writer.close();
+        CuAssert(tc, _T("failed lookup is not a deleted document"), rejected);
+    }
+}
+
 CuSuite* testIndexCompaction() {
     CuSuite* suite = CuSuiteNew(_T("CLucene Index Compaction Test"));
 
@@ -485,6 +715,10 @@ CuSuite* testIndexCompaction() {
     SUITE_ADD_TEST(suite, TestMergeNullBitmapEmptySrc);
     SUITE_ADD_TEST(suite, TestMergeNullBitmapEmptyIndexSrcBitmapValues);
     SUITE_ADD_TEST(suite, TestMergeNullBitmapIgnoreDoc);
+    SUITE_ADD_TEST(suite, TestHelperBorrowsMapping);
+    SUITE_ADD_TEST(suite, TestDenseCompactionMappingLifetime);
+    SUITE_ADD_TEST(suite, TestBorrowedCompactionMapping);
+    SUITE_ADD_TEST(suite, TestBorrowedCompactionMappingFailure);
     SUITE_ADD_TEST(suite, TestCompactionTokenCounts);
     SUITE_ADD_TEST(suite, TestCompactionDeletedDocumentsSingleDestination);
     SUITE_ADD_TEST(suite, TestCompactionWithoutFrequencies);


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

Reply via email to