924060929 commented on code in PR #70708: URL: https://github.com/apache/doris/pull/70708#discussion_r4674565946
########## 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: **[P2] Reserve one split per scan before allocating extra ranges.** I reproduced this with two collections on the same MongoDB 8.0.20 replica set, using `auto`, `file_split_size=1024`, and two FE scan providers sharing one statement scope. Planning the larger collection first gives it all 256 splits. The smaller collection then fails with `MongoDB statement/source split budget exhausted`. Reversing only the planning order succeeds with 1 + 255 splits. This makes a same-source join depend on which input is planned first. Could we reserve each participating scan’s minimum share before publishing optional ranges? A regression should exercise both planning orders under the same 256-split cap. ########## 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: **[P2] Account for the full metadata replies in the probe budget.** With `_id_` first and a partial index with a long filter later in the same batch, the driver received 75,351 BSON bytes from `listIndexes` on MongoDB 8.0.20. This `break` counted only the `_id_` entry, so the probe passed the 64 KiB index-metadata cap. The following `collStats` reply added 55,238 bytes that were also omitted. Including the 266-byte sample reply, `probe.sampleBytes()` reported just 312 bytes. Could we account for every index spec in the batch already fetched, and either fetch only the size statistic from the server or charge the full stats reply to the probe and statement budgets? ########## 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; + } + } + } + if (index == null) { + return new MongoSplitProbe(List.of(), -1, bytes, false); + } + Document stats = probeDatabase(table.getDatabase(), deadline, checkCancelled) + .runCommand(new Document("collStats", table.getName()).append("scale", 1)); + Number size = stats.get("size", Number.class); + long logicalBytes = size == null ? -1 : size.longValue(); + List<BsonValue> samples = new ArrayList<>(); + // Sampling an index prefix puts almost all increasing keys into the final range. + // Keep $sample first so MongoDB can use its random cursor, then retain only bounded + // fixed-width keys. Statistics tune cost only; they never narrow source coverage. + // Unsupported large strings/arrays become null before they can reach the FE. + Document type = new Document("$type", "$" + field); + Document supported = new Document("$in", List.of(type, List.of("int", "long", "objectId", "date"))); + Document projection = new Document("_id", 0).append("value", + new Document("$cond", List.of(supported, "$" + field, new Document("$literal", null)))); + // Do not shrink small-table requests below MongoDB's 5% random-cursor threshold. + // Its historical random cursor can stall on concurrently rewritten records; a bounded + // full sample of a small collection remains cheap and preserves the pinned timestamp. + var pipeline = List.of(new Document("$sample", new Document("size", rows)), Review Comment: **Skip sampling once `auto` has enough information to choose a single cursor.** At this point `collStats.size` is available, but the planner checks `small_collection` only after running this pipeline. With 10,000 documents and `file_split_size=33554432`, the FE returned one `small_collection` split. The MongoDB profiler recorded `COLLSCAN`, `docsExamined=10000` for the planning aggregate alone. Could we apply the existing size check before issuing `$sample`? A command-level test could verify that this case returns one split and sends no sampling aggregate. -- 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]
