Gabriel39 commented on code in PR #70708: URL: https://github.com/apache/doris/pull/70708#discussion_r4681665521
########## 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: The descriptor-byte variant retained in the latest review summary is now addressed in b8137876f8, in addition to the earlier count reservation. Final predicates/projections are not known during initialization, so optional ranges leave one maximum-sized descriptor (the existing 8 MiB per-plan ceiling) for every pending scan under both the 32 MiB source and 64 MiB statement caps. Mandatory cursors still use actual bytes even when those conservative reservations cannot all fit. This avoids rejecting many small scans, adding a planning wait, changing hard caps or revising a published plan. Early inputs in a large join can receive fewer optional ranges. The unfixed source fails three new cases with budget exhaustion: actual serialized provider descriptors under source pressure, multiple-source statement pressure, and concurrent optional admissions before a wide scan. Both planning orders now succeed. All 187 MongoDB FE and 166 connector SPI tests pass, including 256 tiny mandatory scans and refusal when mandatory descriptors themselves exceed the source cap. Full FE Checkstyle and whitespace checks pass. Fresh remote checks are requested; the earlier External success predates this FE change. -- 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]
