Copilot commented on code in PR #62222:
URL: https://github.com/apache/doris/pull/62222#discussion_r3050195070
##########
be/src/exec/scan/scanner.cpp:
##########
@@ -123,6 +123,16 @@ Status Scanner::get_block_after_projects(RuntimeState*
state, Block* block, bool
Status Scanner::get_block(RuntimeState* state, Block* block, bool* eof) {
// only empty block should be here
DCHECK(block->rows() == 0);
+
+ // Early exit when the global shared scan limit is exhausted.
+ // This avoids unnecessary I/O when other scanners have already
+ // collected enough rows for the SQL LIMIT.
+ auto* shared_limit = _local_state->shared_scan_limit_ptr();
+ if (shared_limit && shared_limit->load(std::memory_order_acquire) <= 0) {
+ *eof = true;
+ return Status::OK();
+ }
Review Comment:
`shared_scan_limit` uses -1 as the sentinel for “no limit” (see
ScanOperatorX::_shared_scan_limit docs), but this early-exit treats any value
`<= 0` as exhausted. If `_shared_scan_limit` is -1, scanners will immediately
return EOF and queries without a SQL LIMIT can return zero rows. Please change
the checks to treat negative values as “unlimited” (do not early-exit) and only
stop when the counter is actually 0.
##########
be/src/exec/scan/scanner.cpp:
##########
@@ -168,6 +186,8 @@ Status Scanner::get_block(RuntimeState* state, Block*
block, bool* eof) {
// set eof to true if per scanner limit is reached
// currently for query: ORDER BY key LIMIT n
*eof = *eof || (_limit > 0 && _num_rows_return >= _limit);
+ // Also stop when the global shared scan limit is exhausted.
+ *eof = *eof || (shared_limit &&
shared_limit->load(std::memory_order_acquire) <= 0);
Review Comment:
This EOF condition also uses `<= 0` on the shared limit. With “-1 means no
limit”, this will force EOF for unlimited scans. After fixing the counter
semantics, this check should only stop when the shared limit is actually
exhausted (typically `== 0` for the limited case).
##########
be/src/exec/scan/scanner.cpp:
##########
@@ -156,6 +166,14 @@ Status Scanner::get_block(RuntimeState* state, Block*
block, bool* eof) {
}
// record rows return (after filter) for _limit check
_num_rows_return += block->rows();
+ // Decrement the global shared scan limit so that other scanners
+ // can observe the progress and stop early when the SQL LIMIT is
+ // satisfied. The counter may go negative when multiple scanners
+ // subtract concurrently; this is harmless because the operator's
+ // reached_limit() provides the authoritative truncation.
+ if (shared_limit && block->rows() > 0) {
+ shared_limit->fetch_sub(block->rows(),
std::memory_order_acq_rel);
Review Comment:
Using `fetch_sub()` here can drive the shared limit counter negative (e.g.
concurrent scanners), which collides with the existing “-1 means no limit”
sentinel and makes later `<= 0` checks ambiguous. Consider switching to a
CAS-based decrement that clamps at 0 for limited scans (and skips decrement
entirely when the counter is negative/unlimited), or use the existing
`ScannerContext::acquire_limit_quota()` logic to preserve the counter’s
semantics.
```suggestion
// satisfied. Preserve negative values as the existing "no limit"
// sentinel, and clamp limited scans at 0 so concurrent scanners
// cannot drive the counter into the sentinel range.
if (shared_limit && block->rows() > 0) {
int64_t current =
shared_limit->load(std::memory_order_acquire);
while (current > 0) {
const int64_t next = std::max<int64_t>(0, current -
block->rows());
if (shared_limit->compare_exchange_weak(current, next,
std::memory_order_acq_rel,
std::memory_order_acquire)) {
break;
}
}
```
##########
be/src/storage/rowset/rowset_reader_context.h:
##########
@@ -107,6 +107,10 @@ struct RowsetReaderContext {
// General limit pushdown for DUP_KEYS and UNIQUE_KEYS with MOW.
// Propagated from ReaderParams.general_read_limit.
int64_t general_read_limit = -1;
+
+ // Dynamic shared limit pointer from ScanOperatorX.
+ // See ReaderParams.shared_scan_limit for details.
+ std::atomic<int64_t>* shared_scan_limit = nullptr;
Review Comment:
This struct now uses `std::atomic<int64_t>` but the header does not include
`<atomic>`. Please add the include to keep the header self-contained (and avoid
relying on transitive includes).
##########
be/src/exec/operator/scan_operator.cpp:
##########
@@ -1044,6 +1044,11 @@ int64_t ScanLocalState<Derived>::limit_per_scanner() {
return _parent->cast<typename Derived::Parent>()._limit_per_scanner;
}
+template <typename Derived>
+std::atomic<int64_t>* ScanLocalState<Derived>::shared_scan_limit_ptr() {
+ return &_parent->cast<typename Derived::Parent>()._shared_scan_limit;
Review Comment:
`shared_scan_limit_ptr()` currently returns a non-null pointer
unconditionally. Since `_shared_scan_limit` is documented as “-1 means no
limit”, returning a pointer when the value is negative causes downstream code
to misinterpret “no limit” as “limit exhausted” (see Scanner/SegmentIterator
checks). Consider returning `nullptr` when `_shared_scan_limit` is negative (or
otherwise exposing an API that makes the “unlimited” case unambiguous).
```suggestion
auto& shared_scan_limit = _parent->cast<typename
Derived::Parent>()._shared_scan_limit;
return shared_scan_limit.load() < 0 ? nullptr : &shared_scan_limit;
```
##########
be/src/storage/segment/segment_iterator.cpp:
##########
@@ -2619,14 +2619,18 @@ Status SegmentIterator::_next_batch_internal(Block*
block) {
// If the row bitmap size is smaller than nrows_read_limit, there's no
need to reserve that many column rows.
uint32_t nrows_read_limit =
std::min(cast_set<uint32_t>(_row_bitmap.cardinality()),
_opts.block_row_max);
- if (_can_opt_topn_reads()) {
- nrows_read_limit = std::min(static_cast<uint32_t>(_opts.topn_limit),
nrows_read_limit);
+ if (_can_opt_limit_reads()) {
+ nrows_read_limit = _opts.read_limit.cap(nrows_read_limit);
+ } else if (_opts.read_limit.exhausted()) {
+ // Even without index optimization eligibility, stop reading when
+ // the global limit is fully exhausted — no more rows needed.
Review Comment:
With the new `read_limit.exhausted()` branch, `nrows_read_limit` can be
forced to 0 even when the scan is “unlimited” if the shared counter uses the -1
sentinel and `exhausted()` treats `<= 0` as exhausted. Please ensure the
shared-limit semantics are consistent end-to-end (negative = unlimited),
otherwise SegmentIterator may stop reading rows unexpectedly.
```suggestion
} else if (_opts.read_limit.local_limit >= 0 &&
_opts.read_limit.exhausted()) {
// Even without index optimization eligibility, stop reading when
// the global limit is fully exhausted — no more rows needed.
// Negative limits are treated as unlimited and must not force reads
to stop.
```
##########
be/test/storage/segment/segment_iterator_limit_opt_test.cpp:
##########
@@ -0,0 +1,142 @@
+// 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.
+
+#include <atomic>
+
+#include "gtest/gtest.h"
+#include "storage/olap_common.h"
+#include "storage/predicate/block_column_predicate.h"
+#include "storage/predicate/null_predicate.h"
+#include "storage/segment/segment_iterator.h"
+#include "storage/tablet/tablet_schema.h"
+
+namespace doris::segment_v2 {
+
+class SegmentIteratorLimitOptTest : public ::testing::Test {
+protected:
+ void SetUp() override {
+ TabletSchemaPB schema_pb;
+ schema_pb.set_keys_type(KeysType::DUP_KEYS);
+ auto* col = schema_pb.add_column();
+ col->set_unique_id(0);
+ col->set_name("k1");
+ col->set_type("INT");
+ col->set_is_key(true);
+ col->set_is_nullable(true);
+
+ _tablet_schema = std::make_shared<TabletSchema>();
+ _tablet_schema->init_from_pb(schema_pb);
+ _read_schema = std::make_shared<Schema>(_tablet_schema);
+ }
+
+ // Build a SegmentIterator with minimal opts for _can_opt_limit_reads()
testing.
+ // The segment pointer is null — only _opts and internal maps are accessed.
+ std::unique_ptr<SegmentIterator> make_iter() {
+ auto iter = std::make_unique<SegmentIterator>(nullptr, _read_schema);
+ iter->_opts.tablet_schema = _tablet_schema;
+ iter->_opts.stats = &_stats;
+ // delete_condition_predicates is default-constructed (empty)
+ return iter;
+ }
Review Comment:
This test directly accesses `SegmentIterator` private members (`_opts`,
`_column_predicate_index_exec_status`) and calls the private method
`_can_opt_limit_reads()`. As written it won’t compile unless you use the
existing test pattern (e.g. `#define private public` before including the
header, or declaring the test as a friend), or refactor to test via public APIs.
##########
be/src/storage/iterators.h:
##########
@@ -134,7 +134,43 @@ class StorageReadOptions {
// slots that cast may be eliminated in storage layer
std::map<std::string, DataTypePtr> target_cast_type_for_variants;
RowRanges row_ranges;
- size_t topn_limit = 0;
+
+ // Unified read limit for per-batch row cap in SegmentIterator.
+ //
+ // Two sources can contribute a limit:
+ // - local_limit : per-segment static cap (from topn or
general_read_limit)
+ // - global_remaining : cross-scanner dynamic budget (from ScanOperator
shared limit)
+ //
+ // When both are set, the effective limit is min(local_limit,
*global_remaining).
+ struct ReadLimit {
+ size_t local_limit = 0;
+ std::atomic<int64_t>* global_remaining = nullptr;
+
+ bool active() const { return local_limit > 0 || global_remaining !=
nullptr; }
+
+ // Cap max_rows by the effective limit.
+ uint32_t cap(uint32_t max_rows) const {
+ uint32_t limit = max_rows;
+ if (local_limit > 0 && local_limit < limit) {
+ limit = static_cast<uint32_t>(local_limit);
+ }
+ if (global_remaining != nullptr) {
+ int64_t remaining =
+ global_remaining->load(std::memory_order_acquire);
+ if (remaining >= 0 &&
+ remaining < static_cast<int64_t>(limit)) {
+ limit = static_cast<uint32_t>(remaining);
+ }
+ }
+ return limit;
+ }
+
+ // True when the global budget is fully exhausted (0 or negative).
+ bool exhausted() const {
+ return global_remaining != nullptr &&
+ global_remaining->load(std::memory_order_acquire) <= 0;
+ }
Review Comment:
`StorageReadOptions` now exposes `std::atomic` and `std::memory_order_*` in
this header, but `<atomic>` isn’t included here. Also, `ReadLimit::exhausted()`
currently treats any value `<= 0` as exhausted; that conflicts with the
established “-1 means no limit” semantics and can cause readers to stop
immediately when the pointer is set but unlimited. Please include `<atomic>`
and make `exhausted()` consistent with the sentinel/unlimited behavior (and
ideally keep the counter from going negative for the limited case).
##########
be/src/storage/tablet/tablet_reader.h:
##########
@@ -218,6 +218,12 @@ class TabletReader {
// When > 0, the storage layer (VCollectIterator) will stop reading
// after returning this many rows. -1 means no limit.
int64_t general_read_limit = -1;
+
+ // Pointer to the shared remaining-row budget maintained by
ScanOperatorX.
+ // Decremented by ScannerScheduler after each block is produced.
+ // Storage layer uses it as a dynamic hint to reduce I/O.
+ // nullptr means no dynamic limit. -1 means no limit.
+ std::atomic<int64_t>* shared_scan_limit = nullptr;
Review Comment:
This new field introduces `std::atomic<int64_t>` in a public header, but the
header doesn’t include `<atomic>`. Also, the comment says the budget is
“Decremented by ScannerScheduler”, but the decrement was moved into
`Scanner::get_block()` in this PR; please update the comment so it reflects the
current ownership/location of the decrement logic.
--
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]