Gabriel39 commented on code in PR #70708:
URL: https://github.com/apache/doris/pull/70708#discussion_r4674887571


##########
fe/fe-connector/fe-connector-mongodb/src/main/java/org/apache/doris/connector/mongodb/MongoRangePlanner.java:
##########
@@ -0,0 +1,401 @@
+// 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.
+
+package org.apache.doris.connector.mongodb;
+
+import org.apache.doris.connector.spi.ConnectorSession;
+import org.apache.doris.connector.spi.ConnectorStatementScope;
+import org.apache.doris.connector.spi.DorisConnectorException;
+import org.apache.doris.connector.spi.scan.ConnectorScanContext;
+import org.apache.doris.thrift.TMongoSnapshot;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.bson.BsonValue;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.function.Supplier;
+
+/** Complete planning precedes publication. Statement memos retain either that 
plan or its failure. */
+final class MongoRangePlanner {
+    private static final Logger LOG = 
LogManager.getLogger(MongoRangePlanner.class);
+    static final int SAMPLE_ROWS = 4096;
+    static final int PROBE_TIMEOUT_MS = 2000;
+    private static final long MAX_PLAN_DESCRIPTOR_BYTES = 8L * 1024 * 1024;
+    private final String memoKey = "mongodb.split.plan:" + UUID.randomUUID();
+    private final Supplier<MongoCatalogClient> client;
+    private final long probeTimeoutMs;
+
+    MongoRangePlanner(Supplier<MongoCatalogClient> client, long 
probeTimeoutMs) {
+        this.client = client;
+        this.probeTimeoutMs = probeTimeoutMs;
+    }
+
+    MongoSplitPlan plan(ConnectorSession session, MongoTableHandle table, 
TMongoSnapshot snapshot,
+            String preference, ConnectorScanContext context, long 
descriptorBytes) {
+        checkCancelled(session, context);
+        var options = session.getSessionProperties();
+        String strategy = options.getOrDefault("mongodb_split_strategy", 
"single");
+        if (!Set.of("single", "auto", "range").contains(strategy)) {
+            throw new IllegalArgumentException("Invalid 
mongodb_split_strategy");
+        }
+        if ("single".equals(strategy)) {
+            return MongoSplitPlan.single(1, 1, "single_strategy");
+        }
+        String field = options.getOrDefault("mongodb_split_field", "");
+        // Spelling out the default _id must retain its multi-scan contract, 
including joins.
+        boolean custom = !field.isEmpty() && !"_id".equals(field);
+        if (!custom) {
+            field = "_id";
+        }
+        if (!MongoPredicateTranslator.safePath(field) || field.isEmpty() || 
field.length() > 256) {
+            throw new IllegalArgumentException("MongoDB split field must be an 
unambiguous top-level field");
+        }
+        String selectedField = field;
+        Budget budget = 
session.getStatementScope().computeIfAbsent("mongodb.split.budget", 
Budget::new);
+        String tableKey = tableKey(session, table);
+        // Count fallback scans too: a view must not make a global custom 
field look unambiguous.
+        if (custom) {
+            budget.customField(tableKey);
+        }
+        Memo memo = session.getStatementScope().computeIfAbsent(tableKey, 
Memo::new);
+        return memo.get(session, context, () -> load(session, table, snapshot, 
preference, context,
+                strategy, selectedField, descriptorBytes, budget));
+    }
+
+    Optional<MongoSplitPlan> planned(ConnectorSession session, 
MongoTableHandle table) {
+        Memo memo = session.getStatementScope().getIfPresent(tableKey(session, 
table));
+        return memo == null ? Optional.empty() : memo.completed();
+    }
+
+    void freezeDiagnostics(ConnectorSession session, MongoTableHandle table, 
Map<String, String> properties) {
+        session.getStatementScope().computeIfAbsent(tableKey(session, table) + 
":diagnostics",
+                () -> Map.copyOf(properties));
+    }
+
+    Map<String, String> diagnostics(ConnectorSession session, MongoTableHandle 
table) {
+        Map<String, String> properties = session.getStatementScope()
+                .getIfPresent(tableKey(session, table) + ":diagnostics");
+        return properties == null ? Map.of() : properties;
+    }
+
+    private String tableKey(ConnectorSession session, MongoTableHandle table) {
+        // One provider can see several namespaces; never reuse another 
collection's bounds/admission.
+        return memoKey + ":" + session.getCatalogId() + ":" + 
table.getSchema().getVersion();
+    }
+
+    private MongoSplitPlan load(ConnectorSession session, MongoTableHandle 
table, TMongoSnapshot snapshot,
+            String preference, ConnectorScanContext context, String strategy, 
String field,
+            long descriptorBytes, Budget budget) {
+        int maximum = splitLimit(session);
+        validateSplitSizes(session);
+        int requested = Math.min(8, maximum);
+        // The default single strategy exits before this path; opted-in plans 
always reserve bytes.
+        assert descriptorBytes > 0 : "MongoDB range descriptor bytes must be 
positive";
+        int descriptorMaximum = (int) Math.min(maximum, 
MAX_PLAN_DESCRIPTOR_BYTES / descriptorBytes);
+        if (descriptorMaximum == 0) {
+            throw new DorisConnectorException("MongoDB split descriptor 
exceeds planning byte budget");
+        }
+        String source = snapshot == null ? "catalog:" + session.getCatalogId()
+                : snapshot.getSourceKind() + ":" + snapshot.getSourceId();
+        if (!"collection".equals(table.getObjectKind())) {
+            return fallback(strategy, requested, "unsupported_object", source, 
descriptorBytes, budget);
+        }
+        if (snapshot == null || session.getStatementScope() == 
ConnectorStatementScope.NONE) {
+            return fallback(strategy, requested, "snapshot_required", source, 
descriptorBytes, budget);
+        }
+        if (descriptorMaximum == 1) {
+            return single(requested, maximum == 1 ? "split_limit" : 
"descriptor_budget",
+                    source, descriptorBytes, budget);
+        }
+        long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(
+                Math.min(probeTimeoutMs, 
MongoSnapshot.remainingMillis(session)));
+        MongoSplitProbe probe;
+        try {
+            budget.acquireProbe(session, context, deadline);
+            try {
+                checkCancelled(session, context);
+                probe = client.get().probeSplits(table, field, preference, 
snapshot, SAMPLE_ROWS,
+                        remaining(session, context, deadline), () -> 
checkCancelled(session, context));
+                budget.sampled(probe.sampleBytes());
+            } finally {
+                budget.probes.release();
+            }
+        } catch (PlanningLimit limit) {
+            checkCancelled(session, context);
+            MongoSnapshot.remainingMillis(session);
+            // Keep diagnostics independent of connection settings and sampled 
source values.
+            LOG.debug("MongoDB range planning reached probe_budget: 
query_id={}, strategy={}, requested={}",
+                    session.getQueryId(), strategy, requested);
+            // Only optional pre-publication tuning can fall back. 
Cancellation, authorization,
+            // history and source errors must never be converted into a 
successful full scan.
+            return fallback(strategy, requested, "probe_budget", source, 
descriptorBytes, budget);
+        }
+        checkCancelled(session, context);
+        MongoSnapshot.remainingMillis(session);
+        long targetBytes = targetBytes(session, probe.logicalBytes());
+        long estimate = probe.logicalBytes() < 0 ? 8
+                : Math.max(1, probe.logicalBytes() / targetBytes + 
(probe.logicalBytes() % targetBytes == 0 ? 0 : 1));
+        requested = (int) Math.min(maximum, estimate);
+        if (!probe.indexed()) {
+            return fallback(strategy, requested, "missing_index", source, 
descriptorBytes, budget);
+        }
+        String family = family(probe.samples());
+        if (family.isEmpty()) {
+            return probe.samples().isEmpty()
+                    ? single(requested, "empty_sample", source, 
descriptorBytes, budget)
+                    : fallback(strategy, requested, "unsupported_type", 
source, descriptorBytes, budget);
+        }
+        if ("auto".equals(strategy) && probe.logicalBytes() < 0) {
+            return single(requested, "unknown_complement_cost", source, 
descriptorBytes, budget);
+        }
+        // Division avoids overflow when a valid shared split-size setting is 
near Long.MAX_VALUE.
+        if ("auto".equals(strategy) && probe.logicalBytes() / targetBytes < 2) 
{
+            return single(requested, "small_collection", source, 
descriptorBytes, budget);
+        }
+        int admitted = budget.admit(source, Math.min(requested, 
descriptorMaximum), descriptorBytes);

Review Comment:
   Fixed in 2191942fd2bd7821a71034b43e2c2c9ba8a0e35c. Opted-in scan providers 
now register one minimum cursor during the existing scan-properties 
initialization phase. FileQueryScanNode initialization loads these properties 
for every node before PhysicalPlanTranslator finalizes ranges. Admission 
preserves all pending minima before assigning optional ranges; snapshot scans 
through different catalogs share the source reservation group. Count 
reservations do no source I/O and do not freeze descriptor-byte estimates 
before the final predicates/projection are attached.
   
   The new regression mirrors that engine lifecycle and exercises both planning 
orders under the same 256-split cap; both now return 255 large-input ranges 
plus one small-input cursor. A concurrent admission test also preserves both 
minima across 16 schedules. The order test fails on the baseline with 
split-budget exhaustion.
   
   Actual MongoDB 8.0.20 replica-set provider/driver validation also returns 
255 + 1 in both orders at the same statement T, with sampling only for the 
large input. All 182 MongoDB FE tests, 166 upstream connector SPI tests and 
full FE Checkstyle pass. Full Doris SQL/BE execution and MongoDB 7/mongos were 
not rerun for this increment.



##########
fe/fe-connector/fe-connector-mongodb/src/main/java/org/apache/doris/connector/mongodb/MongoDriverCatalogClient.java:
##########
@@ -158,33 +170,176 @@ public BsonTimestamp selectSnapshot(String database, 
String collection, String p
         // with limit=1/batchSize=1, to discover T without transferring a 
potentially large source row.
         // The driver may request an extra wire batch slot to exhaust a 
limit-one cursor.
         try (ClientSession session = 
client.startSession(ClientSessionOptions.builder()
-                .causallyConsistent(false).snapshot(true).build());
-                MongoCursor<Document> cursor = snapshotDatabase(database, 
deadline).getCollection(collection)
-                        
.withReadPreference(properties.readPreferenceForSnapshot(preference)).find(session)
-                        .projection(new Document("_id", 0)
-                                .append("__doris_snapshot_probe__", new 
Document("$literal", 1)))
-                        .limit(1).batchSize(1).iterator()) {
-            cursor.hasNext();
-            // This is cursor.atClusterTime captured by the driver's 
snapshot-session protocol;
-            // operationTime, $clusterTime and the local wall clock are not 
substitutes for T.
-            BsonTimestamp timestamp = session.getSnapshotTimestamp();
-            if (timestamp == null) {
-                throw new DorisConnectorException("MongoDB snapshot probe did 
not return a snapshot timestamp");
+                .causallyConsistent(false).snapshot(true).build())) {
+            // Each blocking step must observe scan cancellation before 
starting the next one;
+            // an in-flight synchronous driver call still uses the original 
CSOT deadline.
+            try (MongoCursor<Document> cursor = snapshotDatabase(database, 
deadline, checkCancelled)
+                    
.getCollection(collection).withReadPreference(properties.readPreferenceForSnapshot(preference))
+                    .find(session).projection(new Document("_id", 0)
+                            .append("__doris_snapshot_probe__", new 
Document("$literal", 1)))
+                    .limit(1).batchSize(1).iterator()) {
+                checkSnapshot(deadline, checkCancelled);
+                cursor.hasNext();
+                checkSnapshot(deadline, checkCancelled);
+                // This is cursor.atClusterTime captured by the driver's 
snapshot-session protocol;
+                // operationTime, $clusterTime and the local wall clock are 
not substitutes for T.
+                BsonTimestamp timestamp = session.getSnapshotTimestamp();
+                if (timestamp == null) {
+                    throw new DorisConnectorException("MongoDB snapshot probe 
did not return a snapshot timestamp");
+                }
+                return timestamp;
             }
-            return timestamp;
         } catch (MongoException failure) {
             throw failure(failure);
         }
     }
 
-    private MongoDatabase snapshotDatabase(String database, long deadline) {
-        long remaining = deadline - System.nanoTime();
-        if (remaining <= 0) {
+    @Override
+    public MongoSplitProbe probeSplits(MongoTableHandle table, String field, 
String preference,
+            TMongoSnapshot snapshot, int rows, long timeoutMs, Runnable 
checkCancelled) {
+        long deadline = System.nanoTime() + 
TimeUnit.MILLISECONDS.toNanos(timeoutMs);
+        String index = null;
+        long bytes = 0;
+        try {
+            var collection = probeDatabase(table.getDatabase(), deadline, 
checkCancelled)
+                    .getCollection(table.getName());
+            // Fetch the bounded index inventory together: one RTT per index 
can exhaust the
+            // optional probe deadline before a later qualifying ordinary 
index is reached.
+            try (MongoCursor<Document> indexes = 
collection.listIndexes().batchSize(128)
+                    .timeoutMode(TimeoutMode.CURSOR_LIFETIME).iterator()) {
+                int count = 0;
+                while (true) {
+                    // hasNext may issue getMore. Cancellation must be checked 
before that request,
+                    // not only after it returns; the lifetime timeout also 
covers all cursor batches.
+                    checkProbe(deadline, checkCancelled);
+                    if (!indexes.hasNext()) {
+                        break;
+                    }
+                    checkProbe(deadline, checkCancelled);
+                    Document value = indexes.next();
+                    bytes += 
MongoSplitPlan.encode(value.toBsonDocument()).length;
+                    if (++count > 128 || bytes > 65536) {
+                        throw new MongoRangePlanner.PlanningLimit();
+                    }
+                    if (eligibleIndex(value, field)) {
+                        index = value.getString("name");
+                        break;

Review Comment:
   Fixed in 2191942fd2bd7821a71034b43e2c2c9ba8a0e35c. Index enumeration now 
drains and charges every specification already fetched in the current batch, 
including later specifications after the first qualifying index, before 
enforcing the 64 KiB index limit. The complete collStats BSON reply and 
complete sampling reply are charged incrementally as well. Already consumed 
replies stay charged when an optional deadline or budget rejects the probe; a 
successful return is no longer required for statement accounting.
   
   The shared counter saturates safely on oversize input. Queued probes recheck 
the statement budget while waiting and after acquiring a permit, returning that 
permit on rejection so spent budgets cannot start more source work.
   
   Regression coverage includes a qualifying first index followed by a 
75000-character partial-filter specification, a 55000-character statistics 
field, oversized statistics, rejected-reply charging and queued-budget 
exhaustion. Live MongoDB 8.0.20 rejects 75157 bytes of fetched index 
specifications before sampling. Another real probe reports and charges exactly 
37408 bytes, matching command-listener accounting of 46 index-specification 
bytes + the full 36971-byte collStats reply + the full 391-byte sample reply. 
All 182 MongoDB FE tests, 166 SPI tests and full FE Checkstyle pass. These live 
checks cover the provider/driver boundary, not full Doris SQL/BE execution.



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