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 238f43a5d67 [improvement](be) Rewrite the tokens of a batch in place 
in the one-to-one filters (#70269)
238f43a5d67 is described below

commit 238f43a5d674ff142d7912263530e3e6a64fb74b
Author: Jack <[email protected]>
AuthorDate: Sun Nov 22 18:30:05 2026 +0800

    [improvement](be) Rewrite the tokens of a batch in place in the one-to-one 
filters (#70269)
    
    ### What problem does this PR solve?
    
    Issue Number: None
    
    Related PR: #70268 (depends on)
    
    Problem Summary: Let lowercase, icu_normalizer and asciifolding rewrite
    a token batch in place instead of copying every term: custom analyzers
    with these filters get 1.7x to 2.2x faster, with the same tokens.
---
 .../analysis/token_filter/ascii_folding_filter.cpp | 117 +++--
 .../analysis/token_filter/ascii_folding_filter.h   |  41 +-
 .../token_filter/ascii_folding_filter_factory.h    |   6 +-
 .../token_filter/icu_normalizer_filter.cpp         |  30 +-
 .../analysis/token_filter/icu_normalizer_filter.h  |  22 +-
 .../analysis/token_filter/lower_case_filter.h      | 133 ++++--
 .../inverted/analysis/component_stream_test.cpp    |  29 +-
 .../ascii_folding_filter_factory_test.cpp          |  35 ++
 .../lower_case_filter_factory_test.cpp             | 112 ++++-
 .../token_filter/one_to_one_filter_test.cpp        | 482 +++++++++++++++++++++
 10 files changed, 872 insertions(+), 135 deletions(-)

diff --git 
a/be/src/storage/index/inverted/analysis/token_filter/ascii_folding_filter.cpp 
b/be/src/storage/index/inverted/analysis/token_filter/ascii_folding_filter.cpp
index 3abf65e6d7f..60b9b40f12e 100644
--- 
a/be/src/storage/index/inverted/analysis/token_filter/ascii_folding_filter.cpp
+++ 
b/be/src/storage/index/inverted/analysis/token_filter/ascii_folding_filter.cpp
@@ -23,74 +23,99 @@
 #include <optional>
 #include <string_view>
 
-#include "common/logging.h"
+#include "common/compiler_util.h"
 #include "storage/index/inverted/analysis/scratch.h"
 
 namespace doris::segment_v2::inverted_index {
 
-ASCIIFoldingFilter::ASCIIFoldingFilter(std::unique_ptr<TextTokenStream> in, 
bool preserve_original)
-        : PerTokenFilter(std::move(in)), 
_preserve_original(preserve_original), _output(512, 0) {}
+namespace {
 
-bool ASCIIFoldingFilter::next_token(TokenRef& token) {
-    if (_state != std::nullopt) {
-        DCHECK(_preserve_original);
-        // The input token it views is still in the input batch: input_token() 
has not run since.
-        token = {.data = _state->data(),
-                 .size = static_cast<uint32_t>(_state->size()),
-                 .position_increment = 0};
-        _state = std::nullopt;
-        return true;
-    }
-    if (!input_token(token)) {
-        return false;
-    }
-    const char* buffer = token.data;
-    auto length = static_cast<int32_t>(token.size);
+// Whether folding may change `term`: only a valid character at or above 
U+0080 folds, and the
+// folding loop drops invalid bytes only along with folding such a character. 
"a\xFF" is left as it
+// is, while "\xFF\xC3\x86" folds to "AE". Inlined: it runs for every token.
+ALWAYS_INLINE inline bool may_fold(std::string_view term) {
+    const char* text = term.data();
+    const auto length = static_cast<int32_t>(term.size());
     for (int32_t i = 0; i < length;) {
         UChar32 c = U_UNASSIGNED;
-        U8_NEXT(buffer, i, length, c);
-        if (c < 0) {
-            continue;
-        }
+        U8_NEXT(text, i, length, c);
         if (c >= 0x0080) {
-            fold_to_ascii(buffer, length);
-            token.data = _output.data();
-            token.size = static_cast<uint32_t>(_output_pos);
-            break;
+            return true;
         }
     }
-    return true;
+    return false;
+}
+
+// The folded form of `term`, a view of `output`, or nothing when the term 
folds to itself, as one
+// of characters without an ASCII form does, e.g. the Han character U+4E2D.
+std::optional<std::string_view> fold(std::string_view term, std::string& 
output) {
+    // No character folds to more than twice its UTF-8 length, e.g. "⒇" (3 
bytes) folds to "(20)".
+    if (output.size() < 2 * term.size()) {
+        output.resize(2 * term.size());
+    }
+    const int32_t folded_size = ASCIIFoldingFilter::fold_to_ascii(
+            term.data(), 0, output.data(), 0, 
static_cast<int32_t>(term.size()));
+    const std::string_view folded(output.data(), folded_size);
+    if (folded == term) {
+        return std::nullopt;
+    }
+    return folded;
 }
 
-void ASCIIFoldingFilter::on_reset() {
-    _state = std::nullopt;
+} // namespace
+
+ASCIIFoldingFilter::ASCIIFoldingFilter(std::unique_ptr<TextTokenStream> in)
+        : TextTokenFilter(std::move(in)) {}
+
+void ASCIIFoldingFilter::reset(std::string_view text) {
+    TextTokenFilter::reset(text);
     release_oversized_scratch(_output);
 }
 
-void ASCIIFoldingFilter::fold_to_ascii(const char* in, int32_t length) {
-    // Worst-case scenario: 3-byte UTF-8 → 4-byte ASCII (expansion ratio 
~1.33x)
-    // Conservative estimate: 2x input length is sufficient to cover all cases
-    int32_t max_size_needed = 2 * length;
-    if (_output.size() < max_size_needed) {
-        _output.resize(max_size_needed);
+bool ASCIIFoldingFilter::next_batch(TokenBatch& batch) {
+    if (!_in->next_batch(batch)) {
+        return false;
     }
-
-    _output_pos = fold_to_ascii(in, 0, _output.data(), 0, length);
-    if (_preserve_original && need_to_preserve(in, length)) {
-        _state = std::string_view(in, length);
+    for (TokenRef& token : batch.tokens()) {
+        if (!may_fold(token.term())) {
+            continue;
+        }
+        if (const auto folded = fold(token.term(), _output)) {
+            char* term = batch.allocate_term(folded->size());
+            folded->copy(term, folded->size());
+            token.data = term;
+            token.size = static_cast<uint32_t>(folded->size());
+        }
     }
+    return true;
 }
 
-bool ASCIIFoldingFilter::need_to_preserve(const char* in, int32_t 
input_length) {
-    if (input_length != _output_pos) {
+bool ASCIIFoldingPreserveOriginalFilter::next_token(TokenRef& token) {
+    if (_original != std::nullopt) {
+        // The input token it views is still in the input batch: input_token() 
has not run since.
+        token = {.data = _original->data(),
+                 .size = static_cast<uint32_t>(_original->size()),
+                 .position_increment = 0};
+        _original = std::nullopt;
         return true;
     }
-    for (int32_t i = 0; i < input_length; i++) {
-        if (in[i] != _output[i]) {
-            return true;
-        }
+    if (!input_token(token)) {
+        return false;
     }
-    return false;
+    if (!may_fold(token.term())) {
+        return true;
+    }
+    if (const auto folded = fold(token.term(), _output)) {
+        _original = token.term();
+        token.data = folded->data();
+        token.size = static_cast<uint32_t>(folded->size());
+    }
+    return true;
+}
+
+void ASCIIFoldingPreserveOriginalFilter::on_reset() {
+    _original = std::nullopt;
+    release_oversized_scratch(_output);
 }
 
 int32_t ASCIIFoldingFilter::fold_to_ascii(const char* in, int32_t input_pos, 
char* out,
diff --git 
a/be/src/storage/index/inverted/analysis/token_filter/ascii_folding_filter.h 
b/be/src/storage/index/inverted/analysis/token_filter/ascii_folding_filter.h
index ab1b129bf5d..77ae7eb63e8 100644
--- a/be/src/storage/index/inverted/analysis/token_filter/ascii_folding_filter.h
+++ b/be/src/storage/index/inverted/analysis/token_filter/ascii_folding_filter.h
@@ -17,41 +17,60 @@
 
 #pragma once
 
+#include <cstddef>
+#include <cstdint>
 #include <memory>
 #include <optional>
 #include <string>
 #include <string_view>
 
 #include "storage/index/inverted/analysis/per_token_stream.h"
+#include "storage/index/inverted/analysis/text_token_stream.h"
+#include "storage/index/inverted/analysis/token_batch.h"
 
 namespace doris::segment_v2::inverted_index {
 
-// Folds the letters, digits and symbols of every token to their ASCII 
equivalents; with
-// preserve_original, a token that changed is followed by the original at the 
same position.
-class ASCIIFoldingFilter final : public PerTokenFilter {
+// Folds the letters, digits and symbols of every token to their ASCII 
equivalents where it stands
+// in the batch, one token for one: a term that folding changes is replaced by 
a view of its folded
+// form in term storage, the rest keep their views. preserve_original can make 
two tokens of one,
+// so ASCIIFoldingPreserveOriginalFilter does that instead.
+class ASCIIFoldingFilter final : public TextTokenFilter {
 public:
-    ASCIIFoldingFilter(std::unique_ptr<TextTokenStream> in, bool 
preserve_original);
+    explicit ASCIIFoldingFilter(std::unique_ptr<TextTokenStream> in);
 
+    void reset(std::string_view text) override;
+    bool next_batch(TokenBatch& batch) override;
     // The scratch of one folded token, and the input.
     size_t reserved_bytes() const override {
-        return PerTokenFilter::reserved_bytes() + _output.capacity();
+        return TextTokenFilter::reserved_bytes() + _output.capacity();
     }
 
     static int32_t fold_to_ascii(const char* in, int32_t input_pos, char* out, 
int32_t output_pos,
                                  int32_t length);
 
+private:
+    std::string _output;
+};
+
+// asciifolding with preserve_original: a token that folding changes is 
followed by the original at
+// the same position, e.g. "café" makes "cafe" and then "café" with a position 
increment of 0.
+class ASCIIFoldingPreserveOriginalFilter final : public PerTokenFilter {
+public:
+    explicit 
ASCIIFoldingPreserveOriginalFilter(std::unique_ptr<TextTokenStream> in)
+            : PerTokenFilter(std::move(in)) {}
+
+    // The scratch of one folded token, and the input.
+    size_t reserved_bytes() const override {
+        return PerTokenFilter::reserved_bytes() + _output.capacity();
+    }
+
 protected:
     void on_reset() override;
     bool next_token(TokenRef& token) override;
 
 private:
-    void fold_to_ascii(const char* in, int32_t length);
-    bool need_to_preserve(const char* in, int32_t input_length);
-
     // The original of the token last folded, still to come out.
-    std::optional<std::string_view> _state;
-    bool _preserve_original = false;
-    int32_t _output_pos = 0;
+    std::optional<std::string_view> _original;
     std::string _output;
 };
 
diff --git 
a/be/src/storage/index/inverted/analysis/token_filter/ascii_folding_filter_factory.h
 
b/be/src/storage/index/inverted/analysis/token_filter/ascii_folding_filter_factory.h
index 47c55fda7f0..8e15ceabdce 100644
--- 
a/be/src/storage/index/inverted/analysis/token_filter/ascii_folding_filter_factory.h
+++ 
b/be/src/storage/index/inverted/analysis/token_filter/ascii_folding_filter_factory.h
@@ -31,8 +31,12 @@ public:
         _preserve_original = settings.get_bool("preserve_original", false);
     }
 
+    // preserve_original can make two tokens of one, which only the per-token 
filter can.
     std::unique_ptr<TextTokenStream> create(std::unique_ptr<TextTokenStream> 
in) const override {
-        return std::make_unique<ASCIIFoldingFilter>(std::move(in), 
_preserve_original);
+        if (_preserve_original) {
+            return 
std::make_unique<ASCIIFoldingPreserveOriginalFilter>(std::move(in));
+        }
+        return std::make_unique<ASCIIFoldingFilter>(std::move(in));
     }
 
 private:
diff --git 
a/be/src/storage/index/inverted/analysis/token_filter/icu_normalizer_filter.cpp 
b/be/src/storage/index/inverted/analysis/token_filter/icu_normalizer_filter.cpp
index 10d048413cd..0c686f01a05 100644
--- 
a/be/src/storage/index/inverted/analysis/token_filter/icu_normalizer_filter.cpp
+++ 
b/be/src/storage/index/inverted/analysis/token_filter/icu_normalizer_filter.cpp
@@ -28,24 +28,35 @@ namespace doris::segment_v2::inverted_index {
 
 ICUNormalizerFilter::ICUNormalizerFilter(std::unique_ptr<TextTokenStream> in,
                                          std::shared_ptr<const 
icu::Normalizer2> normalizer)
-        : PerTokenFilter(std::move(in)), _normalizer(std::move(normalizer)) {
+        : TextTokenFilter(std::move(in)), _normalizer(std::move(normalizer)) {
     if (_normalizer == nullptr) {
         throw Exception(ErrorCode::INVALID_ARGUMENT,
                         "ICUNormalizerFilter: normalizer cannot be null");
     }
 }
 
-bool ICUNormalizerFilter::next_token(TokenRef& token) {
-    if (!input_token(token)) {
+void ICUNormalizerFilter::reset(std::string_view text) {
+    TextTokenFilter::reset(text);
+    release_oversized_scratch(_output_buffer);
+}
+
+bool ICUNormalizerFilter::next_batch(TokenBatch& batch) {
+    if (!_in->next_batch(batch)) {
         return false;
     }
+    for (TokenRef& token : batch.tokens()) {
+        normalize(token, batch);
+    }
+    return true;
+}
 
+void ICUNormalizerFilter::normalize(TokenRef& token, TokenBatch& batch) {
     UErrorCode status = U_ZERO_ERROR;
     icu::UnicodeString src16 = icu::UnicodeString::fromUTF8(
             icu::StringPiece(token.data, static_cast<int32_t>(token.size)));
     UNormalizationCheckResult quick_result = _normalizer->quickCheck(src16, 
status);
     if (U_SUCCESS(status) && quick_result == UNORM_YES) {
-        return true;
+        return;
     }
 
     icu::UnicodeString result16;
@@ -53,18 +64,15 @@ bool ICUNormalizerFilter::next_token(TokenRef& token) {
     _normalizer->normalize(src16, result16, status);
     if (U_FAILURE(status)) {
         LOG(WARNING) << "Normalize failed: " << u_errorName(status);
-        return true;
+        return;
     }
 
     _output_buffer.clear();
     result16.toUTF8String(_output_buffer);
-    token.data = _output_buffer.data();
+    char* term = batch.allocate_term(_output_buffer.size());
+    _output_buffer.copy(term, _output_buffer.size());
+    token.data = term;
     token.size = static_cast<uint32_t>(_output_buffer.size());
-    return true;
-}
-
-void ICUNormalizerFilter::on_reset() {
-    release_oversized_scratch(_output_buffer);
 }
 
 } // namespace doris::segment_v2::inverted_index
diff --git 
a/be/src/storage/index/inverted/analysis/token_filter/icu_normalizer_filter.h 
b/be/src/storage/index/inverted/analysis/token_filter/icu_normalizer_filter.h
index b969ba8008b..711667bdb71 100644
--- 
a/be/src/storage/index/inverted/analysis/token_filter/icu_normalizer_filter.h
+++ 
b/be/src/storage/index/inverted/analysis/token_filter/icu_normalizer_filter.h
@@ -19,30 +19,36 @@
 
 #include <unicode/normalizer2.h>
 
+#include <cstddef>
 #include <memory>
 #include <string>
+#include <string_view>
 
-#include "storage/index/inverted/analysis/per_token_stream.h"
+#include "storage/index/inverted/analysis/text_token_stream.h"
+#include "storage/index/inverted/analysis/token_batch.h"
 
 namespace doris::segment_v2::inverted_index {
 
-// Normalizes every token with an ICU normalizer, NFKC_CF by default.
-class ICUNormalizerFilter final : public PerTokenFilter {
+// Normalizes every token with an ICU normalizer, NFKC_CF by default, where it 
stands in the batch,
+// one token for one. A term the normalizer's quick check passes keeps its 
view; any other is
+// normalized into the term storage of the batch.
+class ICUNormalizerFilter final : public TextTokenFilter {
 public:
     ICUNormalizerFilter(std::unique_ptr<TextTokenStream> in,
                         std::shared_ptr<const icu::Normalizer2> normalizer);
 
+    void reset(std::string_view text) override;
+    bool next_batch(TokenBatch& batch) override;
     // The scratch of one normalized token, and the input.
     size_t reserved_bytes() const override {
-        return PerTokenFilter::reserved_bytes() + _output_buffer.capacity();
+        return TextTokenFilter::reserved_bytes() + _output_buffer.capacity();
     }
 
-protected:
-    void on_reset() override;
-    bool next_token(TokenRef& token) override;
-
 private:
+    void normalize(TokenRef& token, TokenBatch& batch);
+
     std::shared_ptr<const icu::Normalizer2> _normalizer;
+    // The UTF-8 of the token last normalized, before it is copied into the 
batch.
     std::string _output_buffer;
 };
 
diff --git 
a/be/src/storage/index/inverted/analysis/token_filter/lower_case_filter.h 
b/be/src/storage/index/inverted/analysis/token_filter/lower_case_filter.h
index d45f93af40e..cdb34bc6fdd 100644
--- a/be/src/storage/index/inverted/analysis/token_filter/lower_case_filter.h
+++ b/be/src/storage/index/inverted/analysis/token_filter/lower_case_filter.h
@@ -19,6 +19,8 @@
 
 #include <unicode/ucasemap.h>
 
+#include <cstddef>
+#include <cstdint>
 #include <memory>
 #include <string>
 #include <string_view>
@@ -29,8 +31,8 @@
 
 #include "common/cast_set.h"
 #include "common/exception.h"
-#include "storage/index/inverted/analysis/per_token_stream.h"
-#include "storage/index/inverted/analysis/scratch.h"
+#include "storage/index/inverted/analysis/text_token_stream.h"
+#include "storage/index/inverted/analysis/token_batch.h"
 #include "util/utf8_check.h"
 
 namespace doris::segment_v2::inverted_index {
@@ -95,12 +97,14 @@ inline void unicode_lower(std::string& value) {
     }
 }
 
-// Lowercases every token: ASCII byte by byte, anything else with the 
root-locale case mapping.
-// A token that is not ASCII must be valid UTF-8.
-class LowerCaseFilter final : public PerTokenFilter {
+// Lowercases every token where it stands in the batch, one token for one: 
ASCII byte by byte,
+// anything else with the root-locale case mapping. A token that is not ASCII 
must be valid UTF-8.
+// A lowercased term goes to the term storage of the batch, so the filter 
keeps no buffer of its
+// own and its input's reset() and reserved_bytes() are its own.
+class LowerCaseFilter final : public TextTokenFilter {
 public:
     explicit LowerCaseFilter(std::unique_ptr<TextTokenStream> in)
-            : PerTokenFilter(std::move(in)), _ucsm(nullptr, &ucasemap_close) {}
+            : TextTokenFilter(std::move(in)), _ucsm(nullptr, &ucasemap_close) 
{}
 
     void initialize() {
         UErrorCode status = U_ZERO_ERROR;
@@ -113,60 +117,98 @@ public:
         _ucsm.reset(ucsm);
     }
 
-    // The scratch of one lowercased token, and the input.
-    size_t reserved_bytes() const override {
-        return PerTokenFilter::reserved_bytes() + _lower_term.capacity();
-    }
-
-protected:
-    void on_reset() override { release_oversized_scratch(_lower_term); }
-
-    bool next_token(TokenRef& token) override {
-        if (!input_token(token)) {
+    // The input fills `batch` and the filter rewrites its tokens: a term that 
changes is replaced
+    // by a view of its lowercase form in term storage, the rest keep their 
views.
+    bool next_batch(TokenBatch& batch) override {
+        if (!_in->next_batch(batch)) {
             return false;
         }
-        const std::string_view term = token.term();
-        bool has_ascii_upper = false;
-        bool all_ascii = true;
-        for (const char value : term) {
-            const auto byte = static_cast<uint8_t>(value);
-            if (byte >= 0x80) {
-                all_ascii = false;
+        for (TokenRef& token : batch.tokens()) {
+            switch (needs_rewrite(token.term())) {
+            case Rewrite::kNone:
+                break;
+            case Rewrite::kAscii:
+                token.data = lower_ascii(token.term(), batch);
+                break;
+            case Rewrite::kUnicode:
+                lower_unicode(token, batch);
                 break;
             }
-            has_ascii_upper |= byte >= 'A' && byte <= 'Z';
         }
-        if (all_ascii) {
-            if (!has_ascii_upper) {
-                return true;
-            }
-            _lower_term.resize(term.size());
-            for (size_t i = 0; i < term.size(); ++i) {
-                const auto byte = static_cast<uint8_t>(term[i]);
-                _lower_term[i] =
-                        static_cast<char>(byte >= 'A' && byte <= 'Z' ? byte + 
('a' - 'A') : byte);
+        return true;
+    }
+
+private:
+    enum class Rewrite : uint8_t {
+        kNone,    // left as it is
+        kAscii,   // lowercased byte by byte
+        kUnicode, // validated, then lowercased by ICU
+    };
+
+    // Only kUnicode validates a term, so a term skips it only when it is 
valid UTF-8 for certain:
+    //   61 62 63 "abc"   kNone     ASCII without a capital
+    //   61 42 63 "aBc"   kAscii    ASCII with a capital
+    //   E4 B8 AD U+4E2D  kNone     one character of three bytes led by 
E3..E9: always valid, as
+    //                              only the leads E0 and ED narrow the second 
byte, and within
+    //                              U+3000..U+9FFF, where no character has a 
lowercase form
+    //   E4 41 41         kUnicode  41 is no continuation byte, so validation 
throws
+    //   C3 9C 62 65 72   kUnicode  "Über", lowercased to "über"
+    // The single CJK character is what the standard tokenizer makes of 
Chinese text: one token per
+    // ideograph.
+    static Rewrite needs_rewrite(std::string_view term) {
+        uint8_t high = 0;
+        bool upper = false;
+        for (const char c : term) {
+            const auto byte = static_cast<uint8_t>(c);
+            high |= byte;
+            upper |= static_cast<uint8_t>(byte - 'A') < 26;
+        }
+        if (high < 0x80) {
+            return upper ? Rewrite::kAscii : Rewrite::kNone;
+        }
+        if (term.size() == 3) {
+            const auto lead = static_cast<uint8_t>(term[0]);
+            const auto second = static_cast<uint8_t>(term[1]);
+            const auto third = static_cast<uint8_t>(term[2]);
+            if (lead >= 0xE3 && lead <= 0xE9 && (second & 0xC0) == 0x80 && 
(third & 0xC0) == 0x80) {
+                return Rewrite::kNone;
             }
-            token.data = _lower_term.data();
-            return true;
         }
+        return Rewrite::kUnicode;
+    }
+
+    // The lowercase form of ASCII `term`, in the term storage of `batch`.
+    static const char* lower_ascii(std::string_view term, TokenBatch& batch) {
+        char* lower = batch.allocate_term(term.size());
+        for (size_t i = 0; i < term.size(); ++i) {
+            const auto byte = static_cast<uint8_t>(term[i]);
+            lower[i] = static_cast<char>(byte >= 'A' && byte <= 'Z' ? byte + 
('a' - 'A') : byte);
+        }
+        return lower;
+    }
+
+    // Validates the term of `token`, then points it at its lowercase form in 
the term storage of
+    // `batch`. Lowercasing can make a term longer, e.g. U+0130 (C4 B0) 
becomes "i" and a combining
+    // dot above (69 CC 87): ICU then reports the length it needs, and the 
term is lowercased again
+    // into that many bytes.
+    void lower_unicode(TokenRef& token, TokenBatch& batch) const {
 #ifdef BE_TEST
         lower_case_testing::note_unicode_path();
 #endif
+        const std::string_view term = token.term();
         if (!validate_utf8(term.data(), term.size())) {
             throw Exception(ErrorCode::INVERTED_INDEX_ANALYZER_ERROR,
                             "Failed to lowercase token: invalid UTF-8");
         }
-
-        _lower_term.resize(term.size());
+        char* lower = batch.allocate_term(term.size());
         UErrorCode status = U_ZERO_ERROR;
-        int32_t result_len = ucasemap_utf8ToLower(
-                _ucsm.get(), _lower_term.data(), 
cast_set<int32_t>(_lower_term.size()), term.data(),
-                cast_set<int32_t>(term.size()), &status);
+        int32_t result_len =
+                ucasemap_utf8ToLower(_ucsm.get(), lower, 
cast_set<int32_t>(term.size()),
+                                     term.data(), 
cast_set<int32_t>(term.size()), &status);
         if (status == U_BUFFER_OVERFLOW_ERROR) {
-            _lower_term.resize(cast_set<size_t>(result_len));
+            lower = batch.allocate_term(cast_set<size_t>(result_len));
             status = U_ZERO_ERROR;
-            result_len = ucasemap_utf8ToLower(_ucsm.get(), _lower_term.data(),
-                                              
cast_set<int32_t>(_lower_term.size()), term.data(),
+            result_len = ucasemap_utf8ToLower(_ucsm.get(), lower, result_len, 
term.data(),
                                               cast_set<int32_t>(term.size()), 
&status);
         }
         if (U_FAILURE(status)) {
@@ -174,14 +216,11 @@ protected:
                             "Failed to convert token to lowercase. ICU Error: 
{} - {}",
                             static_cast<int32_t>(status), u_errorName(status));
         }
-        token.data = _lower_term.data();
+        token.data = lower;
         token.size = cast_set<uint32_t>(result_len);
-        return true;
     }
 
-private:
     std::unique_ptr<UCaseMap, decltype(&ucasemap_close)> _ucsm;
-    std::string _lower_term;
 };
 
 } // namespace doris::segment_v2::inverted_index
diff --git a/be/test/storage/index/inverted/analysis/component_stream_test.cpp 
b/be/test/storage/index/inverted/analysis/component_stream_test.cpp
index aefa29c0622..712dd150daf 100644
--- a/be/test/storage/index/inverted/analysis/component_stream_test.cpp
+++ b/be/test/storage/index/inverted/analysis/component_stream_test.cpp
@@ -374,16 +374,16 @@ std::unique_ptr<TextTokenStream> whole_value(Components& 
components) {
     return components.tokenizer("empty");
 }
 
-TEST(ComponentStreamTest, LowerCaseFilterReleasesItsScratch) {
+TEST(ComponentStreamTest, LowerCaseFilterKeepsNothingOfItsOwn) {
     Components components;
     expect_text_stream_contract(
             [&] { return components.filter("lowercase", 
components.tokenizer("standard")); },
             contract_texts());
     auto stream = components.filter("lowercase", whole_value(components));
     auto& lower = as<LowerCaseFilter>(*stream);
-    expect_released_at_next_row(*stream, repeat_to("ÄBC", kLongRowBytes), 
"short", true, [&] {
-        return lower._lower_term.capacity() + per_token_filter_bytes(lower);
-    });
+    // A lowercased term goes to the batch, which the consumer owns.
+    expect_released_at_next_row(*stream, repeat_to("ÄBC", kLongRowBytes), 
"short", false,
+                                [&] { return lower._in->reserved_bytes(); });
 }
 
 TEST(ComponentStreamTest, ASCIIFoldingFilterReleasesItsScratch) {
@@ -397,12 +397,21 @@ TEST(ComponentStreamTest, 
ASCIIFoldingFilterReleasesItsScratch) {
                                              settings);
                 },
                 contract_texts());
-        auto stream = components.filter("asciifolding", 
whole_value(components), settings);
-        auto& folding = as<ASCIIFoldingFilter>(*stream);
-        expect_released_at_next_row(*stream, repeat_to("café", kLongRowBytes), 
"short", true, [&] {
-            return folding._output.capacity() + 
per_token_filter_bytes(folding);
-        });
     }
+    // Without preserve_original the filter folds into its scratch and copies 
the folded term into
+    // the batch; with it, a per-token filter keeps its input batch as well.
+    auto stream = components.filter("asciifolding", whole_value(components),
+                                    settings_of({{"preserve_original", 
"false"}}));
+    auto& folding = as<ASCIIFoldingFilter>(*stream);
+    expect_released_at_next_row(*stream, repeat_to("café", kLongRowBytes), 
"short", true, [&] {
+        return folding._output.capacity() + folding._in->reserved_bytes();
+    });
+    auto preserving = components.filter("asciifolding", 
whole_value(components),
+                                        settings_of({{"preserve_original", 
"true"}}));
+    auto& preserve = as<ASCIIFoldingPreserveOriginalFilter>(*preserving);
+    expect_released_at_next_row(*preserving, repeat_to("café", kLongRowBytes), 
"short", true, [&] {
+        return preserve._output.capacity() + per_token_filter_bytes(preserve);
+    });
 }
 
 TEST(ComponentStreamTest, ICUNormalizerFilterReleasesItsScratch) {
@@ -414,7 +423,7 @@ TEST(ComponentStreamTest, 
ICUNormalizerFilterReleasesItsScratch) {
     auto& normalizer = as<ICUNormalizerFilter>(*stream);
     // NFKC_CF folds case, so the normalized token is as long as the row.
     expect_released_at_next_row(*stream, repeat_to("ABc", kLongRowBytes), 
"short", true, [&] {
-        return normalizer._output_buffer.capacity() + 
per_token_filter_bytes(normalizer);
+        return normalizer._output_buffer.capacity() + 
normalizer._in->reserved_bytes();
     });
 }
 
diff --git 
a/be/test/storage/index/inverted/analysis/token_filter/ascii_folding_filter_factory_test.cpp
 
b/be/test/storage/index/inverted/analysis/token_filter/ascii_folding_filter_factory_test.cpp
index fd31d1096ed..bc1d1fba6bf 100644
--- 
a/be/test/storage/index/inverted/analysis/token_filter/ascii_folding_filter_factory_test.cpp
+++ 
b/be/test/storage/index/inverted/analysis/token_filter/ascii_folding_filter_factory_test.cpp
@@ -25,6 +25,7 @@
 
 #include "storage/index/inverted/analysis/text_stream_contract.h"
 #include 
"storage/index/inverted/analysis/tokenizer/keyword/keyword_tokenizer_factory.h"
+#include 
"storage/index/inverted/analysis/tokenizer/standard/standard_tokenizer_factory.h"
 
 namespace doris::segment_v2::inverted_index {
 
@@ -119,6 +120,40 @@ TEST_F(ASCIIFoldingFilterFactoryTest, 
PositionIncrementsCorrect) {
     assert_filter_output("á b c", {{"a b c", 1}, {"á b c", 0}}, true);
 }
 
+namespace {
+
+std::unique_ptr<TextTokenStream> create_standard_folding(bool 
preserve_original) {
+    StandardTokenizerFactory tokenizer_factory;
+    tokenizer_factory.initialize(Settings());
+    Settings settings;
+    settings.set("preserve_original", preserve_original ? "true" : "false");
+    ASCIIFoldingFilterFactory filter_factory;
+    filter_factory.initialize(settings);
+    return filter_factory.create(tokenizer_factory.create());
+}
+
+} // namespace
+
+// preserve_original makes two tokens of one, which only the per-token filter 
makes.
+TEST_F(ASCIIFoldingFilterFactoryTest, 
StandardTokenizerPreservesTheOriginalAtItsPosition) {
+    auto filter = create_standard_folding(true);
+    EXPECT_NE(dynamic_cast<ASCIIFoldingPreserveOriginalFilter*>(filter.get()), 
nullptr);
+    EXPECT_EQ(collect_checked(*filter, "café"),
+              (std::vector<CollectedToken> {{"cafe", 1}, {"café", 0}}));
+    EXPECT_EQ(collect_checked(*filter, "Ærø café 中"),
+              (std::vector<CollectedToken> {
+                      {"AEro", 1}, {"Ærø", 0}, {"cafe", 1}, {"café", 0}, {"中", 
1}}));
+}
+
+// Without preserve_original the one-to-one filter folds every token where it 
stands.
+TEST_F(ASCIIFoldingFilterFactoryTest, 
StandardTokenizerFoldsWithoutTheOriginal) {
+    auto filter = create_standard_folding(false);
+    EXPECT_NE(dynamic_cast<ASCIIFoldingFilter*>(filter.get()), nullptr);
+    EXPECT_EQ(collect_checked(*filter, "café"), (std::vector<CollectedToken> 
{{"cafe", 1}}));
+    EXPECT_EQ(collect_checked(*filter, "Ærø café 中"),
+              (std::vector<CollectedToken> {{"AEro", 1}, {"cafe", 1}, {"中", 
1}}));
+}
+
 TEST_F(ASCIIFoldingFilterFactoryTest, ExhaustiveUnicodeCharacters) {
     // This test includes a wide range of Unicode characters to ensure 
comprehensive
     // coverage of the folding logic in ASCIIFoldingFilter.
diff --git 
a/be/test/storage/index/inverted/analysis/token_filter/lower_case_filter_factory_test.cpp
 
b/be/test/storage/index/inverted/analysis/token_filter/lower_case_filter_factory_test.cpp
index 4bff3873d11..3cae1455229 100644
--- 
a/be/test/storage/index/inverted/analysis/token_filter/lower_case_filter_factory_test.cpp
+++ 
b/be/test/storage/index/inverted/analysis/token_filter/lower_case_filter_factory_test.cpp
@@ -23,6 +23,7 @@
 #include <memory>
 #include <string>
 #include <string_view>
+#include <utility>
 #include <vector>
 
 #include "storage/index/inverted/analysis/text_stream_contract.h"
@@ -149,11 +150,15 @@ TEST_F(LowerCaseFilterTest, 
RejectsInvalidUtf8WithAnalyzerError) {
     ASSERT_EQ(valid_terms.size(), 1);
     EXPECT_EQ(valid_terms[0], "valid");
 
-    // The batch with the malformed token fails as a whole, and the stream is 
not read after that.
+    // The input hands out one token per batch, and the filter rewrites the 
batches of its input:
+    // the first comes out lowercased, the second fails, and the stream is not 
read after that.
     auto filter = 
create_lowercase_filter(std::make_unique<ScriptedLowercaseInput>(
             std::vector<std::string> {"VALID", std::string(1, 
static_cast<char>(0xFF))}));
     filter->reset("");
     TokenBatch batch;
+    ASSERT_TRUE(filter->next_batch(batch));
+    ASSERT_EQ(batch.size(), 1);
+    EXPECT_EQ(batch.tokens()[0].term(), "valid");
     try {
         filter->next_batch(batch);
         FAIL() << "expected malformed UTF-8 to fail analysis";
@@ -162,6 +167,111 @@ TEST_F(LowerCaseFilterTest, 
RejectsInvalidUtf8WithAnalyzerError) {
     }
 }
 
+namespace {
+
+// Hands out all its terms in one batch, as views of the strings it keeps, 
whatever the text.
+class OneBatchLowercaseInput final : public TextTokenizer {
+public:
+    explicit OneBatchLowercaseInput(std::vector<std::string> terms) : 
_terms(std::move(terms)) {}
+
+    void reset(std::string_view /*text*/) override { _done = false; }
+
+    bool next_batch(TokenBatch& batch) override {
+        batch.clear();
+        if (_done) {
+            return false;
+        }
+        for (const std::string& term : _terms) {
+            batch.push(term, 1);
+        }
+        _done = true;
+        return true;
+    }
+
+    size_t reserved_bytes() const override { return 0; }
+
+    const std::vector<std::string>& terms() const { return _terms; }
+
+private:
+    std::vector<std::string> _terms;
+    bool _done = true;
+};
+
+// The terms the lowercase filter makes of `terms` in one batch, each with 
whether it still views
+// the input.
+std::vector<std::pair<std::string, bool>> lower_in_one_batch(
+        const std::vector<std::string>& terms) {
+    auto input = std::make_unique<OneBatchLowercaseInput>(terms);
+    const OneBatchLowercaseInput& source = *input;
+    auto filter = create_lowercase_filter(std::move(input));
+    filter->reset("");
+    TokenBatch batch;
+    EXPECT_TRUE(filter->next_batch(batch));
+    std::vector<std::pair<std::string, bool>> lowered;
+    for (size_t i = 0; i < batch.size(); ++i) {
+        const TokenRef& token = batch.tokens()[i];
+        EXPECT_EQ(token.position_increment, 1);
+        lowered.emplace_back(token.term(), token.data == 
source.terms()[i].data());
+    }
+    EXPECT_FALSE(filter->next_batch(batch));
+    return lowered;
+}
+
+} // namespace
+
+// The four classes of term: a term left as it is keeps its view of the input, 
a lowercased one
+// points into the batch, and only the last class goes through validation and 
ICU.
+TEST_F(LowerCaseFilterTest, HandlesEachClassOfTerm) {
+    const std::vector<std::string> terms = {
+            // Left as they are: ASCII without a capital, the empty term, and 
one character of
+            // three bytes led by E3..E9: U+4E2D, U+3000 and U+9FFF.
+            "abc", "", "\xE4\xB8\xAD", "\xE3\x80\x80", "\xE9\xBF\xBF",
+            // Lowercased byte by byte: ASCII with a capital.
+            "aBC", std::string("A\0B", 3),
+            // Validated and lowercased by ICU: Über, two CJK characters, the 
leads E2 (U+2FFF)
+            // and EA (U+A000) next to the range, and a capital of three 
bytes, Ⓐ (U+24B6).
+            "\xC3\x9C"
+            "ber",
+            "\xE4\xB8\xAD\xE6\x96\x87", "\xE2\xBF\xBF", "\xEA\x80\x80", 
"\xE2\x92\xB6"};
+    const std::vector<std::pair<std::string, bool>> expected = {{"abc", true},
+                                                                {"", true},
+                                                                
{"\xE4\xB8\xAD", true},
+                                                                
{"\xE3\x80\x80", true},
+                                                                
{"\xE9\xBF\xBF", true},
+                                                                {"abc", false},
+                                                                
{std::string("a\0b", 3), false},
+                                                                {"\xC3\xBC"
+                                                                 "ber",
+                                                                 false},
+                                                                
{"\xE4\xB8\xAD\xE6\x96\x87", false},
+                                                                
{"\xE2\xBF\xBF", false},
+                                                                
{"\xEA\x80\x80", false},
+                                                                
{"\xE2\x93\x90", false}};
+    lower_case_testing::reset_unicode_path_count();
+    EXPECT_EQ(lower_in_one_batch(terms), expected);
+    EXPECT_EQ(lower_case_testing::unicode_path_count(), 5);
+}
+
+// A lead byte of E3..E9 needs two continuation bytes to be left as it is; 
without them the term is
+// validated and fails, as it did when every term that is not ASCII was 
validated.
+TEST_F(LowerCaseFilterTest, RejectsALeadWithoutContinuationBytes) {
+    for (const std::string& text :
+         {std::string("\xE4"
+                      "AA"),
+          std::string("\xE4\xB8"
+                      "A"),
+          std::string("\xE4\xB8"), std::string("\xE4\xB8\xAD\xB8"), 
std::string("\xE9\xBF\xFF")}) {
+        SCOPED_TRACE(text);
+        auto filter = create_lowercase_filter();
+        try {
+            collect_checked(*filter, text);
+            FAIL() << "expected malformed UTF-8 to fail analysis";
+        } catch (const Exception& error) {
+            EXPECT_EQ(error.code(), ErrorCode::INVERTED_INDEX_ANALYZER_ERROR);
+        }
+    }
+}
+
 TEST_F(LowerCaseFilterTest, HandlesNumbersAndSymbols) {
     assert_filter_output("123!@# ABC", {{"123!@# abc", 1}});
 }
diff --git 
a/be/test/storage/index/inverted/analysis/token_filter/one_to_one_filter_test.cpp
 
b/be/test/storage/index/inverted/analysis/token_filter/one_to_one_filter_test.cpp
new file mode 100644
index 00000000000..353500b6b0a
--- /dev/null
+++ 
b/be/test/storage/index/inverted/analysis/token_filter/one_to_one_filter_test.cpp
@@ -0,0 +1,482 @@
+// 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.
+
+// The one-to-one filters, lowercase, icu_normalizer and asciifolding without 
preserve_original,
+// rewrite the batches of their input where they stand. Each is checked 
against a per-token filter
+// running the code it replaced, on random token streams: the same terms, 
increments and
+// exceptions, however the input cuts its batches and wherever its terms live.
+
+#include <gtest/gtest.h>
+#include <unicode/normalizer2.h>
+#include <unicode/ucasemap.h>
+#include <unicode/unistr.h>
+#include <unicode/utf8.h>
+
+#include <cstddef>
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <optional>
+#include <random>
+#include <string>
+#include <string_view>
+#include <utility>
+#include <vector>
+
+#include "common/check.h"
+#include "common/exception.h"
+#include "storage/index/inverted/analysis/per_token_stream.h"
+#include "storage/index/inverted/analysis/text_stream_contract.h"
+#include "storage/index/inverted/analysis/token_batch.h"
+#include 
"storage/index/inverted/analysis/token_filter/ascii_folding_filter_factory.h"
+#include 
"storage/index/inverted/analysis/token_filter/icu_normalizer_filter_factory.h"
+#include 
"storage/index/inverted/analysis/token_filter/lower_case_filter_factory.h"
+#include "util/utf8_check.h"
+
+namespace doris::segment_v2::inverted_index {
+namespace {
+
+struct ScriptedToken {
+    std::string term;
+    int32_t position_increment = 1;
+    // Pushed as a copy into the term storage of the batch, which the filter 
then grows; otherwise
+    // as a view of the script.
+    bool in_batch = false;
+};
+
+// The batches of one value.
+using Script = std::vector<std::vector<ScriptedToken>>;
+
+// Hands out the batches of its script, whatever the text.
+class ScriptedBatchInput final : public TextTokenizer {
+public:
+    explicit ScriptedBatchInput(const Script& script) : _script(script) {}
+
+    void reset(std::string_view /*text*/) override { _next = 0; }
+
+    bool next_batch(TokenBatch& batch) override {
+        batch.clear();
+        if (_next == _script.size()) {
+            return false;
+        }
+        for (const ScriptedToken& token : _script[_next++]) {
+            if (token.in_batch) {
+                batch.push_copy(token.term, token.position_increment);
+            } else {
+                batch.push(token.term, token.position_increment);
+            }
+        }
+        return true;
+    }
+
+    size_t reserved_bytes() const override { return 0; }
+
+private:
+    const Script& _script;
+    size_t _next = 0;
+};
+
+// What a filter did to one token before it rewrote batches: the new term, or 
nothing to keep it.
+using Rewrite = std::function<std::optional<std::string>(std::string_view)>;
+
+// The per-token form of a one-to-one filter, as the three filters were.
+class PerTokenRewrite final : public PerTokenFilter {
+public:
+    PerTokenRewrite(std::unique_ptr<TextTokenStream> in, Rewrite rewrite)
+            : PerTokenFilter(std::move(in)), _rewrite(std::move(rewrite)) {}
+
+protected:
+    bool next_token(TokenRef& token) override {
+        if (!input_token(token)) {
+            return false;
+        }
+        if (std::optional<std::string> term = _rewrite(token.term())) {
+            _term = std::move(*term);
+            token.data = _term.data();
+            token.size = static_cast<uint32_t>(_term.size());
+        }
+        return true;
+    }
+
+private:
+    Rewrite _rewrite;
+    std::string _term;
+};
+
+// LowerCaseFilter before it rewrote batches: ASCII byte by byte, anything 
else validated and then
+// lowercased with the root-locale case map.
+std::optional<std::string> lower_case_per_token(std::string_view term) {
+    bool ascii = true;
+    bool upper = false;
+    for (const char c : term) {
+        const auto byte = static_cast<uint8_t>(c);
+        ascii &= byte < 0x80;
+        upper |= byte >= 'A' && byte <= 'Z';
+    }
+    if (ascii) {
+        if (!upper) {
+            return std::nullopt;
+        }
+        std::string lower(term);
+        for (char& c : lower) {
+            c = c >= 'A' && c <= 'Z' ? static_cast<char>(c - 'A' + 'a') : c;
+        }
+        return lower;
+    }
+    if (!validate_utf8(term.data(), term.size())) {
+        throw Exception(ErrorCode::INVERTED_INDEX_ANALYZER_ERROR,
+                        "Failed to lowercase token: invalid UTF-8");
+    }
+    static const UCaseMap* const case_map = [] {
+        UErrorCode status = U_ZERO_ERROR;
+        const UCaseMap* map = ucasemap_open("", 0, &status);
+        DORIS_CHECK(U_SUCCESS(status));
+        return map;
+    }();
+    // Lowercasing at most doubles a term.
+    std::string lower(2 * term.size(), '\0');
+    UErrorCode status = U_ZERO_ERROR;
+    const int32_t length =
+            ucasemap_utf8ToLower(case_map, lower.data(), 
static_cast<int32_t>(lower.size()),
+                                 term.data(), 
static_cast<int32_t>(term.size()), &status);
+    DORIS_CHECK(U_SUCCESS(status));
+    lower.resize(length);
+    return lower;
+}
+
+// ICUNormalizerFilter before it rewrote batches.
+std::optional<std::string> normalize_per_token(const icu::Normalizer2& 
normalizer,
+                                               std::string_view term) {
+    UErrorCode status = U_ZERO_ERROR;
+    const icu::UnicodeString src16 = icu::UnicodeString::fromUTF8(
+            icu::StringPiece(term.data(), static_cast<int32_t>(term.size())));
+    if (normalizer.quickCheck(src16, status) == UNORM_YES && 
U_SUCCESS(status)) {
+        return std::nullopt;
+    }
+    icu::UnicodeString result16;
+    status = U_ZERO_ERROR;
+    normalizer.normalize(src16, result16, status);
+    DORIS_CHECK(U_SUCCESS(status));
+    std::string result;
+    result16.toUTF8String(result);
+    return result;
+}
+
+// ASCIIFoldingFilter before it rewrote batches: a term with a valid character 
at or above U+0080
+// is folded, any other is kept.
+std::optional<std::string> fold_per_token(std::string_view term) {
+    const char* text = term.data();
+    const auto length = static_cast<int32_t>(term.size());
+    for (int32_t i = 0; i < length;) {
+        UChar32 c = U_UNASSIGNED;
+        U8_NEXT(text, i, length, c);
+        if (c >= 0x80) {
+            std::string folded(2 * term.size(), '\0');
+            folded.resize(ASCIIFoldingFilter::fold_to_ascii(text, 0, 
folded.data(), 0, length));
+            return folded;
+        }
+    }
+    return std::nullopt;
+}
+
+std::string utf8_of(UChar32 c) {
+    char buffer[U8_MAX_LENGTH];
+    int32_t length = 0;
+    U8_APPEND_UNSAFE(buffer, length, c);
+    return {buffer, static_cast<size_t>(length)};
+}
+
+// Characters that take different paths through the three filters: cased, 
case-expanding, folded,
+// normalized, combining, caseless CJK just inside and outside U+3000..U+9FFF, 
supplementary.
+const std::vector<std::string>& unicode_pieces() {
+    static const std::vector<std::string> pieces = {
+            "é", "É", "Ü", "ß", "ẞ", "İ", "ı", "Σ", "ς", "Ω", "Ⱥ", "Ⱦ", "DŽ", 
"Dž", "Я", "я", "Ⓐ",
+            "A", "f", "fi", "ffi", "⒇", "⑽", "½", "Ⅻ", "㎏", "ꜳ", "Œ", "Þ", "中", 
"文", "あ", "カ",
+            "한",
+            // KELVIN SIGN and ANGSTROM SIGN, which lowercase and normalize to 
ASCII k and å.
+            "\xE2\x84\xAA", "\xE2\x84\xAB",
+            // A combining acute alone and after e, and Hangul jamo that 
compose to U+AC00.
+            "\xCC\x81", "e\xCC\x81", "\xE1\x84\x80\xE1\x85\xA1",
+            // SOFT HYPHEN and ZERO WIDTH SPACE, which NFKC_CF removes, and 
U+FFFD.
+            "\xC2\xAD", "\xE2\x80\x8B", "\xEF\xBF\xBD",
+            // U+3000 and U+9FFF, the ends of the caseless range, and U+A000 
and U+2FFF next to it.
+            "\xE3\x80\x80", "\xE9\xBF\xBF", "\xEA\x80\x80", "\xE2\xBF\xBF",
+            // Supplementary: an emoji, DESERET CAPITAL LONG I, MATHEMATICAL 
BOLD CAPITAL A.
+            "\U0001F600", "\U00010400", "\U0001D400", std::string("\0", 1)};
+    return pieces;
+}
+
+// Malformed UTF-8: stray, truncated, overlong, surrogate and out-of-range 
sequences, and leads of
+// E3..E9 without their continuation bytes.
+const std::vector<std::string>& invalid_pieces() {
+    static const std::vector<std::string> pieces = {"\xFF",
+                                                    "\x80",
+                                                    "\xBF",
+                                                    "\xC3",
+                                                    "\xC0\x80",
+                                                    "\xE4\xB8",
+                                                    "\xE4"
+                                                    "AA",
+                                                    "\xE4\xB8"
+                                                    "A",
+                                                    "\xE9\xBF\xFF",
+                                                    "\xED\xA0\x80",
+                                                    "\xF0\x9F\x98",
+                                                    "\xF4\x90\x80\x80",
+                                                    "\xE0\x80\x80",
+                                                    "\xFF\xC3\x86",
+                                                    "\xC3\x86\xFF"};
+    return pieces;
+}
+
+std::string random_ascii(std::mt19937_64& random, bool capital) {
+    static constexpr std::string_view kLower = 
"abcdefghijklmnopqrstuvwxyz0123456789-_.@";
+    static constexpr std::string_view kUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+    std::string term;
+    const size_t size = 1 + random() % 12;
+    for (size_t i = 0; i < size; ++i) {
+        term.push_back(kLower[random() % kLower.size()]);
+    }
+    if (capital) {
+        term[random() % size] = kUpper[random() % kUpper.size()];
+    }
+    return term;
+}
+
+// A term of one of the classes the filters tell apart, or a malformed one.
+std::string random_term(std::mt19937_64& random, bool malformed) {
+    if (malformed) {
+        std::string term = random() % 2 == 0 ? random_ascii(random, random() % 
2 == 0) : "";
+        term += invalid_pieces()[random() % invalid_pieces().size()];
+        if (random() % 2 == 0) {
+            term += unicode_pieces()[random() % unicode_pieces().size()];
+        }
+        return term;
+    }
+    switch (random() % 12) {
+    case 0:
+    case 1:
+        return random_ascii(random, false);
+    case 2:
+    case 3:
+        return random_ascii(random, true);
+    case 4:
+    case 5:
+        // One CJK character of three bytes.
+        return utf8_of(static_cast<UChar32>(0x3000 + random() % 0x7000));
+    case 6:
+        return "";
+    case 7:
+    case 8:
+    case 9:
+    case 10: {
+        std::string term;
+        const size_t pieces = 1 + random() % 4;
+        for (size_t i = 0; i < pieces; ++i) {
+            term += random() % 3 == 0 ? random_ascii(random, random() % 2 == 0)
+                                      : unicode_pieces()[random() % 
unicode_pieces().size()];
+        }
+        return term;
+    }
+    default: {
+        // A long term, longer than the inline buffer of an icu::UnicodeString.
+        std::string term;
+        const size_t pieces = 20 + random() % 60;
+        for (size_t i = 0; i < pieces; ++i) {
+            term += unicode_pieces()[random() % unicode_pieces().size()];
+        }
+        return term;
+    }
+    }
+}
+
+// One value in 1 to 4 batches of 1 to 300 tokens; a token is malformed with 
the given odds.
+Script random_script(std::mt19937_64& random, size_t malformed_per_mille) {
+    Script script(1 + random() % 4);
+    for (std::vector<ScriptedToken>& batch : script) {
+        batch.resize(1 + random() % 300);
+        for (ScriptedToken& token : batch) {
+            token.term = random_term(random, random() % 1000 < 
malformed_per_mille);
+            token.position_increment = static_cast<int32_t>(random() % 4);
+            token.in_batch = random() % 2 == 0;
+        }
+    }
+    return script;
+}
+
+using MakeFilter =
+        
std::function<std::unique_ptr<TextTokenStream>(std::unique_ptr<TextTokenStream>)>;
+
+// The tokens of the value `script` scripts, or the exception the filter threw.
+struct Outcome {
+    std::vector<CollectedToken> tokens;
+    bool threw = false;
+    int code = 0;
+    std::string message;
+
+    bool operator==(const Outcome&) const = default;
+};
+
+Outcome read(const Script& script, const MakeFilter& make_filter) {
+    auto stream = make_filter(std::make_unique<ScriptedBatchInput>(script));
+    Outcome outcome;
+    try {
+        outcome.tokens = collect_checked(*stream, "");
+    } catch (const Exception& error) {
+        outcome.threw = true;
+        outcome.code = error.code();
+        outcome.message = error.message();
+    }
+    return outcome;
+}
+
+size_t tokens_of(const Script& script) {
+    size_t tokens = 0;
+    for (const auto& batch : script) {
+        tokens += batch.size();
+    }
+    return tokens;
+}
+
+constexpr size_t kValues = 100;
+// The values of every third index may have malformed tokens.
+constexpr size_t kValuesWithMalformedTokens = (kValues + 2) / 3;
+
+// `make_filter` against the per-token `rewrite` on random values; those of 
every third index have
+// malformed tokens with the given odds. Returns how many values threw, so a 
caller can tell that
+// both kinds of value were met.
+size_t expect_matches_per_token(const MakeFilter& make_filter, const Rewrite& 
rewrite,
+                                size_t malformed_per_mille, uint64_t seed) {
+    std::mt19937_64 random(seed);
+    const MakeFilter per_token = [&](std::unique_ptr<TextTokenStream> in) {
+        return std::make_unique<PerTokenRewrite>(std::move(in), rewrite);
+    };
+    size_t threw = 0;
+    for (size_t value = 0; value < kValues; ++value) {
+        const Script script = random_script(random, value % 3 == 0 ? 
malformed_per_mille : 0);
+        const Outcome expected = read(script, per_token);
+        const Outcome actual = read(script, make_filter);
+        EXPECT_EQ(actual, expected) << "value " << value << " of " << 
tokens_of(script)
+                                    << " tokens in " << script.size() << " 
batches";
+        threw += expected.threw ? 1 : 0;
+    }
+    return threw;
+}
+
+TEST(OneToOneFilterTest, LowerCaseMatchesThePerTokenFilter) {
+    LowerCaseFilterFactory factory;
+    factory.initialize({});
+    // About one malformed token in each value that may have one: most of 
those values throw, at
+    // any token of any batch, and the others do not.
+    const size_t threw = expect_matches_per_token(
+            [&](std::unique_ptr<TextTokenStream> in) { return 
factory.create(std::move(in)); },
+            lower_case_per_token, 3, 20261104);
+    EXPECT_GT(threw, 0);
+    EXPECT_LT(threw, kValuesWithMalformedTokens);
+}
+
+TEST(OneToOneFilterTest, ASCIIFoldingMatchesThePerTokenFilter) {
+    ASCIIFoldingFilterFactory factory;
+    factory.initialize({});
+    // Malformed tokens never throw here: folding drops their stray bytes or 
keeps them.
+    const size_t threw = expect_matches_per_token(
+            [&](std::unique_ptr<TextTokenStream> in) { return 
factory.create(std::move(in)); },
+            fold_per_token, 100, 20261105);
+    EXPECT_EQ(threw, 0);
+}
+
+Settings setting_of(const std::string& key, const std::string& value) {
+    Settings settings;
+    settings.set(key, value);
+    return settings;
+}
+
+TEST(OneToOneFilterTest, ICUNormalizerMatchesThePerTokenFilter) {
+    // NFKC_CF, two other forms, and Elasticsearch's example of a set filter, 
which leaves the
+    // Swedish letters alone.
+    const std::vector<Settings> settings = {Settings(), setting_of("name", 
"nfd"),
+                                            setting_of("name", "nfkc"),
+                                            setting_of("unicode_set_filter", 
"[^åäöÅÄÖ]")};
+    uint64_t seed = 20261106;
+    for (const Settings& setting : settings) {
+        ICUNormalizerFilterFactory factory;
+        factory.initialize(setting);
+        const icu::Normalizer2& normalizer = *factory._normalizer;
+        const size_t threw = expect_matches_per_token(
+                [&](std::unique_ptr<TextTokenStream> in) { return 
factory.create(std::move(in)); },
+                [&](std::string_view term) { return 
normalize_per_token(normalizer, term); }, 100,
+                seed++);
+        EXPECT_EQ(threw, 0);
+    }
+}
+
+// A term a filter leaves as it is keeps its view of the input; a changed one 
points into the
+// term storage of the batch.
+void expect_views(const MakeFilter& make_filter,
+                  const std::vector<std::pair<std::string, 
std::optional<std::string>>>& cases) {
+    Script script(1);
+    for (const auto& [term, changed] : cases) {
+        script[0].push_back({.term = term, .position_increment = 1, .in_batch 
= false});
+    }
+    auto stream = make_filter(std::make_unique<ScriptedBatchInput>(script));
+    stream->reset("");
+    TokenBatch batch;
+    ASSERT_TRUE(stream->next_batch(batch));
+    ASSERT_EQ(batch.size(), cases.size());
+    for (size_t i = 0; i < cases.size(); ++i) {
+        SCOPED_TRACE(cases[i].first);
+        const TokenRef& token = batch.tokens()[i];
+        if (cases[i].second.has_value()) {
+            EXPECT_EQ(token.term(), *cases[i].second);
+            EXPECT_NE(token.data, script[0][i].term.data());
+        } else {
+            EXPECT_EQ(token.term(), cases[i].first);
+            EXPECT_EQ(token.data, script[0][i].term.data());
+        }
+    }
+    EXPECT_FALSE(stream->next_batch(batch));
+}
+
+TEST(OneToOneFilterTest, ASCIIFoldingKeepsTheViewsOfTermsItLeaves) {
+    ASCIIFoldingFilterFactory factory;
+    factory.initialize({});
+    // U+4E2D folds to itself; a stray byte without a character to fold is 
kept, and dropped along
+    // with folding one.
+    expect_views([&](std::unique_ptr<TextTokenStream> in) { return 
factory.create(std::move(in)); },
+                 {{"abc", std::nullopt},
+                  {"", std::nullopt},
+                  {"中", std::nullopt},
+                  {"a\xFF", std::nullopt},
+                  {"café", "cafe"},
+                  {"\xFF\xC3\x86", "AE"},
+                  {"⒇", "(20)"}});
+}
+
+TEST(OneToOneFilterTest, ICUNormalizerKeepsTheViewsOfTermsItLeaves) {
+    ICUNormalizerFilterFactory factory;
+    factory.initialize({});
+    expect_views([&](std::unique_ptr<TextTokenStream> in) { return 
factory.create(std::move(in)); },
+                 {{"abc", std::nullopt},
+                  {"", std::nullopt},
+                  {"中", std::nullopt},
+                  {"ABC", "abc"},
+                  {"fi", "fi"},
+                  {"Full", "full"}});
+}
+
+} // namespace
+} // namespace doris::segment_v2::inverted_index


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

Reply via email to