hello-stephen commented on code in PR #71166:
URL: https://github.com/apache/doris/pull/71166#discussion_r4809551231
##########
be/src/storage/index/inverted/analysis/inverted_index_parser.cpp:
##########
@@ -141,6 +146,12 @@ bool should_write_index_norms(const TabletIndex&
index_meta) {
return true;
}
+bool should_write_sparse_index_norms(const TabletIndex& index_meta) {
+ // A variant path is usually absent from most rows of a segment, so dense
norms are mostly the
+ // default byte of rows that can never match.
+ return is_variant_path_index(index_meta) &&
config::inverted_index_sparse_norms_for_variant;
Review Comment:
[P2] Synchronize the read of the live sparse-norms setting. This is a plain
`bool`. The BE config endpoint writes it under `mutable_string_config_lock`,
while the memtable flush thread reads it here without that lock. Changing the
setting during an analyzed V3 VARIANT flush therefore creates a C++ data race.
Take a synchronized snapshot when the writer initializes.
##########
be/test/storage/segment/inverted_index_writer_test.cpp:
##########
@@ -2301,4 +2302,275 @@ TEST_F(InvertedIndexWriterTest,
NormsFollowIndexNormsProperty) {
config::inverted_index_skip_norms_for_variant =
original_skip_norms_for_variant;
}
+namespace {
+
+// FieldInfos::OMIT_NORMS in the .fnm field bits, and FlagBits::SPARSE_NORMS
in its flags.
+constexpr uint8_t kOmitNormsBit = 0x10;
+constexpr uint32_t kSparseNormsFlag = 1U << 1;
+constexpr uint32_t kNormsLayoutRows = 3000;
+
+// What a reader takes from one written index, for comparing the dense and
sparse norms layouts.
+struct NormsLayoutView {
+ std::vector<std::string> files;
+ bool has_norms = false;
+ std::optional<uint64_t> token_count;
+ // read through norms(field, bytes) before anything is cached, then
through norms(field)
+ std::vector<uint8_t> copied_norms;
+ std::vector<uint8_t> cached_norms;
+ // .frq, .prx, .tis and .tii, by file name
+ std::map<std::string, std::string> postings_files;
+ uint8_t fnm_bits = 0;
+ uint32_t fnm_flags = 0;
+
+ bool has_file_ending(std::string_view extension) const {
+ return std::any_of(files.begin(), files.end(),
+ [&](const std::string& file) { return
file.ends_with(extension); });
+ }
+};
+
+TabletIndex make_norms_index_meta(const std::string& index_suffix) {
+ TabletIndexPB index_meta_pb;
+ index_meta_pb.set_index_type(IndexType::INVERTED);
+ index_meta_pb.set_index_id(1);
+ index_meta_pb.set_index_name("test");
+ index_meta_pb.add_col_unique_id(1); // c2 column id
+ (*index_meta_pb.mutable_properties())["parser"] = "standard";
+ // positions make the writer compute the block-max data from the norms
+ (*index_meta_pb.mutable_properties())["support_phrase"] = "true";
+ TabletIndex index_meta;
+ index_meta.init_from_pb(index_meta_pb);
+ if (!index_suffix.empty()) {
+ index_meta.set_escaped_escaped_index_suffix_path(index_suffix);
+ }
+ return index_meta;
+}
+
+// Rows 0, 7, 14, ... are NULL. Rows 11, 22, ... that are not NULL hold "",
which an analyzed index
+// adds as a document without the field. Every other row holds "common" and up
to 39 more words, so
+// the norms include lengths above 23, which the norm byte rounds, and the
postings of "common" span
+// many skip blocks.
+std::string norms_layout_value(uint32_t row) {
+ static const std::vector<std::string> words = {"alpha", "beta", "gamma",
"delta"};
+ std::string value;
+ if (row % 11 != 0) {
+ value = "common";
+ for (uint32_t i = 0; i < row % 40; ++i) {
Review Comment:
[P3] Add a field length that actually rounds in the norm byte. This fixture
produces at most 40 tokens, all of which encode exactly. The first lossy length
is 41, which decodes to 40. As written, the token-count comparison could pass
if the sparse reader summed decoded norms. Include a 41-token value and assert
the exact token total separately from the decoded norms.
##########
regression-test/suites/inverted_index_p0/test_variant_subcolumn_sparse_norms.groovy:
##########
@@ -0,0 +1,238 @@
+// 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.
+
+// With inverted_index_sparse_norms_for_variant on, a variant path index of
storage format V3 keeps
+// its BM25 norms only for the rows that hold the path (.nrs) instead of one
byte for every row
+// (.nrm). Scores must not change: the same rows loaded with the config off,
on, and switched on
+// between two loads give the same score() results, also on a merge-on-write
table with deleted
+// rows, whose statistics subtract the norms of the hidden rows. An ordinary
column index keeps
+// dense norms.
+// It flips a BE config, so it must not share the cluster with other suites.
+suite("test_variant_subcolumn_sparse_norms", "p0,nonConcurrent") {
+ if (isCloudMode()) {
+ return
+ }
+
+ sql """ set enable_match_without_inverted_index = false """
+ sql """ set debug_variant_enable_typed_paths_to_sparse = false """
+ sql """ set debug_variant_enable_doc_mode = false """
+
+ // Rows without s_note leave gaps that dense norms fill with the default
byte. The values hold
+ // 1 to 30 words, so some lengths are above 23, where the norm byte rounds
the length.
+ def insertFirstBatch = { tableName ->
+ sql """ insert into ${tableName} values
+ (1, 'alpha database server', parse_to_variant('{"s_host":"alpha
database server", "o_text":"alpha"}')),
+ (2, 'beta server cluster', parse_to_variant('{"s_host":"beta
server cluster", "s_note":"alpha", "o_text":"alpha beta"}')),
+ (3, 'alpha', parse_to_variant('{"s_note":"alpha alpha beta",
"o_text":"gamma"}')),
+ (4, 'gamma', parse_to_variant('{"other":"alpha"}')),
+ (5, 'delta', parse_to_variant('{"s_note":"alpha beta gamma delta
alpha beta gamma delta alpha beta gamma delta alpha beta gamma delta alpha beta
gamma delta alpha beta gamma delta alpha beta", "o_text":"alpha alpha"}')),
+ (6, 'epsilon', parse_to_variant('{"s_host":"", "o_text":"beta"}'))
+ """
+ }
+ def insertSecondBatch = { tableName ->
+ sql """ insert into ${tableName} values
+ (7, 'alpha beta', parse_to_variant('{"s_note":"beta alpha",
"s_host":"alpha"}')),
+ (8, 'zeta', parse_to_variant('{"other":"beta"}')),
+ (9, 'alpha', parse_to_variant('{"s_note":"alpha gamma gamma gamma
gamma gamma", "o_text":"alpha gamma"}')),
+ (10, 'eta', parse_to_variant('{"s_host":"server alpha server",
"o_text":"delta"}')),
+ (11, 'theta', parse_to_variant('{"o_text":"alpha beta gamma delta
alpha beta gamma delta alpha beta gamma delta alpha beta gamma delta alpha beta
gamma delta alpha beta gamma delta alpha beta gamma"}')),
+ (12, 'iota', parse_to_variant('{"s_note":"alpha"}'))
+ """
+ }
+ def createDuplicateTable = { tableName ->
+ sql "DROP TABLE IF EXISTS ${tableName}"
+ sql """
+ CREATE TABLE ${tableName} (
+ id INT,
+ content TEXT,
+ v variant<
+ 's_*' : text,
+ PROPERTIES("variant_max_subcolumns_count"="0")
+ >,
+ INDEX idx_content (content) USING INVERTED PROPERTIES(
+ "parser"="english",
+ "support_phrase"="true"
+ ),
+ INDEX idx_v_s (v) USING INVERTED PROPERTIES(
+ "parser"="english",
+ "support_phrase"="true",
+ "field_pattern"="s_*"
+ ),
+ INDEX idx_v (v) USING INVERTED PROPERTIES(
+ "parser"="english",
+ "support_phrase"="true"
+ )
+ ) ENGINE=OLAP DUPLICATE KEY(id)
+ DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES (
+ "replication_allocation" = "tag.location.default: 1",
+ "disable_auto_compaction" = "true",
+ "inverted_index_storage_format" = "V3"
+ )
+ """
+ }
+
+ // the field_pattern index (s_note), the whole-column index's copy
(o_text), a phrase, and an
+ // ordinary column
+ def scoreQueries = { tableName ->
+ return [
+ """ select id, round(score(), 4) from ${tableName}
+ where cast(v["s_note"] as string) match_any "alpha"
+ order by score() desc, id limit 20 """,
+ """ select id, round(score(), 4) from ${tableName}
+ where cast(v["s_host"] as string) match_phrase "alpha database"
+ order by score() desc, id limit 20 """,
+ """ select id, round(score(), 4) from ${tableName}
+ where cast(v["o_text"] as string) match_any "alpha gamma"
+ order by score() desc, id limit 20 """,
+ """ select id, round(score(), 4) from ${tableName}
+ where content match_any "alpha"
+ order by score() desc, id limit 20 """,
+ ]
+ }
+ def scoresOf = { tableName -> scoreQueries(tableName).collect { query ->
sql query } }
+
+ def backendIdToIp = [:]
+ def backendIdToHttpPort = [:]
+ getBackendIpHttpPort(backendIdToIp, backendIdToHttpPort)
+ // For every index suffix, whether its files include a name ending with
`extension`, over all
+ // segments of the table.
+ def filesBySuffixOf = { tableName, extension ->
+ def tablet = sql_return_maparray("show tablets from ${tableName}")[0]
+ def (code, out, err) = http_client("GET", String.format(
+ "http://%s:%s/api/show_nested_index_file?tablet_id=%s",
+ backendIdToIp.get(tablet.BackendId),
backendIdToHttpPort.get(tablet.BackendId),
+ tablet.TabletId))
+ logger.info("show_nested_index_file of ${tableName} code=${code},
out=${out}, err=${err}")
+ assertEquals(0, code)
+ def found = [:]
+ for (def rowset in parseJson(out.trim()).rowsets) {
+ for (def segment in rowset.segments) {
+ for (def index in segment.indices) {
+ def hasFile = index.files.any { file ->
file.name.endsWith(extension) }
+ found[index.index_suffix] = (found[index.index_suffix] ?:
false) || hasFile
+ }
+ }
+ }
+ return found
+ }
+ def anyVariantPath = { found -> found.any { suffix, hasFile -> suffix !=
"" && hasFile } }
+
+ // dense norms, the baseline
+ createDuplicateTable("test_variant_sparse_norms_dense")
+ insertFirstBatch("test_variant_sparse_norms_dense")
+ insertSecondBatch("test_variant_sparse_norms_dense")
+ sql " sync "
+ def denseScores = scoresOf("test_variant_sparse_norms_dense")
+
+ order_qt_dense_s_note """
${scoreQueries("test_variant_sparse_norms_dense")[0]} """
+ order_qt_dense_s_host_phrase """
${scoreQueries("test_variant_sparse_norms_dense")[1]} """
+ order_qt_dense_o_text """
${scoreQueries("test_variant_sparse_norms_dense")[2]} """
+ order_qt_dense_content """
${scoreQueries("test_variant_sparse_norms_dense")[3]} """
+
+ setBeConfigTemporary([inverted_index_sparse_norms_for_variant: true]) {
+ // sparse norms for every segment
+ createDuplicateTable("test_variant_sparse_norms_sparse")
+ insertFirstBatch("test_variant_sparse_norms_sparse")
+ insertSecondBatch("test_variant_sparse_norms_sparse")
+ sql " sync "
+
+ def nrs = filesBySuffixOf("test_variant_sparse_norms_sparse", ".nrs")
+ def nrm = filesBySuffixOf("test_variant_sparse_norms_sparse", ".nrm")
+ logger.info("sparse table: .nrs by suffix ${nrs}, .nrm by suffix
${nrm}")
+ assertTrue(anyVariantPath(nrs))
+ assertFalse(anyVariantPath(nrm))
+ // the ordinary column index keeps dense norms
+ assertEquals(true, nrm[""])
+ assertEquals(false, nrs[""])
+
+ order_qt_sparse_s_note """
${scoreQueries("test_variant_sparse_norms_sparse")[0]} """
+ order_qt_sparse_s_host_phrase """
${scoreQueries("test_variant_sparse_norms_sparse")[1]} """
+ order_qt_sparse_o_text """
${scoreQueries("test_variant_sparse_norms_sparse")[2]} """
+ order_qt_sparse_content """
${scoreQueries("test_variant_sparse_norms_sparse")[3]} """
+ assertEquals(denseScores, scoresOf("test_variant_sparse_norms_sparse"))
+ }
+
+ // one dense segment and one sparse segment in the same tablet
+ createDuplicateTable("test_variant_sparse_norms_mixed")
+ insertFirstBatch("test_variant_sparse_norms_mixed")
+ setBeConfigTemporary([inverted_index_sparse_norms_for_variant: true]) {
+ insertSecondBatch("test_variant_sparse_norms_mixed")
+ }
+ sql " sync "
+
assertTrue(anyVariantPath(filesBySuffixOf("test_variant_sparse_norms_mixed",
".nrs")))
Review Comment:
[P3] Verify that both layouts are present for the same scored path. These
checks can pass with `.nrs` only on the unqueried `other` path and `.nrm` on
every path used by `score()`. Check for `.nrs` and `.nrm` on `s_note` or
`o_text` in different segments so the score comparison actually exercises mixed
layouts.
##########
contrib/clucene:
##########
@@ -1 +1 @@
-Subproject commit bb3b6ef0c3216f2913efb3d5fae0604a6d365bfd
+Subproject commit 294e26fb805dfbac325621358050db83531def68
Review Comment:
[P2] Pin the CLucene commit that landed on `apache:clucene`. The current
hash is the pre-merge PR head. The squash commit shares its parent and the
source branch was deleted, so a mirror of the upstream branch cannot obtain
this object from branch history. `build.sh` requires the exact gitlink hash.
[Landed CLucene
commit](https://github.com/apache/doris-thirdparty/commit/55d614d81f47dedbe8271967d249868a1dcd261e)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]