hello-stephen commented on code in PR #71435: URL: https://github.com/apache/doris/pull/71435#discussion_r4799364568
########## regression-test/suites/fault_injection_p0/test_segment_open_profile_scoring.groovy: ########## @@ -0,0 +1,68 @@ +// 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. + +import org.apache.doris.regression.action.ProfileAction + +suite("test_segment_open_profile_scoring", "nonConcurrent") { + sql "SET enable_profile = true" + sql "SET profile_level = 2" + sql "SET enable_sql_cache = false" + sql "SET enable_query_cache = false" + // The same logical scoring query exercises direct collection and the shared tablet + // collector. Disabling cache insertion only during load leaves fresh segments cold. + [false, true].each { parallel -> + sql "DROP TABLE IF EXISTS test_segment_open_profile_scoring" + sql """ + CREATE TABLE test_segment_open_profile_scoring ( + id BIGINT NOT NULL, content TEXT, + INDEX idx_content(content) USING INVERTED PROPERTIES("parser" = "english") + ) UNIQUE KEY(id) + DISTRIBUTED BY HASH(id) BUCKETS 1 + PROPERTIES ("replication_num" = "1", "enable_unique_key_merge_on_write" = "true", + "disable_auto_compaction" = "true") + """ + setBeConfigTemporary([disable_segment_cache: true]) { + (0..<3).each { batch -> + sql """ INSERT INTO test_segment_open_profile_scoring + SELECT ${batch} * 4096 + number, 'alpha beta' + FROM numbers("number" = "4096") """ + } + } + sql "SYNC" + sql "SET enable_parallel_scan = ${parallel}" + sql "SET parallel_scan_min_rows_per_scanner = 1024" + sql "SET parallel_scan_max_scanners_count = 16" + ["cold", "warm"].each { cache -> Review Comment: [P2] Set the cache and footer-check options during the measured queries. The insert block restores the original `disable_segment_cache` value, and nonConcurrent CI can randomize it to true. Those fresh segments then never enter the cache, so the warm read reports opens and fails the zero-open assertion. CI also enables segment-row consistency checks, which let the parallel builder open all three segments before BM25 collection and satisfy the totals without testing shared collection attribution. Temporarily enable cache insertion and disable footer verification for both measured queries, and check that the parallel case actually uses multiple scanners. ########## be/src/storage/rowset/beta_rowset_reader.cpp: ########## @@ -46,12 +60,224 @@ #include "storage/schema.h" #include "storage/segment/lazy_init_segment_iterator.h" #include "storage/segment/segment.h" +#include "storage/storage_layout.h" #include "storage/tablet/tablet_meta.h" #include "storage/tablet/tablet_schema.h" namespace doris { using namespace ErrorCode; +namespace { + +// Bound work for large IN lists: at most 64 range comparisons per candidate segment. +constexpr size_t MAX_SEGMENT_PRUNING_KEY_RANGES = 64; + +using SegmentKeyBuffer = std::basic_string<char, std::char_traits<char>, CustomStdAllocator<char>>; + +struct EncodedSegmentKeyRange { + std::optional<SegmentKeyBuffer> lower; + std::optional<SegmentKeyBuffer> upper; + bool include_lower; + bool include_upper; + bool full_varchar_key; +}; + +// Called only after comparable_key has checked the supported types. Unlike std::string, +// these buffers check and charge the query's limiter, including long VARCHAR IN endpoints. +void encode_segment_key(const RowCursor& key, SegmentKeyBuffer* bytes) { + const auto width = key.schema()->num_read_columns(); + size_t size = width; // One NULL/normal marker per column. + for (uint32_t i = 0; i < width; ++i) { + if (!key.field(i).is_null()) { + size += key.column(i)->type() == FieldType::OLAP_FIELD_TYPE_VARCHAR + ? key.field(i).get<TYPE_STRING>().size() + : key.column(i)->length(); + } + } + bytes->reserve(size); + for (uint32_t i = 0; i < width; ++i) { + const auto& field = key.field(i); + if (field.is_null()) { + bytes->push_back(KeyConsts::KEY_NULL_FIRST_MARKER); + continue; + } + bytes->push_back(KeyConsts::KEY_NORMAL_MARKER); + switch (key.column(i)->type()) { +#define ENCODE_INTEGER(FT) \ + case FieldType::FT: { \ + const auto value = StorageLayout<FieldType::FT>::to_storage( \ + field.get<storage_field_type_to_primitive_type(FieldType::FT)>()); \ + KeyCoderTraits<FieldType::FT>::full_encode_ascending_to(&value, bytes); \ + break; \ + } + ENCODE_INTEGER(OLAP_FIELD_TYPE_TINYINT) + ENCODE_INTEGER(OLAP_FIELD_TYPE_SMALLINT) + ENCODE_INTEGER(OLAP_FIELD_TYPE_INT) + ENCODE_INTEGER(OLAP_FIELD_TYPE_BIGINT) + ENCODE_INTEGER(OLAP_FIELD_TYPE_LARGEINT) +#undef ENCODE_INTEGER + case FieldType::OLAP_FIELD_TYPE_VARCHAR: { + const auto& value = field.get<TYPE_STRING>(); + bytes->append(value.data(), value.size()); + break; + } + default: + DORIS_CHECK(false) << "Unsupported segment pruning key"; + } + } +} + +// VARCHAR full encoding has no terminator. Only a final physical key column can be +// compared by length; e.g. ("a", 1) cannot be distinguished from ("a\\x01...", ...). +std::optional<bool> comparable_key(const RowCursor& key, const TabletSchema& written_schema) { + const size_t width = key.schema()->num_read_columns(); + if (width == 0 || width > written_schema.num_key_columns()) { + return std::nullopt; + } + bool full_varchar_key = false; + for (size_t i = 0; i < width; ++i) { + const auto& written = written_schema.column(i); + const auto* query = key.column(cast_set<uint32_t>(i)); + // Schema changes may replace a column at the same ordinal or change its encoding. + if (!written.is_key() || !query->is_key() || written.unique_id() < 0 || + written.unique_id() != query->unique_id() || written.type() != query->type() || + written.length() != query->length() || written.is_nullable() != query->is_nullable()) { + return std::nullopt; + } + switch (written.type()) { + case FieldType::OLAP_FIELD_TYPE_TINYINT: + case FieldType::OLAP_FIELD_TYPE_SMALLINT: + case FieldType::OLAP_FIELD_TYPE_INT: + case FieldType::OLAP_FIELD_TYPE_BIGINT: + case FieldType::OLAP_FIELD_TYPE_LARGEINT: + break; + case FieldType::OLAP_FIELD_TYPE_VARCHAR: + // PK extrema selected with a sequence suffix need not be logical VARCHAR extrema + // after stripping that suffix. Fixed-width prefixes do not have this ambiguity. + if (i + 1 != written_schema.num_key_columns() || written_schema.has_sequence_col()) { + return std::nullopt; + } + full_varchar_key = true; + break; + default: + return std::nullopt; + } + } + return full_varchar_key; +} + +DorisVector<EncodedSegmentKeyRange> prepare_segment_key_ranges(const RowsetMeta& meta, + const RowsetReaderContext& context, + const StorageReadOptions& options) { + const auto& written_schema = meta.tablet_schema(); + // Non-MoW linked schema changes keep bounds with the old key layout but save the new + // schema: dropping b from (a VARCHAR, b INT) leaves b's bytes in a's apparent bounds. + // MoW forbids dropping keys and rewrites rowsets when adding/reordering keys. + // Z-order first/last keys are not lexicographic extrema, just as its prefix seek is disabled. + if (!context.enable_unique_key_merge_on_write || !config::enable_segment_key_range_pruning || + context.reader_type != ReaderType::READER_QUERY || context.read_changelog || + context.rowid_conversion != nullptr || context.ann_topn_runtime || context.score_runtime || + context.collection_statistics || !written_schema || + written_schema->sort_type() != SortType::LEXICAL || + !written_schema->cluster_key_uids().empty() || meta.is_segments_key_bounds_aggregated() || + meta.get_segments_key_bounds().size() != meta.num_segments() || + options.key_ranges.empty() || options.key_ranges.size() > MAX_SEGMENT_PRUNING_KEY_RANGES) { + return {}; + } + // Keep the existing SegmentIterator eligibility for value-only projections. + const auto& columns = context.read_schema->columns(); + if (std::none_of(columns.begin(), columns.end(), + [](const TabletColumnPtr& col) { return col && col->is_key(); })) { + return {}; + } + DorisVector<EncodedSegmentKeyRange> ranges; + ranges.reserve(options.key_ranges.size()); + for (const auto& range : options.key_ranges) { + if ((range.lower_key == nullptr && range.upper_key == nullptr) || + (range.lower_key != nullptr && range.upper_key != nullptr && + range.lower_key->schema()->num_read_columns() != + range.upper_key->schema()->num_read_columns())) { + return {}; + } + EncodedSegmentKeyRange encoded {.lower = std::nullopt, + .upper = std::nullopt, + .include_lower = range.include_lower, + .include_upper = range.include_upper, + .full_varchar_key = false}; + auto encode = [&](const RowCursor* key, std::optional<SegmentKeyBuffer>& bytes) { + if (key == nullptr) { + return true; + } + auto mode = comparable_key(*key, *written_schema); + if (!mode.has_value()) { + return false; + } + encoded.full_varchar_key = *mode; + bytes.emplace(); + encode_segment_key(*key, &*bytes); Review Comment: [P2] Bound the memory used by optional key pruning. A 48-value IN list of 32 KiB VARCHARs fits the default scan-key limit but keeps about 3 MiB of encoded lower and upper bounds alive per active reader here, even when the rowset has one segment. The existing segment seek encodes one endpoint at a time. The new limiter test already shows this path failing with 2 MiB of headroom. Cap the scratch space by bytes and fall back to ordinary iteration for larger inputs, or compare the VARCHAR payload directly from the cursor. ########## be/src/exec/scan/olap_scanner.cpp: ########## @@ -1065,6 +1066,9 @@ void OlapScanner::_collect_profile_before_close() { stats.output_index_result_column_timer); COUNTER_UPDATE(local_state->_filtered_segment_counter, stats.filtered_segment_number); COUNTER_UPDATE(local_state->_total_segment_counter, stats.total_segment_number); + COUNTER_UPDATE(local_state->_segment_key_bounds_pruned_counter, + stats.segment_key_bounds_pruned); + COUNTER_UPDATE(local_state->_segment_open_counter, stats.segment_open_count); Review Comment: [P2] Publish segment counters when a scan stops before scanner EOS. A shared LIMIT can finish the scan context after several scanners each contribute part of the limit. `ScannerContext::get_block_from_queue` can park those scanners without calling `mark_to_need_to_close()`, so their opens and prunes never reach these counters. A late runtime filter can also discard the prepared reader that holds the shared BM25 collector's opens. Publish scanner-local deltas as work completes, including before releasing a prepared reader. ########## be/src/storage/rowset/beta_rowset_reader.cpp: ########## @@ -46,12 +60,224 @@ #include "storage/schema.h" #include "storage/segment/lazy_init_segment_iterator.h" #include "storage/segment/segment.h" +#include "storage/storage_layout.h" #include "storage/tablet/tablet_meta.h" #include "storage/tablet/tablet_schema.h" namespace doris { using namespace ErrorCode; +namespace { + +// Bound work for large IN lists: at most 64 range comparisons per candidate segment. +constexpr size_t MAX_SEGMENT_PRUNING_KEY_RANGES = 64; + +using SegmentKeyBuffer = std::basic_string<char, std::char_traits<char>, CustomStdAllocator<char>>; + +struct EncodedSegmentKeyRange { + std::optional<SegmentKeyBuffer> lower; + std::optional<SegmentKeyBuffer> upper; + bool include_lower; + bool include_upper; + bool full_varchar_key; +}; + +// Called only after comparable_key has checked the supported types. Unlike std::string, +// these buffers check and charge the query's limiter, including long VARCHAR IN endpoints. +void encode_segment_key(const RowCursor& key, SegmentKeyBuffer* bytes) { + const auto width = key.schema()->num_read_columns(); + size_t size = width; // One NULL/normal marker per column. + for (uint32_t i = 0; i < width; ++i) { + if (!key.field(i).is_null()) { + size += key.column(i)->type() == FieldType::OLAP_FIELD_TYPE_VARCHAR + ? key.field(i).get<TYPE_STRING>().size() + : key.column(i)->length(); + } + } + bytes->reserve(size); + for (uint32_t i = 0; i < width; ++i) { + const auto& field = key.field(i); + if (field.is_null()) { + bytes->push_back(KeyConsts::KEY_NULL_FIRST_MARKER); + continue; + } + bytes->push_back(KeyConsts::KEY_NORMAL_MARKER); + switch (key.column(i)->type()) { +#define ENCODE_INTEGER(FT) \ + case FieldType::FT: { \ + const auto value = StorageLayout<FieldType::FT>::to_storage( \ + field.get<storage_field_type_to_primitive_type(FieldType::FT)>()); \ + KeyCoderTraits<FieldType::FT>::full_encode_ascending_to(&value, bytes); \ + break; \ + } + ENCODE_INTEGER(OLAP_FIELD_TYPE_TINYINT) + ENCODE_INTEGER(OLAP_FIELD_TYPE_SMALLINT) + ENCODE_INTEGER(OLAP_FIELD_TYPE_INT) + ENCODE_INTEGER(OLAP_FIELD_TYPE_BIGINT) + ENCODE_INTEGER(OLAP_FIELD_TYPE_LARGEINT) +#undef ENCODE_INTEGER + case FieldType::OLAP_FIELD_TYPE_VARCHAR: { + const auto& value = field.get<TYPE_STRING>(); + bytes->append(value.data(), value.size()); + break; + } + default: + DORIS_CHECK(false) << "Unsupported segment pruning key"; + } + } +} + +// VARCHAR full encoding has no terminator. Only a final physical key column can be +// compared by length; e.g. ("a", 1) cannot be distinguished from ("a\\x01...", ...). +std::optional<bool> comparable_key(const RowCursor& key, const TabletSchema& written_schema) { + const size_t width = key.schema()->num_read_columns(); + if (width == 0 || width > written_schema.num_key_columns()) { + return std::nullopt; + } + bool full_varchar_key = false; + for (size_t i = 0; i < width; ++i) { + const auto& written = written_schema.column(i); + const auto* query = key.column(cast_set<uint32_t>(i)); + // Schema changes may replace a column at the same ordinal or change its encoding. + if (!written.is_key() || !query->is_key() || written.unique_id() < 0 || + written.unique_id() != query->unique_id() || written.type() != query->type() || + written.length() != query->length() || written.is_nullable() != query->is_nullable()) { + return std::nullopt; + } + switch (written.type()) { + case FieldType::OLAP_FIELD_TYPE_TINYINT: + case FieldType::OLAP_FIELD_TYPE_SMALLINT: + case FieldType::OLAP_FIELD_TYPE_INT: + case FieldType::OLAP_FIELD_TYPE_BIGINT: + case FieldType::OLAP_FIELD_TYPE_LARGEINT: + break; + case FieldType::OLAP_FIELD_TYPE_VARCHAR: + // PK extrema selected with a sequence suffix need not be logical VARCHAR extrema + // after stripping that suffix. Fixed-width prefixes do not have this ambiguity. + if (i + 1 != written_schema.num_key_columns() || written_schema.has_sequence_col()) { + return std::nullopt; + } + full_varchar_key = true; + break; + default: + return std::nullopt; + } + } + return full_varchar_key; +} + +DorisVector<EncodedSegmentKeyRange> prepare_segment_key_ranges(const RowsetMeta& meta, + const RowsetReaderContext& context, + const StorageReadOptions& options) { + const auto& written_schema = meta.tablet_schema(); + // Non-MoW linked schema changes keep bounds with the old key layout but save the new + // schema: dropping b from (a VARCHAR, b INT) leaves b's bytes in a's apparent bounds. + // MoW forbids dropping keys and rewrites rowsets when adding/reordering keys. + // Z-order first/last keys are not lexicographic extrema, just as its prefix seek is disabled. + if (!context.enable_unique_key_merge_on_write || !config::enable_segment_key_range_pruning || Review Comment: [P2] Synchronize reads of the live pruning flag. `DECLARE_mBool` declares a plain `bool`. `set_config` writes it under `mutable_string_config_lock`, but a scanner can read it here concurrently without that lock. Use the atomic publication pattern in `get_inverted_index_candidate_pushdown_ratio()` to make both startup and live updates visible safely. -- 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]
