airborne12 commented on code in PR #70384:
URL: https://github.com/apache/doris/pull/70384#discussion_r4763409182


##########
be/src/storage/segment/segment_iterator.cpp:
##########
@@ -1166,6 +1168,75 @@ Status SegmentIterator::_apply_ann_topn_predicate() {
     return Status::OK();
 }
 
+void SegmentIterator::_reset_range_iterator() {
+    // TopN pruning can replace the bitmap between batches. Refresh the cached 
cardinality with
+    // the cursor so batch sizing does not use the larger range from before 
the bound arrived.
+    _row_bitmap_cardinality = _row_bitmap.cardinality();
+    if (_opts.read_orderby_key_reverse) {
+        _range_iter = 
std::make_unique<BackwardBitmapRangeIterator>(_row_bitmap);
+    } else {
+        _range_iter = std::make_unique<BitmapRangeIterator>(_row_bitmap);
+    }
+}
+
+Status SegmentIterator::_update_topn_runtime_filter_ranges() {
+    // Apply the first bound immediately and throttle later changes by raw 
rows read.
+    // A 40960-row delta is not enough; it must exceed the limit.
+    constexpr uint64_t update_threshold = 4096 * 10;
+    auto needs_update = [&](const TopNRuntimeFilter& filter) {
+        return filter.predicate->version() > filter.applied_version &&
+               (filter.applied_version == 0 ||
+                _topn_rows_read - filter.last_update_rows > update_threshold);
+    };
+    if (std::ranges::none_of(_topn_runtime_filters, needs_update)) {
+        return Status::OK();
+    }
+
+    SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_zonemap_ns);
+    roaring::Roaring remaining = _row_bitmap;
+    // Exclude already consumed rows BEFORE intersecting page ranges. For 
example, after reading
+    // [0,100), a surviving page [50,150) may only add [100,150) to the 
rebuilt forward iterator.
+    if (_opts.read_orderby_key_reverse) {
+        remaining.removeRange(_topn_read_position, num_rows());
+    } else {
+        remaining.removeRange(0, _topn_read_position);
+    }
+    const auto before = remaining.cardinality();
+    // The last returned batch may have exhausted the cursor before the 
producer publishes a
+    // tighter bound. There are no unread rows to test against page metadata 
in that case.
+    if (before == 0) {
+        return Status::OK();
+    }
+    for (auto& filter : _topn_runtime_filters) {
+        if (!needs_update(filter)) {
+            continue;
+        }
+        const auto snapshot = filter.predicate->snapshot();
+        DCHECK(snapshot.predicate != nullptr);
+        AndBlockColumnPredicate predicate;
+        predicate.add_column_predicate(
+                SingleColumnBlockPredicate::create_unique(snapshot.predicate));
+        RowRanges ranges = RowRanges::create_single(num_rows());
+        RETURN_IF_ERROR(
+                
_column_iterators[filter.predicate->column_id()]->get_row_ranges_by_zone_map(

Review Comment:
   This is at parity with master, where 
`be/src/storage/segment/segment_iterator.cpp:1314` 
(`_update_topn_runtime_filter_ranges`, called at the top of 
`_next_batch_internal` at `:3214`, master 6a1da3db536) does the same, so it is 
not introduced by this backport. The only difference in that function is 
`std::make_unique` vs `reset(new ...)`. `ColumnReader::_get_filtered_pages` / 
`_calculate_row_ranges` and `RowRanges::ranges_union` are the same pre-existing 
code on both branches.
   
   On the cost itself, the concern is valid for large segments:
   
   - **How often.** A refresh runs only when the shared predicate's version has 
moved (the heap bound got tighter) and more than 40960 rows were read since the 
last refresh, so a segment gets at most `rows_read / 40960` refreshes. With 
random order the bound soon stops moving and there are few refreshes. The worst 
case is the one described here: `k` falls as `id` rises, so the bound gets 
tighter in every batch and nothing unread is pruned.
   - **Work per refresh.** `ZoneMap::from_proto` plus the predicate check runs 
for all `P` pages of the column, including pages already read. Then 
`_calculate_row_ranges` adds each surviving page with `ranges_union`, which 
copies the whole list each time. This is O(S) when the surviving pages are 
contiguous, because they merge into one range, and O(S²) when they alternate 
with pruned pages.
   - **Rough size.** Data pages are 64 KB, so a page holds about 8K BIGINT 
values and `P ≈ N / 8192`, with about 5 pages read between refreshes.
     - N = 5M (memtable-flush size): P ≈ 610, up to ~120 refreshes, ~75K 
zone-map parses. In the worst fragmented case, about 2M range copies. That is 
small next to the scan.
     - N = 50M (a narrow 1 GB compaction segment): P ≈ 6.1K, up to ~1.2K 
refreshes, ~7.4M zone-map parses. In the worst fragmented case, the copies 
reach the order of 10⁹. That can cost more than the scan itself, but only when 
the bound keeps getting tighter for the whole segment.
   
   I think a small follow-up on master is worth doing, then picking it to 4.2:
   1. Make `_calculate_row_ranges` linear. The page indexes are in ascending 
order, so `row_ranges->add(...)` (which merges with the last range) can replace 
`ranges_union`. This also helps the existing zone-map pruning at init.
   2. Check only the pages that still overlap unread rows. Do not parse the 
pages before `_topn_read_position` again.
   3. Back off when a refresh prunes nothing: double the row threshold, and 
reset it when a refresh filters rows. The total refresh work then stays near 
linear in segment size.
   
   So this backport stays at parity with master, and the cost is a follow-up 
item for master.
   



-- 
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]

Reply via email to