This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/branch-4.2 by this push:
new 0684162c4e0 branch-4.2: [opt](hive) Decouple partition metadata
batches from directory tasks (70247) (#70311)
0684162c4e0 is described below
commit 0684162c4e0f47397a5ed16d2cc7db1b50d19aa4
Author: 924060929 <[email protected]>
AuthorDate: Fri Nov 27 15:26:58 2026 +0800
branch-4.2: [opt](hive) Decouple partition metadata batches from directory
tasks (70247) (#70311)
cherry pick from #70247
---
.../apache/doris/common/util/FairTaskExecutor.java | 10 +
.../doris/datasource/FederationBackendPolicy.java | 16 +
.../apache/doris/datasource/FileQueryScanNode.java | 6 +
.../org/apache/doris/datasource/SplitProducer.java | 30 ++
.../doris/datasource/hive/HMSCachedClient.java | 6 +
.../datasource/hive/HiveExternalMetaCache.java | 33 +-
.../datasource/hive/ThriftHMSCachedClient.java | 6 +-
.../hive/source/HivePartitionBatchLoader.java | 353 +++++++++++++
.../doris/datasource/hive/source/HiveScanNode.java | 207 ++++++--
.../doris/common/util/FairTaskExecutorTest.java | 27 +
.../apache/doris/datasource/SplitProducerTest.java | 114 ++++
.../datasource/hive/HiveMetaStoreCacheTest.java | 86 +++
.../hive/source/HivePartitionBatchLoaderTest.java | 586 +++++++++++++++++++++
.../hive/source/HivePartitionStreamingTest.java | 440 ++++++++++++++++
.../hive/source/HiveStreamingSplitTest.java | 9 +
.../doris/planner/FederationBackendPolicyTest.java | 119 +++++
16 files changed, 2014 insertions(+), 34 deletions(-)
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/common/util/FairTaskExecutor.java
b/fe/fe-core/src/main/java/org/apache/doris/common/util/FairTaskExecutor.java
index c525db2b19a..622744fd821 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/common/util/FairTaskExecutor.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/common/util/FairTaskExecutor.java
@@ -192,6 +192,16 @@ public final class FairTaskExecutor implements Closeable {
}
}
+ /** Remove a queued task already completed by its submitting reader,
or cancelled before execution. */
+ public void remove(Runnable task) {
+ for (Entry entry : pending) {
+ if (entry.task == task && pending.remove(entry)) {
+ queued.decrementAndGet();
+ notifySpace();
+ }
+ }
+ }
+
public void removeSpaceListener(Runnable listener) {
synchronized (admissionLock) {
spaceListeners.remove(listener);
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/FederationBackendPolicy.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/FederationBackendPolicy.java
index 2ac01065bbb..0d002cbe399 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/datasource/FederationBackendPolicy.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/FederationBackendPolicy.java
@@ -250,6 +250,22 @@ public class FederationBackendPolicy {
for (List<Backend> backendList : backendMap.values()) {
backends.addAll(backendList);
}
+ if (backends.size() == 1 &&
splits.stream().allMatch(Split::isRemotelyAccessible)) {
+ // Every remotely readable split has the same owner. Avoid
per-split hashing,
+ // candidate allocation and weight-map updates under the batch
assignment lock.
+ // Local-only splits still need the locality checks in the general
path below.
+ Backend backend = backends.get(0);
+ long weight = 0;
+ for (Split split : splits) {
+ weight = Math.addExact(weight,
split.getSplitWeight().getRawValue());
+ split.setAlternativeHosts(Collections.emptyList());
+ }
+ assignment.putAll(backend, splits);
+ if (!splits.isEmpty()) {
+ assignedWeightPerBackend.put(backend,
Math.addExact(assignedWeightPerBackend.get(backend), weight));
+ }
+ return assignment;
+ }
ResettableRandomizedIterator<Backend> randomCandidates = new
ResettableRandomizedIterator<>(backends);
// optimizedLocalScheduling enables prioritized assignment of splits
to local nodes when splits contain
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/FileQueryScanNode.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/FileQueryScanNode.java
index c9bcaf85e1b..880bf9e3abf 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/datasource/FileQueryScanNode.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/FileQueryScanNode.java
@@ -912,6 +912,12 @@ public abstract class FileQueryScanNode extends
FileScanNode {
: scanTaskLease.group(false);
}
+ protected Executor getMetadataTaskExecutor() {
+ return scanTaskLease == null
+ ?
Env.getCurrentEnv().getExtMetaCacheMgr().getScheduleExecutor()
+ : scanTaskLease.group(true);
+ }
+
protected boolean isScanTaskLeaseClosed() {
return scanTaskLease != null && scanTaskLease.isClosed();
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/SplitProducer.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/SplitProducer.java
index dff653ad9b6..b050ba5ed90 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/datasource/SplitProducer.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/datasource/SplitProducer.java
@@ -32,6 +32,7 @@ import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
@@ -50,6 +51,10 @@ public class SplitProducer implements Runnable, Closeable {
public interface BatchSource extends Closeable {
List<Split> getNextBatch() throws Exception;
+ default CompletableFuture<Void> isBlocked() {
+ return null;
+ }
+
@Override
default void close() throws IOException {
}
@@ -70,6 +75,7 @@ public class SplitProducer implements Runnable, Closeable {
private Iterator<Map.Entry<Backend, Collection<Split>>> pending =
Collections.emptyIterator();
private Backend pendingBackend;
private Deque<TScanRangeLocations> pendingRanges;
+ private CompletableFuture<Void> waitingForSource;
public SplitProducer(SplitAssignment assignment, Executor executor,
BatchSource source,
Consumer<Exception> completion) {
@@ -145,8 +151,15 @@ public class SplitProducer implements Runnable, Closeable {
return false;
}
if (pendingRanges == null && !pending.hasNext()) {
+ if (awaitSource()) {
+ return false;
+ }
List<Split> batch = source.getNextBatch();
if (batch.isEmpty()) {
+ // A dependency, including one completed during the read,
means retry rather than EOF.
+ if (source.isBlocked() != null) {
+ return !awaitSource();
+ }
complete(null);
return false;
}
@@ -173,6 +186,22 @@ public class SplitProducer implements Runnable, Closeable {
return false;
}
+ private boolean awaitSource() {
+ CompletableFuture<Void> dependency = source.isBlocked();
+ if (dependency == null) {
+ return false;
+ }
+ if (dependency.isDone()) {
+ dependency.join();
+ return false;
+ }
+ if (waitingForSource != dependency) {
+ waitingForSource = dependency;
+ dependency.whenComplete((unused, error) -> schedule());
+ }
+ return true;
+ }
+
private void complete(Exception failure) {
synchronized (scheduleLock) {
if (completed) {
@@ -191,6 +220,7 @@ public class SplitProducer implements Runnable, Closeable {
assignment.removeCloseable(this);
pending = Collections.emptyIterator();
pendingRanges = null;
+ waitingForSource = null;
try {
source.close();
} catch (Exception e) {
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/HMSCachedClient.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/HMSCachedClient.java
index 9a3b631899e..d6151e2ad80 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/HMSCachedClient.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/HMSCachedClient.java
@@ -41,6 +41,12 @@ import java.util.function.Function;
* Currently, we support obtain hive metadata from thrift protocol and JDBC
protocol.
*/
public interface HMSCachedClient {
+ int DEFAULT_PARTITION_BATCH_SIZE = 5000;
+
+ default int getPartitionBatchSize() {
+ return DEFAULT_PARTITION_BATCH_SIZE;
+ }
+
Database getDatabase(String dbName);
List<String> getAllDatabases();
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/HiveExternalMetaCache.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/HiveExternalMetaCache.java
index 6432f1ebf13..76f65a03fc6 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/HiveExternalMetaCache.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/HiveExternalMetaCache.java
@@ -679,11 +679,36 @@ public class HiveExternalMetaCache extends
AbstractExternalMetaCache {
return getAllPartitions(dorisTable, partitionValuesList, false);
}
+ /** Cache-only scan probe. A miss must not perform remote I/O on the split
producer. */
+ public Optional<List<HivePartition>> getCachedPartitions(NameMapping
nameMapping,
+ List<List<String>> partitionValuesList) {
+ MetaCacheEntry<PartitionCacheKey, HivePartition> entry =
partitionEntry.get(nameMapping.getCtlId());
+ List<HivePartition> partitions = new
ArrayList<>(partitionValuesList.size());
+ for (List<String> values : partitionValuesList) {
+ HivePartition partition = entry.getIfPresent(new
PartitionCacheKey(nameMapping, values));
+ if (partition == null) {
+ return Optional.empty();
+ }
+ partitions.add(partition);
+ }
+ return Optional.of(partitions);
+ }
+
+ /** Load one bounded scan batch, allowing partitions dropped after pruning
to be absent. */
+ public List<HivePartition> getExistingPartitionsWithCache(NameMapping
nameMapping,
+ List<List<String>> partitionValuesList) {
+ return getAllPartitions(nameMapping, partitionValuesList, true, true);
+ }
+
private List<HivePartition> getAllPartitions(ExternalTable dorisTable,
List<List<String>> partitionValuesList,
boolean withCache) {
+ return getAllPartitions(dorisTable.getOrBuildNameMapping(),
partitionValuesList, withCache, false);
+ }
+
+ private List<HivePartition> getAllPartitions(NameMapping nameMapping,
+ List<List<String>> partitionValuesList, boolean withCache, boolean
ignoreMissing) {
long start = System.currentTimeMillis();
- NameMapping nameMapping = dorisTable.getOrBuildNameMapping();
long catalogId = nameMapping.getCtlId();
List<PartitionCacheKey> keys = partitionValuesList.stream()
.map(p -> new PartitionCacheKey(nameMapping, p))
@@ -714,7 +739,11 @@ public class HiveExternalMetaCache extends
AbstractExternalMetaCache {
HivePartition partition = resolved.get(key);
// A key the bulk load did not return (partition dropped
remotely) falls back to the
// per-key loader, preserving the original single-load
not-found error for that partition.
- partitions.add(partition != null ? partition :
partitionEntry.get(key));
+ if (partition != null) {
+ partitions.add(partition);
+ } else if (!ignoreMissing) {
+ partitions.add(partitionEntry.get(key));
+ }
}
} else {
partitions = new ArrayList<>(loadPartitions(keys).values());
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/ThriftHMSCachedClient.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/ThriftHMSCachedClient.java
index 0344673a432..f00ca30ff31 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/ThriftHMSCachedClient.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/ThriftHMSCachedClient.java
@@ -102,7 +102,6 @@ public class ThriftHMSCachedClient implements
HMSCachedClient {
/** Maximum partition names sent by one getPartitionsByNames RPC; a
`hive.` catalog property. */
public static final String PARTITION_BATCH_SIZE_KEY =
"hive.hms_partitions_batch_size_per_rpc";
- public static final int DEFAULT_PARTITION_BATCH_SIZE = 5000;
public ThriftHMSCachedClient(HiveConf hiveConf, int poolSize,
ExecutionAuthenticator executionAuthenticator) {
this(hiveConf, poolSize, executionAuthenticator, new
DefaultMetaStoreClientProvider());
@@ -119,6 +118,11 @@ public class ThriftHMSCachedClient implements
HMSCachedClient {
this.partitionBatchSize = parsePartitionBatchSize(hiveConf);
}
+ @Override
+ public int getPartitionBatchSize() {
+ return partitionBatchSize;
+ }
+
private static int parsePartitionBatchSize(HiveConf hiveConf) {
return parsePartitionBatchSize(hiveConf == null ? null :
hiveConf.get(PARTITION_BATCH_SIZE_KEY));
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/source/HivePartitionBatchLoader.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/source/HivePartitionBatchLoader.java
new file mode 100644
index 00000000000..020445685ad
--- /dev/null
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/source/HivePartitionBatchLoader.java
@@ -0,0 +1,353 @@
+// 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.datasource.hive.source;
+
+import org.apache.doris.common.util.FairTaskExecutor;
+import org.apache.doris.datasource.hive.HivePartition;
+
+import java.io.Closeable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executor;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BooleanSupplier;
+import java.util.function.Function;
+
+/**
+ * One scan's serial HMS producer. Readers claim small directory batches from
one bounded result list.
+ * Claiming its last slice permits one next metadata batch, overlapping HMS
with directory work without
+ * waiting for children or accumulating an unbounded queue. Large cache probes
are queued separately
+ * from remote reads, so an idle reader can help its own cache probe without
doing remote I/O.
+ */
+final class HivePartitionBatchLoader implements Closeable {
+ private static final int INITIAL_BATCH_SIZE = 16;
+ private final Executor scheduler;
+ private final BooleanSupplier keepRunning;
+ private final List<List<String>> partitionValues;
+ private final int maxBatchSize;
+ private final Function<List<List<String>>, Optional<List<HivePartition>>>
cached;
+ private final Function<List<List<String>>, List<HivePartition>> loader;
+ // Serializes synchronous cache hits and inline/offline executors without
recursive submission.
+ private final AtomicInteger pumping = new AtomicInteger();
+ // All fields below are guarded by this. I/O, scheduler calls and future
completion run outside it.
+ private int nextPartition;
+ private List<HivePartition> ready = Collections.emptyList();
+ private int nextReady;
+ private CompletableFuture<Void> available = new CompletableFuture<>();
+ private LoadTask current;
+ private Throwable failure;
+ private int readers;
+
+ HivePartitionBatchLoader(Executor scheduler, BooleanSupplier keepRunning,
+ List<List<String>> partitionValues, int maxBatchSize, int readers,
+ Function<List<List<String>>, Optional<List<HivePartition>>> cached,
+ Function<List<List<String>>, List<HivePartition>> loader) {
+ if (maxBatchSize <= 0 || readers <= 0) {
+ throw new IllegalArgumentException("Batch size and reader count
must be positive");
+ }
+ this.scheduler = scheduler;
+ this.keepRunning = keepRunning;
+ this.partitionValues = partitionValues;
+ this.maxBatchSize = maxBatchSize;
+ this.readers = readers;
+ this.cached = cached;
+ this.loader = loader;
+ }
+
+ private void checkCancelled() {
+ if (!keepRunning.getAsBoolean()) {
+ throw new CancellationException("Split generation stopped");
+ }
+ }
+
+ @Override
+ public void close() {
+ fail(new CancellationException("Split generation stopped"));
+ }
+
+ CompletableFuture<Void> isBlocked() {
+ pump();
+ LoadTask task;
+ synchronized (this) {
+ task = current;
+ }
+ if (task != null) {
+ task.helpCacheProbe();
+ }
+ synchronized (this) {
+ return failure != null || (ready.isEmpty() && (current != null ||
nextPartition < partitionValues.size()))
+ ? available : null;
+ }
+ }
+
+ synchronized boolean isFinished() {
+ return failure == null && ready.isEmpty() && current == null &&
nextPartition == partitionValues.size();
+ }
+
+ List<HivePartition> take(int size) {
+ List<HivePartition> result;
+ synchronized (this) {
+ if (failure != null) {
+ throw new CompletionException(failure);
+ }
+ if (ready.isEmpty()) {
+ return Collections.emptyList();
+ }
+ int end = nextReady + Math.min(size, ready.size() - nextReady);
+ // Own a small reference array: a slow reader must not retain an
entire completed HMS batch.
+ result = new ArrayList<>(ready.subList(nextReady, end));
+ nextReady = end;
+ if (nextReady == ready.size()) {
+ ready = Collections.emptyList();
+ nextReady = 0;
+ available = new CompletableFuture<>();
+ }
+ }
+ pump();
+ return result;
+ }
+
+ void readerClosed() {
+ boolean last;
+ synchronized (this) {
+ last = --readers == 0;
+ }
+ if (last) {
+ fail(new CancellationException("All partition readers closed"));
+ }
+ }
+
+ private void pump() {
+ if (pumping.getAndIncrement() != 0) {
+ return;
+ }
+ int missed = 1;
+ do {
+ LoadTask task = null;
+ synchronized (this) {
+ if (failure == null && current == null && ready.isEmpty() &&
nextPartition < partitionValues.size()) {
+ int size = nextPartition == 0 ?
Math.min(INITIAL_BATCH_SIZE, maxBatchSize) : maxBatchSize;
+ int end = nextPartition + Math.min(size,
partitionValues.size() - nextPartition);
+ task = new LoadTask(partitionValues.subList(nextPartition,
end));
+ nextPartition = end;
+ current = task;
+ }
+ }
+ if (task != null) {
+ try {
+ checkCancelled();
+ if (task.deferredCacheProbe) {
+ // Return the directory slice before walking the next
large cached batch.
+ task.cacheProbe.admit();
+ } else {
+ Optional<List<HivePartition>> hit =
cached.apply(task.batch);
+ if (hit.isPresent()) {
+ publish(task, hit.get());
+ } else {
+ task.remoteLoad.admit();
+ }
+ }
+ } catch (Throwable e) {
+ fail(e);
+ }
+ }
+ missed = pumping.addAndGet(-missed);
+ } while (missed != 0);
+ }
+
+ private void publish(LoadTask task, List<HivePartition> partitions) {
+ CompletableFuture<Void> signal = null;
+ boolean empty;
+ synchronized (this) {
+ if (failure != null) {
+ return;
+ }
+ current = null;
+ ready = partitions;
+ empty = ready.isEmpty();
+ if (!empty || nextPartition == partitionValues.size()) {
+ signal = available;
+ }
+ }
+ task.complete(null);
+ if (signal != null) {
+ signal.complete(null);
+ }
+ if (empty) {
+ pump();
+ }
+ }
+
+ private void fail(Throwable cause) {
+ CompletableFuture<Void> signal;
+ LoadTask task;
+ synchronized (this) {
+ if (failure != null) {
+ return;
+ }
+ failure = cause;
+ ready = Collections.emptyList();
+ if (available.isDone()) {
+ available = new CompletableFuture<>();
+ }
+ signal = available;
+ task = current;
+ current = null;
+ }
+ signal.completeExceptionally(cause);
+ if (task != null) {
+ task.completeExceptionally(cause);
+ }
+ }
+
+ private final class LoadTask extends CompletableFuture<Void> {
+ private final List<List<String>> batch;
+ private final boolean deferredCacheProbe;
+ private final ScheduledStage cacheProbe;
+ private final ScheduledStage remoteLoad;
+
+ private LoadTask(List<List<String>> batch) {
+ this.batch = batch;
+ this.deferredCacheProbe = batch.size() > INITIAL_BATCH_SIZE;
+ this.remoteLoad = new ScheduledStage(() -> {
+ List<HivePartition> partitions = loader.apply(batch);
+ checkCancelled();
+ publish(this, partitions);
+ });
+ this.cacheProbe = new ScheduledStage(() -> {
+ Optional<List<HivePartition>> hit = cached.apply(batch);
+ // A cancellation during a cache miss must not start another
HMS request.
+ checkCancelled();
+ if (hit.isPresent()) {
+ publish(this, hit.get());
+ } else {
+ remoteLoad.admit();
+ }
+ });
+ whenComplete((unused, error) -> {
+ cacheProbe.cancel(false);
+ remoteLoad.cancel(false);
+ });
+ }
+
+ private void helpCacheProbe() {
+ if (deferredCacheProbe) {
+ // FutureTask elects one executor, even if a metadata worker
dequeues it concurrently.
+ // Helpers only probe the cache; a miss submits remoteLoad and
returns without waiting.
+ cacheProbe.run();
+ }
+ }
+
+ private final class ScheduledStage extends FutureTask<Void> {
+ private final AtomicInteger admitting = new AtomicInteger();
+ private boolean admitted;
+ private final Runnable onSpace = this::admit;
+
+ private ScheduledStage(Runnable action) {
+ super(() -> {
+ ClassLoader previous =
Thread.currentThread().getContextClassLoader();
+ try {
+
Thread.currentThread().setContextClassLoader(HivePartitionBatchLoader.class.getClassLoader());
+ checkCancelled();
+ if (!LoadTask.this.isDone()) {
+ action.run();
+ }
+ return null;
+ } finally {
+ Thread.currentThread().setContextClassLoader(previous);
+ }
+ });
+ }
+
+ private void admit() {
+ // Capacity callbacks can race admission, including inline
notification.
+ if (admitting.getAndIncrement() != 0) {
+ return;
+ }
+ int missed = 1;
+ do {
+ // Cancelling one stage can synchronously notify another
stage's capacity callback.
+ if (!isDone() && !LoadTask.this.isDone() && !admitted) {
+ try {
+ if (scheduler instanceof FairTaskExecutor.Group) {
+ admitted = ((FairTaskExecutor.Group)
scheduler).tryExecute(
+ this, this::setException, onSpace);
+ } else {
+ scheduler.execute(this);
+ admitted = true;
+ }
+ if (admitted) {
+ removeSpaceListener();
+ }
+ } catch (RuntimeException e) {
+ setException(e);
+ }
+ }
+ if (isDone()) {
+ removeSpaceListener();
+ removeFromQueue();
+ }
+ missed = admitting.addAndGet(-missed);
+ } while (missed != 0);
+ }
+
+ private void removeSpaceListener() {
+ if (scheduler instanceof FairTaskExecutor.Group) {
+ ((FairTaskExecutor.Group)
scheduler).removeSpaceListener(onSpace);
+ }
+ }
+
+ private void removeFromQueue() {
+ if (scheduler instanceof FairTaskExecutor.Group) {
+ ((FairTaskExecutor.Group) scheduler).remove(this);
+ } else if (scheduler instanceof ThreadPoolExecutor) {
+ ((ThreadPoolExecutor) scheduler).remove(this);
+ }
+ }
+
+ @Override
+ protected void done() {
+ removeSpaceListener();
+ // A helper may have executed this task while its queue entry
was still pending.
+ removeFromQueue();
+ if (LoadTask.this.isDone()) {
+ return;
+ }
+ try {
+ // FutureTask invokes done only after completion; get
never waits here.
+ get();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ fail(e);
+ } catch (ExecutionException e) {
+ fail(e.getCause());
+ } catch (CancellationException e) {
+ fail(e);
+ }
+ }
+ }
+ }
+}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/source/HiveScanNode.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/source/HiveScanNode.java
index 69b021c5509..01070642f6a 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/source/HiveScanNode.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/hive/source/HiveScanNode.java
@@ -28,12 +28,14 @@ import org.apache.doris.common.AnalysisException;
import org.apache.doris.common.Config;
import org.apache.doris.common.Pair;
import org.apache.doris.common.UserException;
+import org.apache.doris.common.profile.SummaryProfile;
import org.apache.doris.common.util.DebugUtil;
import org.apache.doris.common.util.Util;
import org.apache.doris.datasource.ExternalScanTaskCacheKey;
import org.apache.doris.datasource.FileQueryScanNode;
import org.apache.doris.datasource.FileSplit;
import org.apache.doris.datasource.FileSplitter;
+import org.apache.doris.datasource.NameMapping;
import org.apache.doris.datasource.SplitAssignment;
import org.apache.doris.datasource.SplitProducer;
import org.apache.doris.datasource.TableFormatType;
@@ -79,6 +81,7 @@ import org.apache.logging.log4j.Logger;
import java.io.Closeable;
import java.io.IOException;
+import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -87,6 +90,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
@@ -106,6 +110,7 @@ public class HiveScanNode extends FileQueryScanNode {
private boolean partitionInit = false;
private List<HivePartition> prunedPartitions;
+ private HivePartitionBatchLoader partitionBatchLoader;
private Boolean batchMode;
private boolean fileCountBatch;
private long estimatedFileCount;
@@ -263,22 +268,61 @@ public class HiveScanNode extends FileQueryScanNode {
}
});
}
- if (prunedPartitions.isEmpty()) {
+ int partitionCount = partitionInit ? prunedPartitions.size() : (int)
selectedPartitionNum;
+ if (partitionCount == 0) {
splitAssignment.finishSchedule();
return;
}
HiveExternalMetaCache cache = Env.getCurrentEnv().getExtMetaCacheMgr()
.hive(hmsTable.getCatalog().getId());
Executor executor = getSplitTaskExecutor();
- String broker = hmsTable.getCatalog().bindBrokerName();
+ HMSExternalCatalog catalog = (HMSExternalCatalog)
hmsTable.getCatalog();
+ String broker = catalog.bindBrokerName();
// Without the file cache, the eager path listed partitions
concurrently. Keep that overlap.
boolean parallelListing = !fileCountBatch ||
Config.max_external_file_cache_num <= 0;
int producers = parallelListing
- ? Math.min(prunedPartitions.size(),
Config.max_external_cache_loader_thread_pool_size) : 1;
+ ? Math.min(partitionCount,
Config.max_external_cache_loader_thread_pool_size) : 1;
+ // Listing concurrency is independent of the directory claim size.
Small selections must leave
+ // work for the other producers; larger scans still amortize claims up
to the configured batch.
+ int partitionsPerProducer =
Math.min(sessionVariable.splitPartitionBatchSize,
+ (partitionCount - 1) / producers + 1);
+ if (!partitionInit) {
+ NameMapping mapping = hmsTable.getOrBuildNameMapping();
+ List<PartitionItem> items = new
ArrayList<>(selectedPartitions.selectedPartitions.values());
+ // Convert only a requested metadata batch, retaining the pruning
view selected by this query.
+ List<List<String>> values = new AbstractList<List<String>>() {
+ @Override
+ public List<String> get(int index) {
+ return ((ListPartitionItem)
items.get(index)).getItems().get(0)
+ .getPartitionValuesAsStringListForHive();
+ }
+
+ @Override
+ public int size() {
+ return items.size();
+ }
+ };
+ SummaryProfile profile = getSummaryProfile();
+ partitionBatchLoader = new
HivePartitionBatchLoader(getMetadataTaskExecutor(),
+ splitAssignment::needMoreSplit, values,
+ catalog.getClient().getPartitionBatchSize(), producers,
+ batch -> cache.getCachedPartitions(mapping, batch), batch
-> {
+ long start = System.currentTimeMillis();
+ try {
+ return
cache.getExistingPartitionsWithCache(mapping, batch);
+ } finally {
+ if (profile != null) {
+
profile.addExternalTableGetPartitionsTime(System.currentTimeMillis() - start);
+ }
+ }
+ });
+ splitAssignment.addCloseable(partitionBatchLoader);
+ }
AtomicInteger nextPartition = new AtomicInteger();
long started = System.currentTimeMillis();
if (!usesCountFileSplitPolicy()) {
- startSplitProducers(cache, executor, broker, numBackends,
producers, nextPartition, null, started);
+ startSplitProducers(cache, executor, broker, numBackends,
producers,
+ partitionsPerProducer, nextPartition, null, started);
return;
}
int parallelism =
sessionVariable.getParallelExecInstanceNum(scanContext.getClusterName());
@@ -288,21 +332,22 @@ public class HiveScanNode extends FileQueryScanNode {
// The count policy needs only a scan-wide lower bound. Reuse the same
cancellable workers
// and singleton partition loads, then publish one decision before
starting range producers.
for (int i = 0; i < producers; i++) {
- new SplitProducer(splitAssignment, executor, () -> {
- prefetchCountFiles(countPlan, cache, broker, parallelism,
numBackends, nextPartition);
- return Collections.emptyList();
- }, failure -> {
+ SplitProducer.BatchSource source = createCountPrefetchSource(
+ countPlan, cache, broker, parallelism, numBackends,
nextPartition);
+ new SplitProducer(splitAssignment, executor, source, failure -> {
if (failure != null) {
splitAssignment.setException(createSplitPlanningException(failure));
+ closePartitionBatchLoader();
}
if (remaining.decrementAndGet() == 0) {
if (splitAssignment.needMoreSplit()) {
countPlan.needSplit =
FileSplitter.needSplitForCountPushdown(
parallelism, numBackends,
countPlan.fileCount.get());
startSplitProducers(cache, executor, broker,
numBackends,
- producers, nextPartition, countPlan, started);
+ producers, partitionsPerProducer,
nextPartition, countPlan, started);
} else {
closeCountSplitPlan(countPlan);
+ closePartitionBatchLoader();
splitAssignment.finishSchedule();
}
}
@@ -310,6 +355,55 @@ public class HiveScanNode extends FileQueryScanNode {
}
}
+ private SplitProducer.BatchSource createCountPrefetchSource(CountSplitPlan
plan, HiveExternalMetaCache cache,
+ String broker, int parallelism, int numBackends, AtomicInteger
nextPartition) {
+ return new SplitProducer.BatchSource() {
+ private CompletableFuture<Void> blocked;
+ private boolean finished;
+
+ @Override
+ public CompletableFuture<Void> isBlocked() {
+ return finished ? null : blocked;
+ }
+
+ @Override
+ public List<Split> getNextBatch() throws IOException,
UserException {
+ blocked = null;
+ if (partitionBatchLoader == null) {
+ prefetchCountFiles(plan, cache, broker, parallelism,
numBackends, nextPartition);
+ } else {
+ while (splitAssignment.needMoreSplit() &&
FileSplitter.needSplitForCountPushdown(
+ parallelism, numBackends, plan.fileCount.get())) {
+ List<HivePartition> batch =
partitionBatchLoader.take(1);
+ if (batch.isEmpty()) {
+ CompletableFuture<Void> dependency =
partitionBatchLoader.isBlocked();
+ if (dependency != null) {
+ blocked = CompletableFuture.anyOf(dependency,
plan.enoughFiles)
+ .thenApply(unused -> null);
+ return Collections.emptyList();
+ }
+ if (partitionBatchLoader.isFinished()) {
+ break;
+ }
+ continue;
+ }
+ for (FileCacheValue value :
getFileCachesByPartitions(cache, batch, broker, true)) {
+ if (value.getFiles() != null &&
!value.getFiles().isEmpty()) {
+ plan.prefetched.add(value);
+
plan.fileCount.addAndGet(value.getFiles().size());
+ }
+ }
+ if
(!FileSplitter.needSplitForCountPushdown(parallelism, numBackends,
plan.fileCount.get())) {
+ plan.enoughFiles.complete(null);
+ }
+ }
+ }
+ finished = true;
+ return Collections.emptyList();
+ }
+ };
+ }
+
private void prefetchCountFiles(CountSplitPlan plan, HiveExternalMetaCache
cache, String broker,
int parallelism, int numBackends, AtomicInteger nextPartition)
throws IOException, UserException {
@@ -333,11 +427,13 @@ public class HiveScanNode extends FileQueryScanNode {
private static class CountSplitPlan implements Closeable {
private final ConcurrentLinkedQueue<FileCacheValue> prefetched = new
ConcurrentLinkedQueue<>();
private final AtomicLong fileCount = new AtomicLong();
+ private final CompletableFuture<Void> enoughFiles = new
CompletableFuture<>();
private boolean needSplit;
@Override
public void close() {
prefetched.clear();
+ enoughFiles.complete(null);
}
}
@@ -346,40 +442,53 @@ public class HiveScanNode extends FileQueryScanNode {
plan.close();
}
+ private void closePartitionBatchLoader() {
+ if (partitionBatchLoader != null) {
+ splitAssignment.removeCloseable(partitionBatchLoader);
+ partitionBatchLoader.close();
+ }
+ }
+
private void startSplitProducers(HiveExternalMetaCache cache, Executor
executor, String broker,
- int numBackends, int producers, AtomicInteger nextPartition,
CountSplitPlan countPlan, long started) {
+ int numBackends, int producers, int partitionsPerProducer,
+ AtomicInteger nextPartition, CountSplitPlan countPlan, long
started) {
AtomicInteger remaining = new AtomicInteger(producers);
for (int i = 0; i < producers; i++) {
- new SplitProducer(splitAssignment, executor,
- createSplitBatchSource(cache, nextPartition, broker,
numBackends, countPlan), failure -> {
- try {
- if (failure != null) {
-
splitAssignment.setException(createSplitPlanningException(failure));
- }
- } finally {
- if (remaining.decrementAndGet() == 0) {
- if (countPlan != null) {
- closeCountSplitPlan(countPlan);
- }
- if (getSummaryProfile() != null) {
-
getSummaryProfile().addExternalTableGetPartitionFilesTime(
- System.currentTimeMillis() -
started);
- }
- splitAssignment.finishSchedule();
- }
+ SplitProducer.BatchSource source = createSplitBatchSource(cache,
nextPartition, broker, numBackends,
+ countPlan, partitionsPerProducer);
+ new SplitProducer(splitAssignment, executor, source, failure -> {
+ try {
+ if (failure != null) {
+
splitAssignment.setException(createSplitPlanningException(failure));
+ closePartitionBatchLoader();
+ }
+ } finally {
+ if (remaining.decrementAndGet() == 0) {
+ if (countPlan != null) {
+ closeCountSplitPlan(countPlan);
}
- }).start();
+ closePartitionBatchLoader();
+ if (getSummaryProfile() != null) {
+
getSummaryProfile().addExternalTableGetPartitionFilesTime(
+ System.currentTimeMillis() - started);
+ }
+ splitAssignment.finishSchedule();
+ }
+ }
+ }).start();
}
}
SplitProducer.BatchSource createSplitBatchSource(HiveExternalMetaCache
cache, AtomicInteger nextPartition,
String broker, int numBackends) {
- return createSplitBatchSource(cache, nextPartition, broker,
numBackends, null);
+ return createSplitBatchSource(cache, nextPartition, broker,
numBackends, null,
+ sessionVariable.splitPartitionBatchSize);
}
private SplitProducer.BatchSource
createSplitBatchSource(HiveExternalMetaCache cache, AtomicInteger nextPartition,
- String broker, int numBackends, CountSplitPlan countPlan) {
+ String broker, int numBackends, CountSplitPlan countPlan, int
partitionsPerProducer) {
return new SplitProducer.BatchSource() {
+ private Iterator<HivePartition> partitions =
Collections.emptyIterator();
private Iterator<FileCacheValue> fileCaches =
Collections.emptyIterator();
private Iterator<HiveExternalMetaCache.HiveFileStatus> files =
Collections.emptyIterator();
private Iterator<Split> ranges = Collections.emptyIterator();
@@ -387,9 +496,20 @@ public class HiveScanNode extends FileQueryScanNode {
private long targetSize;
private boolean needSplit;
private long partitionSplitCount;
+ private CompletableFuture<Void> blockedOnPartitions;
+
+ @Override
+ public CompletableFuture<Void> isBlocked() {
+ if (partitionBatchLoader == null || ranges.hasNext() ||
files.hasNext() || fileCaches.hasNext()
+ || partitions.hasNext() || countPlan != null &&
!countPlan.prefetched.isEmpty()) {
+ return null;
+ }
+ return blockedOnPartitions != null ? blockedOnPartitions :
partitionBatchLoader.isBlocked();
+ }
@Override
public List<Split> getNextBatch() throws IOException,
UserException {
+ blockedOnPartitions = null;
List<Split> batch =
SplitProducer.newBatch(splitAssignment.getSplitBatchSize());
while (batch.size() < splitAssignment.getSplitBatchSize() &&
splitAssignment.needMoreSplit()) {
if (ranges.hasNext()) {
@@ -434,6 +554,19 @@ public class HiveScanNode extends FileQueryScanNode {
List<FileCacheValue> loaded;
if (prefetched != null) {
loaded = Collections.singletonList(prefetched);
+ } else if (partitionBatchLoader != null) {
+ if (!partitions.hasNext()) {
+ partitions =
partitionBatchLoader.take(partitionsPerProducer).iterator();
+ if (!partitions.hasNext()) {
+ blockedOnPartitions =
partitionBatchLoader.isBlocked();
+ if (blockedOnPartitions == null &&
!partitionBatchLoader.isFinished()) {
+ continue;
+ }
+ return false;
+ }
+ }
+ loaded = getFileCachesByPartitions(cache,
+ Collections.singletonList(partitions.next()),
broker, true);
} else {
int index = nextPartition.getAndIncrement();
if (index >= prunedPartitions.size()) {
@@ -451,10 +584,14 @@ public class HiveScanNode extends FileQueryScanNode {
@Override
public void close() {
+ partitions = Collections.emptyIterator();
ranges = Collections.emptyIterator();
files = Collections.emptyIterator();
fileCaches = Collections.emptyIterator();
currentCache = null;
+ if (partitionBatchLoader != null) {
+ partitionBatchLoader.readerClosed();
+ }
}
};
}
@@ -474,6 +611,14 @@ public class HiveScanNode extends FileQueryScanNode {
}
if (!partitionInit) {
try {
+ if
(!hmsTable.getPartitionColumnTypes(MvccUtil.getSnapshotFromContext(hmsTable)).isEmpty())
{
+ totalPartitionNum = selectedPartitions.totalPartitionNum;
+ selectedPartitionNum =
selectedPartitions.selectedPartitions.size();
+ int threshold =
sessionVariable.getNumPartitionsInBatchMode();
+ if (threshold >= 0 && selectedPartitionNum >= threshold) {
+ return true;
+ }
+ }
prunedPartitions = getPartitions();
} catch (Exception e) {
return false;
@@ -502,7 +647,7 @@ public class HiveScanNode extends FileQueryScanNode {
@Override
public int numApproximateSplits() {
long estimate = fileCountBatch ? estimatedFileCount
- : (long) numSplitsPerPartition.get() * prunedPartitions.size();
+ : (long) numSplitsPerPartition.get() * (partitionInit ?
prunedPartitions.size() : selectedPartitionNum);
return (int) Math.min(Integer.MAX_VALUE, estimate);
}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/common/util/FairTaskExecutorTest.java
b/fe/fe-core/src/test/java/org/apache/doris/common/util/FairTaskExecutorTest.java
index ce33fe8ee89..cfed9fec397 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/common/util/FairTaskExecutorTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/common/util/FairTaskExecutorTest.java
@@ -34,6 +34,33 @@ import java.util.concurrent.atomic.AtomicReference;
@Timeout(30)
class FairTaskExecutorTest {
+ @Test
+ void removingAHelpedTaskReleasesCapacityAndNotifiesOnce() {
+ try (FairTaskExecutor pool = executor(1)) {
+ FairTaskExecutor.Group group = pool.newGroup(1);
+ CountDownLatch running = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ group.execute(() -> {
+ running.countDown();
+ await(release);
+ });
+ await(running);
+ try {
+ FutureTask<Void> helped = new FutureTask<>(() -> null);
+ AtomicInteger notified = new AtomicInteger();
+ Assertions.assertTrue(group.tryExecute(helped,
Assertions::fail, null));
+ Assertions.assertFalse(group.tryExecute(() -> { },
Assertions::fail, notified::incrementAndGet));
+ helped.run();
+ group.remove(helped);
+ group.remove(helped);
+ Assertions.assertEquals(0, group.queuedTasks());
+ Assertions.assertEquals(1, notified.get());
+ } finally {
+ release.countDown();
+ }
+ }
+ }
+
private FairTaskExecutor executor(int workers) {
return new FairTaskExecutor(workers, task -> {
Thread thread = new Thread(task);
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/datasource/SplitProducerTest.java
b/fe/fe-core/src/test/java/org/apache/doris/datasource/SplitProducerTest.java
index 6d7abf1e769..6161ba631a7 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/datasource/SplitProducerTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/datasource/SplitProducerTest.java
@@ -40,6 +40,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
@@ -50,6 +51,119 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
class SplitProducerTest {
+ @Test
+ void producingThenWaitingDoesNotKeepResubmitting() throws Exception {
+ Fixture fixture = new Fixture(1, 3);
+ ManualExecutor executor = new ManualExecutor();
+ CompletableFuture<Void> dependency = new CompletableFuture<>();
+ RecordingSource source = new RecordingSource(1, 0, 2) {
+ private boolean first = true;
+ private boolean paused;
+
+ @Override
+ public CompletableFuture<Void> isBlocked() {
+ return paused ? dependency : null;
+ }
+
+ @Override
+ public List<Split> getNextBatch() throws IOException {
+ paused = first;
+ first = false;
+ return super.getNextBatch();
+ }
+ };
+ fixture.start(executor, source);
+ executor.runUntilIdle();
+ Assertions.assertEquals(1,
fixture.assignment.getAssignedSplits(fixture.backend).size());
+ Assertions.assertEquals(0, fixture.completions.get());
+ dependency.complete(null);
+ executor.runUntilIdle();
+ Assertions.assertEquals(Arrays.asList(0L, 2L),
identities(fixture.source().getNextBatch(2)));
+ Assertions.assertEquals(1, fixture.completions.get());
+ }
+
+ @Test
+ void asynchronousMetadataWaitReleasesWorkerAndResumesOnCompletion() throws
Exception {
+ Fixture fixture = new Fixture(1, 3);
+ ManualExecutor executor = new ManualExecutor();
+ CompletableFuture<Void> dependency = new CompletableFuture<>();
+ RecordingSource source = new RecordingSource(1, 0) {
+ private boolean awaiting = true;
+
+ @Override
+ public CompletableFuture<Void> isBlocked() {
+ return awaiting ? dependency : null;
+ }
+
+ @Override
+ public List<Split> getNextBatch() throws IOException {
+ awaiting = false;
+ return super.getNextBatch();
+ }
+ };
+ fixture.start(executor, source);
+ executor.runUntilIdle();
+ Assertions.assertEquals(0, fixture.completions.get());
+
Assertions.assertTrue(fixture.assignment.getAssignedSplits(fixture.backend).isEmpty());
+ dependency.complete(null);
+ executor.runUntilIdle();
+ Assertions.assertEquals(Collections.singletonList(0L),
identities(fixture.source().getNextBatch(1)));
+ Assertions.assertEquals(1, fixture.completions.get());
+ }
+
+ @Test
+ void metadataCompletionRacingEmptyReadDoesNotBecomeEndOfInput() throws
Exception {
+ Fixture fixture = new Fixture(1, 3);
+ ManualExecutor executor = new ManualExecutor();
+ RecordingSource source = new RecordingSource(1, 0) {
+ private final CompletableFuture<Void> dependency = new
CompletableFuture<>();
+ private CompletableFuture<Void> blocked;
+ private boolean first = true;
+
+ @Override
+ public CompletableFuture<Void> isBlocked() {
+ return blocked;
+ }
+
+ @Override
+ public List<Split> getNextBatch() throws IOException {
+ if (first) {
+ first = false;
+ blocked = dependency;
+ dependency.complete(null);
+ return Collections.emptyList();
+ }
+ blocked = null;
+ return super.getNextBatch();
+ }
+ };
+ fixture.start(executor, source);
+ executor.runUntilIdle();
+ Assertions.assertEquals(Collections.singletonList(0L),
identities(fixture.source().getNextBatch(1)));
+ Assertions.assertEquals(1, fixture.completions.get());
+ }
+
+ @Test
+ void metadataFailureWakesProducerAndReachesConsumer() throws Exception {
+ Fixture fixture = new Fixture(1, 3);
+ ManualExecutor executor = new ManualExecutor();
+ CompletableFuture<Void> dependency = new CompletableFuture<>();
+ RecordingSource source = new RecordingSource(1, 0) {
+ @Override
+ public CompletableFuture<Void> isBlocked() {
+ return dependency;
+ }
+ };
+ fixture.start(executor, source);
+ executor.runUntilIdle();
+ dependency.completeExceptionally(new IllegalStateException("metadata
failed"));
+ executor.runUntilIdle();
+ Assertions.assertTrue(Assertions.assertThrows(UserException.class,
+ () ->
fixture.source().getNextBatch(1)).getMessage().contains("metadata failed"));
+ Assertions.assertEquals(1, source.closeCalls.get());
+ Assertions.assertEquals(1, fixture.completions.get());
+ }
+
@Test
void closingOneBackendResumesTheOtherBoundedQueue() throws Exception {
Backend closed = new Backend(1, "closed", 0);
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/datasource/hive/HiveMetaStoreCacheTest.java
b/fe/fe-core/src/test/java/org/apache/doris/datasource/hive/HiveMetaStoreCacheTest.java
index 14c65454354..798aa472061 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/datasource/hive/HiveMetaStoreCacheTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/datasource/hive/HiveMetaStoreCacheTest.java
@@ -19,20 +19,27 @@ package org.apache.doris.datasource.hive;
import org.apache.doris.analysis.PartitionValue;
import org.apache.doris.analysis.StringLiteral;
+import org.apache.doris.catalog.Column;
+import org.apache.doris.catalog.Env;
import org.apache.doris.catalog.ListPartitionItem;
import org.apache.doris.catalog.PartitionItem;
import org.apache.doris.catalog.PartitionKey;
import org.apache.doris.catalog.Type;
import org.apache.doris.common.ThreadPoolManager;
import org.apache.doris.common.util.Util;
+import org.apache.doris.datasource.CatalogMgr;
import org.apache.doris.datasource.NameMapping;
import org.apache.doris.datasource.metacache.EstimatorCalibrationAssertions;
import org.apache.doris.datasource.metacache.MetaCacheEntry;
import org.apache.doris.datasource.metacache.MetaCacheSizeEstimate;
import com.google.common.collect.HashBiMap;
+import com.google.common.collect.ImmutableList;
+import org.apache.hadoop.hive.metastore.api.Partition;
+import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
import org.mockito.Mockito;
import java.util.ArrayList;
@@ -47,6 +54,85 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class HiveMetaStoreCacheTest {
+ @Test
+ void cachedPartitionProbeDoesNotLoadAndHonorsInvalidation() {
+ ThreadPoolExecutor executor =
ThreadPoolManager.newDaemonFixedThreadPool(1, 1, "part-probe", 1, false);
+ try {
+ HiveExternalMetaCache cache = new HiveExternalMetaCache(executor,
executor);
+ cache.initCatalog(0, new HashMap<>());
+ NameMapping mapping = NameMapping.createForTest("db", "parts");
+ MetaCacheEntry<HiveExternalMetaCache.PartitionCacheKey,
HivePartition> entry = cache.entry(0,
+ HiveExternalMetaCache.ENTRY_PARTITION,
HiveExternalMetaCache.PartitionCacheKey.class,
+ HivePartition.class);
+ HivePartition original = new HivePartition(mapping, false,
"parquet", "s3://bucket/old",
+ ImmutableList.of("1"), Collections.emptyMap());
+ entry.put(new HiveExternalMetaCache.PartitionCacheKey(mapping,
ImmutableList.of("1")), original);
+ List<HivePartition> retained = cache.getCachedPartitions(mapping,
+ ImmutableList.of(ImmutableList.of("1"))).get();
+ Assertions.assertSame(original, retained.get(0));
+ Assertions.assertFalse(cache.getCachedPartitions(mapping,
+ ImmutableList.of(ImmutableList.of("1"),
ImmutableList.of("2"))).isPresent(),
+ "a partial miss must not invoke the remote loader");
+ cache.invalidateTable(0, "db", "parts");
+ Assertions.assertFalse(cache.getCachedPartitions(mapping,
+ ImmutableList.of(ImmutableList.of("1"))).isPresent());
+ HivePartition replacement = new HivePartition(mapping, false,
"parquet", "s3://bucket/new",
+ ImmutableList.of("1"), Collections.emptyMap());
+ entry.put(new HiveExternalMetaCache.PartitionCacheKey(mapping,
ImmutableList.of("1")), replacement);
+ Assertions.assertSame(replacement,
cache.getCachedPartitions(mapping,
+ ImmutableList.of(ImmutableList.of("1"))).get().get(0));
+ Assertions.assertSame(original, retained.get(0), "invalidation
must not mutate an active reader's view");
+ } finally {
+ executor.shutdownNow();
+ }
+ }
+
+ @Test
+ void streamingBatchDoesNotReloadADroppedPartitionIndividually() {
+ ThreadPoolExecutor executor =
ThreadPoolManager.newDaemonFixedThreadPool(1, 1, "part-missing", 1, false);
+ try {
+ HiveExternalMetaCache cache = new HiveExternalMetaCache(executor,
executor);
+ cache.initCatalog(0, new HashMap<>());
+ NameMapping mapping = NameMapping.createForTest("db", "parts");
+ Env env = Mockito.mock(Env.class, Mockito.RETURNS_DEEP_STUBS);
+ HMSExternalCatalog catalog =
Mockito.mock(HMSExternalCatalog.class);
+ HMSExternalDatabase database =
Mockito.mock(HMSExternalDatabase.class);
+ HMSExternalTable table = Mockito.mock(HMSExternalTable.class);
+ HMSCachedClient client = Mockito.mock(HMSCachedClient.class);
+ CatalogMgr manager = env.getCatalogMgr();
+ Mockito.doReturn(catalog).when(manager).getCatalog(0L);
+ Mockito.doReturn(database).when(catalog).getDbNullable("db");
+ Mockito.when(database.getTableNullable("parts")).thenReturn(table);
+
Mockito.when(table.getPartitionColumns()).thenReturn(ImmutableList.of(new
Column("p", Type.INT)));
+ Mockito.when(catalog.getClient()).thenReturn(client);
+ Partition existing = new Partition();
+ existing.setValues(ImmutableList.of("1"));
+ existing.setParameters(Collections.emptyMap());
+ StorageDescriptor descriptor = new StorageDescriptor();
+ descriptor.setInputFormat("parquet");
+ descriptor.setLocation("s3://bucket/p=1");
+ existing.setSd(descriptor);
+ Mockito.when(client.getExistingPartitions(Mockito.eq("db"),
Mockito.eq("parts"), Mockito.anyList()))
+ .thenReturn(ImmutableList.of(existing));
+ try (MockedStatic<Env> environment =
Mockito.mockStatic(Env.class)) {
+ environment.when(Env::getCurrentEnv).thenReturn(env);
+ List<HivePartition> partitions =
cache.getExistingPartitionsWithCache(
+ mapping, ImmutableList.of(ImmutableList.of("1"),
ImmutableList.of("2")));
+ Assertions.assertEquals(1, partitions.size());
+ Assertions.assertEquals(ImmutableList.of("1"),
partitions.get(0).getPartitionValues());
+ Mockito.verify(client).getExistingPartitions("db", "parts",
ImmutableList.of("p=1", "p=2"));
+ Mockito.verify(client,
Mockito.never()).getPartition(Mockito.anyString(), Mockito.anyString(),
+ Mockito.anyList());
+ Assertions.assertTrue(cache.getCachedPartitions(mapping,
+ ImmutableList.of(ImmutableList.of("1"))).isPresent());
+ Assertions.assertFalse(cache.getCachedPartitions(mapping,
+ ImmutableList.of(ImmutableList.of("2"))).isPresent());
+ }
+ } finally {
+ executor.shutdownNow();
+ }
+ }
+
@Test
public void
testCachedFileCountUsesOnlyPresentEntriesAndHonorsInvalidation() {
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/datasource/hive/source/HivePartitionBatchLoaderTest.java
b/fe/fe-core/src/test/java/org/apache/doris/datasource/hive/source/HivePartitionBatchLoaderTest.java
new file mode 100644
index 00000000000..6fbdd56cbe8
--- /dev/null
+++
b/fe/fe-core/src/test/java/org/apache/doris/datasource/hive/source/HivePartitionBatchLoaderTest.java
@@ -0,0 +1,586 @@
+// 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.datasource.hive.source;
+
+import org.apache.doris.common.util.FairTaskExecutor;
+import org.apache.doris.datasource.hive.HivePartition;
+
+import com.google.common.collect.ImmutableList;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+class HivePartitionBatchLoaderTest {
+ @Test
+ void directoryBatchLimitDoesNotOverflowAfterCountPrefetch() {
+ HivePartitionBatchLoader loader = loader(Runnable::run, new
TestContext(),
+ 100, 1024, HivePartitionBatchLoaderTest::partitions);
+ Assertions.assertNull(loader.isBlocked());
+ Assertions.assertEquals(1, loader.take(1).size());
+ Assertions.assertEquals(15, loader.take(Integer.MAX_VALUE).size());
+ }
+
+ @Test
+ void firstBatchStartsSmallAndRemainingBatchIsSharedWithoutDuplicates() {
+ QueuedScheduler scheduler = new QueuedScheduler();
+ List<Integer> requests = new ArrayList<>();
+ HivePartitionBatchLoader loader = loader(scheduler, new TestContext(),
1000, 1024, batch -> {
+ requests.add(batch.size());
+ return partitions(batch);
+ });
+ Assertions.assertTrue(requests.isEmpty());
+ CompletableFuture<Void> initial = loader.isBlocked();
+ Assertions.assertFalse(initial.isDone());
+ scheduler.runNext();
+ Assertions.assertTrue(initial.isDone());
+ List<HivePartition> all = new ArrayList<>(loader.take(16));
+ Assertions.assertEquals(1, scheduler.tasks.size(), "next HMS batch
overlaps the first directory batch");
+ scheduler.runAll();
+ Assertions.assertEquals(ImmutableList.of(16, 984), requests);
+ while (!loader.isFinished()) {
+ List<HivePartition> batch = loader.take(16);
+ Assertions.assertTrue(batch.size() <= 16);
+ all.addAll(batch);
+ }
+ Assertions.assertEquals(1000, all.size());
+ Assertions.assertEquals(1000, new
HashSet<>(all.stream().map(HivePartition::getPartitionValues)
+ .collect(java.util.stream.Collectors.toList())).size());
+ }
+
+ @Test
+ void takingFirstDirectoryBatchDoesNotWalkTheNextLargeCachedBatch() {
+ QueuedScheduler scheduler = new QueuedScheduler();
+ List<Integer> probes = new ArrayList<>();
+ HivePartitionBatchLoader loader = new
HivePartitionBatchLoader(executor(scheduler), new TestContext(),
+ names(1000), 1024, 3, batch -> {
+ probes.add(batch.size());
+ return Optional.of(partitions(batch));
+ }, batch -> {
+ throw new AssertionError("cached metadata must not issue
an HMS request");
+ });
+ Assertions.assertNull(loader.isBlocked());
+ Assertions.assertEquals(16, loader.take(16).size());
+ Assertions.assertEquals(ImmutableList.of(16), probes,
+ "claiming the first slice must not prepare the following 984
cached partitions inline");
+ Assertions.assertEquals(1, scheduler.tasks.size());
+ Runnable queued = scheduler.tasks.element();
+ Assertions.assertNull(loader.isBlocked(), "an idle reader can help the
cache probe");
+ queued.run();
+ Assertions.assertTrue(scheduler.tasks.isEmpty(), "the helped task must
be removed from the queue");
+ Assertions.assertEquals(ImmutableList.of(16, 984), probes);
+ int count = 16;
+ while (!loader.isFinished()) {
+ count += loader.take(16).size();
+ }
+ Assertions.assertEquals(1000, count);
+ }
+
+ @Test
+ void helperAndMetadataWorkerCannotRunTheSameCacheProbeTwice() throws
Exception {
+ QueuedScheduler scheduler = new QueuedScheduler();
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ AtomicInteger probes = new AtomicInteger();
+ HivePartitionBatchLoader loader = new
HivePartitionBatchLoader(executor(scheduler), new TestContext(),
+ names(1000), 1024, 3, batch -> {
+ probes.incrementAndGet();
+ if (batch.size() > 16) {
+ entered.countDown();
+ try {
+ Assertions.assertTrue(release.await(5,
TimeUnit.SECONDS));
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ }
+ return Optional.of(partitions(batch));
+ }, batch -> {
+ throw new AssertionError("cache hit must not issue an HMS
request");
+ });
+ loader.isBlocked();
+ loader.take(16);
+ ExecutorService reader = Executors.newSingleThreadExecutor();
+ try {
+ Future<CompletableFuture<Void>> helper =
reader.submit(loader::isBlocked);
+ Assertions.assertTrue(entered.await(5, TimeUnit.SECONDS));
+ scheduler.runNext();
+ Assertions.assertFalse(helper.isDone(), "the metadata worker must
not duplicate the helper's probe");
+ release.countDown();
+ Assertions.assertNull(helper.get(5, TimeUnit.SECONDS));
+ Assertions.assertEquals(2, probes.get());
+ Assertions.assertTrue(scheduler.tasks.isEmpty());
+ } finally {
+ release.countDown();
+ reader.shutdownNow();
+ }
+ }
+
+ @Test
+ void helpedCacheMissHandsOneQueueSlotToRemoteLoadWithoutWaiting() {
+ QueuedScheduler scheduler = new QueuedScheduler();
+ scheduler.capacity = 1;
+ AtomicInteger requests = new AtomicInteger();
+ HivePartitionBatchLoader loader = new
HivePartitionBatchLoader(executor(scheduler), new TestContext(),
+ names(1000), 1024, 3,
+ batch -> batch.size() == 16 ? Optional.of(partitions(batch)) :
Optional.empty(), batch -> {
+ requests.incrementAndGet();
+ return partitions(batch);
+ });
+ loader.isBlocked();
+ Assertions.assertEquals(16, loader.take(16).size());
+ CompletableFuture<Void> pending = loader.isBlocked();
+ Assertions.assertFalse(pending.isDone());
+ Assertions.assertEquals(0, requests.get(), "helping a cache miss must
not perform the RPC");
+ Assertions.assertEquals(1, scheduler.tasks.size());
+ Assertions.assertNull(scheduler.onSpace, "removing the helped cache
task must admit the remote task");
+ scheduler.runNext();
+ Assertions.assertTrue(pending.isDone());
+ Assertions.assertEquals(1, requests.get());
+ }
+
+ @Test
+ void failureInLargeCachedProbeWakesReaders() {
+ QueuedScheduler scheduler = new QueuedScheduler();
+ IllegalStateException failure = new IllegalStateException("cache probe
failed");
+ HivePartitionBatchLoader loader = new
HivePartitionBatchLoader(executor(scheduler), new TestContext(),
+ names(1000), 1024, 3, batch -> {
+ if (batch.size() > 16) {
+ throw failure;
+ }
+ return Optional.of(partitions(batch));
+ }, batch -> {
+ throw new AssertionError("failed cache probe must not
issue an HMS request");
+ });
+ Assertions.assertNull(loader.isBlocked());
+ Assertions.assertEquals(16, loader.take(16).size());
+ scheduler.runNext();
+ CompletableFuture<Void> pending = loader.isBlocked();
+ Assertions.assertSame(failure,
Assertions.assertThrows(CompletionException.class, pending::join).getCause());
+ Assertions.assertSame(failure,
Assertions.assertThrows(CompletionException.class,
+ () -> loader.take(16)).getCause());
+ }
+
+ @Test
+ void cancellingQueuedLargeCachedProbePreventsItsExecution() {
+ QueuedScheduler scheduler = new QueuedScheduler();
+ TestContext context = new TestContext();
+ List<Integer> probes = new ArrayList<>();
+ HivePartitionBatchLoader loader = new
HivePartitionBatchLoader(executor(scheduler), context,
+ names(1000), 1024, 3, batch -> {
+ probes.add(batch.size());
+ return Optional.of(partitions(batch));
+ }, batch -> {
+ throw new AssertionError("stopped cached scan must not
issue an HMS request");
+ });
+ loader.isBlocked();
+ loader.take(16);
+ Runnable stale = scheduler.tasks.element();
+ context.cancel();
+ loader.close();
+ Assertions.assertTrue(loader.isBlocked().isCompletedExceptionally());
+ Assertions.assertTrue(scheduler.tasks.isEmpty());
+ stale.run();
+ Assertions.assertEquals(ImmutableList.of(16), probes);
+ }
+
+ @Test
+ void cancellationDuringLargeCacheMissDoesNotStartAnHmsRequest() {
+ QueuedScheduler scheduler = new QueuedScheduler();
+ TestContext context = new TestContext();
+ AtomicInteger requests = new AtomicInteger();
+ HivePartitionBatchLoader loader = new
HivePartitionBatchLoader(executor(scheduler), context,
+ names(1000), 1024, 3, batch -> {
+ if (batch.size() > 16) {
+ context.cancel();
+ return Optional.empty();
+ }
+ return Optional.of(partitions(batch));
+ }, batch -> {
+ requests.incrementAndGet();
+ return partitions(batch);
+ });
+ loader.isBlocked();
+ loader.take(16);
+ scheduler.runNext();
+ Assertions.assertTrue(loader.isBlocked().isCompletedExceptionally());
+ Assertions.assertEquals(0, requests.get());
+ }
+
+ @Test
+ void maximumRpcLimitDoesNotOverflowAfterTheFirstBatch() {
+ List<Integer> requests = new ArrayList<>();
+ HivePartitionBatchLoader loader = loader(Runnable::run, new
TestContext(),
+ 17, Integer.MAX_VALUE, batch -> {
+ requests.add(batch.size());
+ return partitions(batch);
+ });
+ Assertions.assertNull(loader.isBlocked());
+ List<HivePartition> all = new ArrayList<>(loader.take(16));
+ all.addAll(loader.take(16));
+ Assertions.assertTrue(loader.isFinished());
+ Assertions.assertEquals(17, all.size());
+ Assertions.assertEquals(ImmutableList.of(16, 1), requests);
+ }
+
+ @Test
+ void configuredRpcLimitAlsoBoundsFirstBatch() {
+ List<Integer> requests = new ArrayList<>();
+ HivePartitionBatchLoader loader = loader(Runnable::run, new
TestContext(),
+ 10, 4, batch -> {
+ requests.add(batch.size());
+ return partitions(batch);
+ });
+ int count = 0;
+ while (!loader.isFinished()) {
+ Assertions.assertNull(loader.isBlocked());
+ count += loader.take(16).size();
+ }
+ Assertions.assertEquals(10, count);
+ Assertions.assertEquals(ImmutableList.of(4, 4, 2), requests);
+ }
+
+ @Test
+ void oneReadyListBoundsMetadataAheadOfDirectoryConsumers() {
+ QueuedScheduler scheduler = new QueuedScheduler();
+ HivePartitionBatchLoader loader = loader(scheduler, new TestContext(),
200, 32,
+ HivePartitionBatchLoaderTest::partitions);
+ loader.isBlocked();
+ scheduler.runNext();
+ loader.take(16);
+ scheduler.runAll();
+ Assertions.assertNull(loader.isBlocked());
+ Assertions.assertTrue(scheduler.tasks.isEmpty());
+ loader.take(16);
+ Assertions.assertTrue(scheduler.tasks.isEmpty(), "half-consumed batch
must stop the parent");
+ loader.take(16);
+ Assertions.assertEquals(1, scheduler.tasks.size());
+ }
+
+ @Test
+ void fullyCachedMetadataDoesNotNeedMetadataCapacity() {
+ QueuedScheduler scheduler = new QueuedScheduler();
+ scheduler.full = true;
+ HivePartitionBatchLoader loader = new
HivePartitionBatchLoader(executor(scheduler), new TestContext(),
+ names(100), 32, 3, batch -> Optional.of(partitions(batch)),
batch -> {
+ throw new AssertionError("cache hit must not load
remotely");
+ });
+ int count = 0;
+ while (!loader.isFinished()) {
+ Assertions.assertNull(loader.isBlocked());
+ count += loader.take(16).size();
+ }
+ Assertions.assertEquals(100, count);
+ Assertions.assertTrue(scheduler.tasks.isEmpty());
+ Assertions.assertNull(scheduler.onSpace);
+ }
+
+ @Test
+ void fullSchedulerReturnsImmediatelyAndCancellationRemovesSpaceWaiter() {
+ QueuedScheduler scheduler = new QueuedScheduler();
+ scheduler.full = true;
+ TestContext context = new TestContext();
+ AtomicInteger requests = new AtomicInteger();
+ HivePartitionBatchLoader loader = loader(scheduler, context, 100, 32,
batch -> {
+ requests.incrementAndGet();
+ return partitions(batch);
+ });
+ CompletableFuture<Void> pending = loader.isBlocked();
+ Assertions.assertFalse(pending.isDone());
+ Runnable stale = scheduler.onSpace;
+ context.cancel();
+ loader.close();
+ Assertions.assertTrue(pending.isCompletedExceptionally());
+ Assertions.assertNull(scheduler.onSpace);
+ scheduler.full = false;
+ stale.run();
+ Assertions.assertTrue(scheduler.tasks.isEmpty());
+ Assertions.assertEquals(0, requests.get());
+ }
+
+ @Test
+ void admissionResumesAfterSpaceWithoutDuplicateRpc() {
+ QueuedScheduler scheduler = new QueuedScheduler();
+ scheduler.full = true;
+ AtomicInteger requests = new AtomicInteger();
+ HivePartitionBatchLoader loader = loader(scheduler, new TestContext(),
10, 32, batch -> {
+ requests.incrementAndGet();
+ return partitions(batch);
+ });
+ CompletableFuture<Void> pending = loader.isBlocked();
+ scheduler.full = false;
+ scheduler.onSpace.run();
+ scheduler.runNext();
+ Assertions.assertTrue(pending.isDone());
+ Assertions.assertEquals(1, requests.get());
+ }
+
+ @Test
+ void spaceCallbackBeforeAdmissionReturnsCannotEnqueueTwice() {
+ Queue<Runnable> accepted = new ArrayDeque<>();
+ AtomicInteger admissions = new AtomicInteger();
+ List<Runnable> callbacks = new ArrayList<>();
+ Executor scheduler = new QueuedScheduler() {
+ @Override
+ public boolean tryExecute(Runnable task, Consumer<Throwable>
onFailure, Runnable onSpace) {
+ callbacks.add(onSpace);
+ if (admissions.incrementAndGet() == 1) {
+ onSpace.run();
+ return false;
+ }
+ accepted.add(task);
+ return true;
+ }
+
+ @Override
+ public void removeSpaceListener(Runnable callback) {
+ }
+
+ @Override
+ public void execute(Runnable task) {
+ throw new UnsupportedOperationException();
+ }
+ };
+ HivePartitionBatchLoader loader = loader(scheduler, new TestContext(),
10, 32,
+ HivePartitionBatchLoaderTest::partitions);
+ CompletableFuture<Void> pending = loader.isBlocked();
+ callbacks.get(0).run();
+ Assertions.assertEquals(2, admissions.get());
+ Assertions.assertEquals(1, accepted.size());
+ accepted.remove().run();
+ Assertions.assertTrue(pending.isDone());
+ Assertions.assertEquals(10, loader.take(16).size());
+ }
+
+ @Test
+ void closingLastReaderCancelsQueuedParentAndWakesWaiters() {
+ QueuedScheduler scheduler = new QueuedScheduler();
+ AtomicInteger requests = new AtomicInteger();
+ HivePartitionBatchLoader loader = loader(scheduler, new TestContext(),
100, 32, batch -> {
+ requests.incrementAndGet();
+ return partitions(batch);
+ });
+ CompletableFuture<Void> pending = loader.isBlocked();
+ Runnable stale = scheduler.tasks.element();
+ loader.readerClosed();
+ loader.readerClosed();
+ Assertions.assertFalse(pending.isDone());
+ loader.readerClosed();
+ Assertions.assertTrue(pending.isCompletedExceptionally());
+ Assertions.assertTrue(scheduler.tasks.isEmpty());
+ stale.run();
+ Assertions.assertEquals(0, requests.get());
+ }
+
+ @Test
+ void failedAdmissionWakesReadersAndDoesNotRunAStaleTask() {
+ QueuedScheduler scheduler = new QueuedScheduler();
+ AtomicInteger requests = new AtomicInteger();
+ HivePartitionBatchLoader loader = loader(scheduler, new TestContext(),
100, 32, batch -> {
+ requests.incrementAndGet();
+ return partitions(batch);
+ });
+ CompletableFuture<Void> pending = loader.isBlocked();
+ Runnable stale = scheduler.tasks.element();
+ IllegalStateException failure = new IllegalStateException("metadata
scheduler closed");
+ scheduler.onFailure.accept(failure);
+ Assertions.assertSame(failure,
Assertions.assertThrows(CompletionException.class, pending::join).getCause());
+ Assertions.assertTrue(scheduler.tasks.isEmpty());
+ stale.run();
+ Assertions.assertEquals(0, requests.get());
+ }
+
+ @Test
+ void loadingFailureIsVisibleToEveryReader() {
+ QueuedScheduler scheduler = new QueuedScheduler();
+ IllegalStateException failure = new IllegalStateException("HMS
failed");
+ HivePartitionBatchLoader loader = loader(scheduler, new TestContext(),
100, 32, batch -> {
+ throw failure;
+ });
+ CompletableFuture<Void> a = loader.isBlocked();
+ CompletableFuture<Void> b = loader.isBlocked();
+ scheduler.runNext();
+ Assertions.assertSame(failure,
Assertions.assertThrows(CompletionException.class, a::join).getCause());
+ Assertions.assertSame(failure,
Assertions.assertThrows(CompletionException.class, b::join).getCause());
+ Assertions.assertSame(failure,
Assertions.assertThrows(CompletionException.class,
+ () -> loader.take(16)).getCause());
+ }
+
+ @Test
+ void cancellationDiscardsUninterruptibleRpcResultAndStopsFurtherCalls()
throws Exception {
+ QueuedScheduler scheduler = new QueuedScheduler();
+ TestContext context = new TestContext();
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ AtomicInteger requests = new AtomicInteger();
+ HivePartitionBatchLoader loader = loader(scheduler, context, 100, 32,
batch -> {
+ requests.incrementAndGet();
+ entered.countDown();
+ try {
+ Assertions.assertTrue(release.await(5, TimeUnit.SECONDS));
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ return partitions(batch);
+ });
+ CompletableFuture<Void> pending = loader.isBlocked();
+ ExecutorService worker = Executors.newSingleThreadExecutor();
+ try {
+ Future<?> running = worker.submit(scheduler::runNext);
+ Assertions.assertTrue(entered.await(5, TimeUnit.SECONDS));
+ context.cancel();
+ loader.close();
+ Assertions.assertTrue(pending.isCompletedExceptionally());
+ release.countDown();
+ running.get(5, TimeUnit.SECONDS);
+ Assertions.assertEquals(1, requests.get());
+ Assertions.assertTrue(scheduler.tasks.isEmpty());
+ } finally {
+ release.countDown();
+ worker.shutdownNow();
+ }
+ }
+
+ @Test
+ void droppedPartitionsDoNotRecurseOrPrematurelyFinish() {
+ HivePartitionBatchLoader loader = loader(Runnable::run, new
TestContext(),
+ 20000, 1, batch -> Collections.emptyList());
+ Assertions.assertNull(loader.isBlocked());
+ Assertions.assertTrue(loader.isFinished());
+ }
+
+ private static HivePartitionBatchLoader loader(Executor scheduler,
TestContext context,
+ int count, int batchSize, Function<List<List<String>>,
List<HivePartition>> fetch) {
+ return new HivePartitionBatchLoader(executor(scheduler), context,
names(count), batchSize, 3,
+ batch -> Optional.empty(), fetch);
+ }
+
+ private static List<List<String>> names(int count) {
+ List<List<String>> result = new ArrayList<>();
+ for (int i = 0; i < count; i++) {
+ result.add(ImmutableList.of(Integer.toString(i)));
+ }
+ return result;
+ }
+
+ private static List<HivePartition> partitions(List<List<String>> names) {
+ List<HivePartition> result = new ArrayList<>();
+ for (List<String> name : names) {
+ result.add(new HivePartition(null, false, "parquet",
"s3://bucket/p=" + name.get(0),
+ name, Collections.emptyMap()));
+ }
+ return result;
+ }
+
+ private static Executor executor(Executor scheduler) {
+ return scheduler instanceof QueuedScheduler ? ((QueuedScheduler)
scheduler).group : scheduler;
+ }
+
+ private static final class TestContext implements
java.util.function.BooleanSupplier {
+ private volatile boolean cancelled;
+
+ @Override
+ public boolean getAsBoolean() {
+ return !cancelled;
+ }
+
+ private void cancel() {
+ cancelled = true;
+ }
+ }
+
+ private static class QueuedScheduler implements Executor {
+ private final FairTaskExecutor.Group group =
Mockito.mock(FairTaskExecutor.Group.class);
+
+ QueuedScheduler() {
+ Mockito.when(group.tryExecute(Mockito.any(), Mockito.any(),
Mockito.any())).thenAnswer(call ->
+ tryExecute(call.getArgument(0), call.getArgument(1),
call.getArgument(2)));
+ Mockito.doAnswer(call -> {
+ removeSpaceListener(call.getArgument(0));
+ return null;
+ }).when(group).removeSpaceListener(Mockito.any());
+ Mockito.doAnswer(call -> {
+ remove(call.getArgument(0));
+ return null;
+ }).when(group).remove(Mockito.any());
+ }
+
+ private final Queue<Runnable> tasks = new ArrayDeque<>();
+ private boolean full;
+ private int capacity = Integer.MAX_VALUE;
+ private Runnable onSpace;
+ private Consumer<Throwable> onFailure;
+
+ public boolean tryExecute(Runnable task, Consumer<Throwable>
onFailure, Runnable callback) {
+ if (full || tasks.size() >= capacity) {
+ onSpace = callback;
+ return false;
+ }
+ this.onFailure = onFailure;
+ tasks.add(task);
+ return true;
+ }
+
+ public void removeSpaceListener(Runnable callback) {
+ if (onSpace == callback) {
+ onSpace = null;
+ }
+ }
+
+ public void remove(Runnable task) {
+ if (tasks.remove(task) && !full && tasks.size() < capacity &&
onSpace != null) {
+ Runnable callback = onSpace;
+ onSpace = null;
+ callback.run();
+ }
+ }
+
+ @Override
+ public void execute(Runnable task) {
+ throw new UnsupportedOperationException();
+ }
+
+ private void runAll() {
+ while (!tasks.isEmpty()) {
+ runNext();
+ }
+ }
+
+ private void runNext() {
+ tasks.remove().run();
+ }
+ }
+}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/datasource/hive/source/HivePartitionStreamingTest.java
b/fe/fe-core/src/test/java/org/apache/doris/datasource/hive/source/HivePartitionStreamingTest.java
new file mode 100644
index 00000000000..e3980d90ed9
--- /dev/null
+++
b/fe/fe-core/src/test/java/org/apache/doris/datasource/hive/source/HivePartitionStreamingTest.java
@@ -0,0 +1,440 @@
+// 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.datasource.hive.source;
+
+import org.apache.doris.analysis.PartitionValue;
+import org.apache.doris.analysis.TupleDescriptor;
+import org.apache.doris.analysis.TupleId;
+import org.apache.doris.catalog.Env;
+import org.apache.doris.catalog.ListPartitionItem;
+import org.apache.doris.catalog.PartitionItem;
+import org.apache.doris.catalog.PartitionKey;
+import org.apache.doris.catalog.Type;
+import org.apache.doris.common.Config;
+import org.apache.doris.common.UserException;
+import org.apache.doris.common.profile.SummaryProfile;
+import org.apache.doris.common.util.LocationPath;
+import org.apache.doris.datasource.ExternalMetaCacheMgr;
+import org.apache.doris.datasource.FederationBackendPolicy;
+import org.apache.doris.datasource.FileSplit;
+import org.apache.doris.datasource.FileSplitter;
+import org.apache.doris.datasource.NameMapping;
+import org.apache.doris.datasource.SplitAssignment;
+import org.apache.doris.datasource.SplitSource;
+import org.apache.doris.datasource.hive.HMSCachedClient;
+import org.apache.doris.datasource.hive.HMSExternalCatalog;
+import org.apache.doris.datasource.hive.HMSExternalTable;
+import org.apache.doris.datasource.hive.HiveExternalMetaCache;
+import org.apache.doris.datasource.hive.HiveExternalMetaCache.FileCacheValue;
+import org.apache.doris.datasource.hive.HiveExternalMetaCache.HiveFileStatus;
+import org.apache.doris.datasource.hive.HivePartition;
+import
org.apache.doris.nereids.trees.plans.logical.LogicalFileScan.SelectedPartitions;
+import org.apache.doris.planner.PlanNodeId;
+import org.apache.doris.planner.ScanContext;
+import org.apache.doris.qe.SessionVariable;
+import org.apache.doris.spi.Split;
+import org.apache.doris.system.Backend;
+import org.apache.doris.thrift.TScanRangeLocation;
+import org.apache.doris.thrift.TScanRangeLocations;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.LinkedListMultimap;
+import com.google.common.collect.Multimap;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+class HivePartitionStreamingTest {
+ @Test
+ void lazyDirectoryListingsOverlapForSmallPartitionSets() throws Exception {
+ for (boolean warm : new boolean[] {false, true}) {
+ for (int partitions : new int[] {2, 8, 16, 17}) {
+ assertLazyListingsOverlap(partitions, warm, false);
+ }
+ }
+ }
+
+ @Test
+ void lazyCountPrefetchListingsOverlapForSmallPartitionSets() throws
Exception {
+ for (boolean warm : new boolean[] {false, true}) {
+ for (int partitions : new int[] {2, 8, 16, 17}) {
+ assertLazyListingsOverlap(partitions, warm, true);
+ }
+ }
+ }
+
+ private void assertLazyListingsOverlap(int partitions, boolean warm,
boolean count) throws Exception {
+ int previous = Config.max_external_cache_loader_thread_pool_size;
+ Config.max_external_cache_loader_thread_pool_size = 2;
+ ExecutorService workers = Executors.newFixedThreadPool(2);
+ CountDownLatch entered = new CountDownLatch(2);
+ CountDownLatch release = new CountDownLatch(1);
+ try (Fixture fixture = new Fixture(partitions, warm, count, workers)) {
+ fixture.session.numPartitionsInBatchMode = 1;
+ fixture.session.splitPartitionBatchSize = 16;
+ fixture.beforeListing = () -> {
+ entered.countDown();
+ try {
+ Assertions.assertTrue(release.await(10, TimeUnit.SECONDS));
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ }
+ };
+ try {
+ fixture.start();
+ Assertions.assertTrue(entered.await(5, TimeUnit.SECONDS),
+ "lazy listing overlap: partitions=" + partitions + ",
warm=" + warm + ", count=" + count);
+ } finally {
+ release.countDown();
+ }
+ List<Long> actual = new ArrayList<>();
+ while (!fixture.consumer.isLastBatch()) {
+ for (TScanRangeLocations range :
fixture.consumer.getNextBatch(128)) {
+ actual.add(range.getLocations().get(0).getBackendId());
+ }
+ }
+ Assertions.assertEquals(partitions, actual.size());
+ Assertions.assertEquals(partitions, new HashSet<>(actual).size());
+ Assertions.assertEquals(partitions, fixture.listed.size());
+
Assertions.assertTrue(fixture.listed.values().stream().allMatch(visits ->
visits == 1));
+ } finally {
+ release.countDown();
+ workers.shutdownNow();
+ Assertions.assertTrue(workers.awaitTermination(10,
TimeUnit.SECONDS));
+ Config.max_external_cache_loader_thread_pool_size = previous;
+ }
+ }
+
+ @Test
+ void choosingBatchModeDoesNotLoadAllPartitionObjects() throws Exception {
+ try (Fixture fixture = new Fixture(1000, false, false)) {
+ Assertions.assertTrue(fixture.node.isBatchMode());
+ Assertions.assertEquals(1000,
fixture.node.getSelectedPartitionNum());
+ Assertions.assertTrue(fixture.node.numApproximateSplits() >= 1000);
+ Mockito.verifyNoInteractions(fixture.cache);
+ Mockito.verify(fixture.cache,
Mockito.never()).getAllPartitionsWithCache(Mockito.any(), Mockito.anyList());
+ }
+ }
+
+ @Test
+ void oneWorkerCanRunBothMetadataAndSplitTasksWithoutWaitingForChildren()
throws Exception {
+ ExecutorService worker = Executors.newSingleThreadExecutor();
+ try (Fixture fixture = new Fixture(1000, false, false, worker)) {
+ fixture.start();
+ List<Long> identities = new ArrayList<>();
+ while (!fixture.consumer.isLastBatch()) {
+ for (TScanRangeLocations range :
fixture.consumer.getNextBatch(128)) {
+ identities.add(range.getLocations().get(0).getBackendId());
+ }
+ }
+ Assertions.assertEquals(1000, identities.size());
+ Assertions.assertEquals(1000, new HashSet<>(identities).size());
+ Assertions.assertEquals(ImmutableList.of(16, 984),
fixture.requests);
+ } finally {
+ worker.shutdownNow();
+ Assertions.assertTrue(worker.awaitTermination(10,
TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ void firstSplitsArriveBeforeTheRemainingMetadataRequest() throws Exception
{
+ try (Fixture fixture = new Fixture(1000, false, false)) {
+ fixture.start();
+ fixture.splits.runAll();
+ Assertions.assertEquals(1, fixture.metadata.pendingTasks());
+ fixture.metadata.runNext();
+ fixture.splits.runAll();
+ Assertions.assertEquals(ImmutableList.of(16), fixture.requests);
+ Assertions.assertFalse(fixture.consumer.getNextBatch(1).isEmpty());
+ Assertions.assertEquals(ImmutableList.of(16), fixture.requests,
+ "first split must not depend on the next large metadata
load");
+ Assertions.assertEquals(1, fixture.metadata.pendingTasks());
+ }
+ }
+
+ @Test
+ void fullScanAndCountPolicyVisitEveryPartitionExactlyOnce() throws
Exception {
+ for (boolean count : new boolean[] {false, true}) {
+ for (boolean warm : new boolean[] {false, true}) {
+ try (Fixture fixture = new Fixture(1000, warm, count)) {
+ fixture.start();
+ List<Long> identities = fixture.drain();
+ Assertions.assertEquals(1000, identities.size());
+ Assertions.assertEquals(1000, new
HashSet<>(identities).size());
+ Assertions.assertEquals(1000, fixture.listed.size());
+
Assertions.assertTrue(fixture.listed.values().stream().allMatch(visits ->
visits == 1));
+ Assertions.assertEquals(warm ? ImmutableList.of() :
ImmutableList.of(16, 984), fixture.requests);
+ }
+ }
+ }
+ }
+
+ @Test
+ void earlyStopCancelsQueuedMetadataAndDirectoryWork() throws Exception {
+ try (Fixture fixture = new Fixture(1000, false, false)) {
+ fixture.start();
+ fixture.splits.runAll();
+ fixture.metadata.runNext();
+ fixture.splits.runAll();
+
Assertions.assertFalse(fixture.consumer.getNextBatch(10).isEmpty());
+ int listed = fixture.listed.size();
+ fixture.assignment.stop();
+ fixture.metadata.runAll();
+ fixture.splits.runAll();
+ Assertions.assertEquals(ImmutableList.of(16), fixture.requests);
+ Assertions.assertEquals(listed, fixture.listed.size());
+ Assertions.assertTrue(fixture.assignment.isStop());
+ }
+ }
+
+ @Test
+ void remoteFailureWakesSplitReadersAndPreservesRootCause() throws
Exception {
+ try (Fixture fixture = new Fixture(1000, false, false)) {
+
Mockito.when(fixture.cache.getExistingPartitionsWithCache(Mockito.any(),
Mockito.anyList()))
+ .thenThrow(new IllegalStateException("HMS request
failed"));
+ fixture.start();
+ fixture.splits.runAll();
+ fixture.metadata.runAll();
+ fixture.splits.runAll();
+ UserException failure =
Assertions.assertThrows(UserException.class,
+ () -> fixture.consumer.getNextBatch(10));
+ Assertions.assertTrue(failure.getMessage().contains("HMS request
failed"));
+
Assertions.assertTrue(failure.getMessage().contains("streaming_table"));
+ Assertions.assertTrue(fixture.listed.isEmpty());
+ }
+ }
+
+ private static class ManualExecutor implements Executor {
+ private final Queue<Runnable> tasks = new ArrayDeque<>();
+
+ @Override
+ public void execute(Runnable task) {
+ tasks.add(task);
+ }
+
+ void runNext() {
+ tasks.remove().run();
+ }
+
+ long pendingTasks() {
+ return tasks.stream().filter(task -> !(task instanceof Future<?>)
|| !((Future<?>) task).isDone()).count();
+ }
+
+ void runAll() {
+ int runs = 0;
+ while (!tasks.isEmpty() && runs++ < 10000) {
+ runNext();
+ }
+ Assertions.assertTrue(tasks.isEmpty(), "blocked producers must
release the executor");
+ }
+ }
+
+ private static class TestNode extends HiveScanNode {
+ private final Executor splits;
+ private final Executor metadata;
+ private final boolean count;
+
+ TestNode(TupleDescriptor descriptor, SessionVariable session, Executor
splits,
+ Executor metadata, boolean count) {
+ super(new PlanNodeId(0), descriptor, false, session, null,
ScanContext.EMPTY);
+ this.splits = splits;
+ this.metadata = metadata;
+ this.count = count;
+ fileSplitter = new FileSplitter(128, 128, 0);
+ }
+
+ @Override
+ protected boolean isBatchModeEnabled() {
+ return true;
+ }
+
+ @Override
+ protected boolean isTableLevelCountStarPushdown() {
+ return count;
+ }
+
+ @Override
+ protected Executor getSplitTaskExecutor() {
+ return splits;
+ }
+
+ @Override
+ protected Executor getMetadataTaskExecutor() {
+ return metadata;
+ }
+
+ @Override
+ protected SummaryProfile getSummaryProfile() {
+ return null;
+ }
+
+ void attach(SplitAssignment assignment) {
+ splitAssignment = assignment;
+ }
+ }
+
+ private static class Fixture implements AutoCloseable {
+ final ManualExecutor splits = new ManualExecutor();
+ final ManualExecutor metadata = new ManualExecutor();
+ final HiveExternalMetaCache cache =
Mockito.mock(HiveExternalMetaCache.class);
+ final HMSCachedClient client = Mockito.mock(HMSCachedClient.class);
+ final Backend backend = new Backend(1, "backend", 9050);
+ final List<Integer> requests = new ArrayList<>();
+ final Map<String, Integer> listed = new ConcurrentHashMap<>();
+ final SessionVariable session = new SessionVariable();
+ Runnable beforeListing = () -> { };
+ final TestNode node;
+ final SplitAssignment assignment;
+ final SplitSource consumer;
+ final Env env = Mockito.mock(Env.class);
+ private MockedStatic<Env> environment;
+
+ Fixture(int count, boolean warm, boolean countPolicy) throws Exception
{
+ this(count, warm, countPolicy, null);
+ }
+
+ Fixture(int count, boolean warm, boolean countPolicy, Executor worker)
throws Exception {
+ HMSExternalTable table = Mockito.mock(HMSExternalTable.class);
+ HMSExternalCatalog catalog =
Mockito.mock(HMSExternalCatalog.class);
+ NameMapping mapping = NameMapping.createForTest("db",
"streaming_table");
+ Mockito.when(table.getName()).thenReturn("streaming_table");
+ Mockito.when(table.getCatalog()).thenReturn(catalog);
+ Mockito.when(table.getOrBuildNameMapping()).thenReturn(mapping);
+
Mockito.when(table.getPartitionColumnTypes(Mockito.any())).thenReturn(ImmutableList.of(Type.INT));
+ Mockito.when(catalog.getClient()).thenReturn(client);
+ Mockito.when(client.getPartitionBatchSize()).thenReturn(1024);
+ Mockito.when(catalog.bindBrokerName()).thenReturn("");
+ TupleDescriptor descriptor = new TupleDescriptor(new TupleId(0));
+ descriptor.setTable(table);
+ session.parallelPipelineTaskNum = 1;
+ node = new TestNode(descriptor, session,
+ worker == null ? splits : worker, worker == null ?
metadata : worker, countPolicy);
+ Map<String, PartitionItem> items = new LinkedHashMap<>();
+ for (int i = 0; i < count; i++) {
+ PartitionKey key =
PartitionKey.createListPartitionKeyWithTypes(
+ ImmutableList.of(new
PartitionValue(Integer.toString(i))), ImmutableList.of(Type.INT), true);
+ items.put("p=" + i, new
ListPartitionItem(ImmutableList.of(key)));
+ }
+ node.setSelectedPartitions(new SelectedPartitions(count, items,
true, false));
+ Mockito.when(cache.getCachedPartitions(Mockito.same(mapping),
Mockito.anyList())).thenAnswer(call ->
+ warm ? Optional.of(partitions(mapping,
call.getArgument(1))) : Optional.empty());
+
Mockito.when(cache.getExistingPartitionsWithCache(Mockito.same(mapping),
Mockito.anyList()))
+ .thenAnswer(call -> {
+ List<List<String>> values = call.getArgument(1);
+ requests.add(values.size());
+ return partitions(mapping, values);
+ });
+ Mockito.when(cache.getFilesByPartitions(Mockito.anyList(),
Mockito.anyBoolean(), Mockito.anyBoolean(),
+ Mockito.isNull(), Mockito.same(table))).thenAnswer(call ->
{
+ beforeListing.run();
+ List<FileCacheValue> files = new ArrayList<>();
+ for (HivePartition partition :
call.<List<HivePartition>>getArgument(0)) {
+ String identity =
partition.getPartitionValues().get(0);
+ listed.merge(identity, 1, Integer::sum);
+ FileCacheValue value = new FileCacheValue();
+
value.setPartitionValues(partition.getPartitionValues());
+ HiveFileStatus file = new HiveFileStatus();
+ file.setPath(LocationPath.of(partition.getPath() +
"/data.parquet"));
+ file.setLength(1);
+ value.getFiles().add(file);
+ files.add(value);
+ }
+ return files;
+ });
+ ExternalMetaCacheMgr manager =
Mockito.mock(ExternalMetaCacheMgr.class);
+ Mockito.when(env.getExtMetaCacheMgr()).thenReturn(manager);
+ Mockito.when(manager.hive(Mockito.anyLong())).thenReturn(cache);
+ FederationBackendPolicy policy =
Mockito.mock(FederationBackendPolicy.class);
+ Mockito.when(policy.numBackends()).thenReturn(1);
+
Mockito.when(policy.computeScanRangeAssignment(Mockito.anyList())).thenAnswer(call
-> {
+ Multimap<Backend, Split> assigned =
LinkedListMultimap.create();
+ assigned.putAll(backend, call.<List<Split>>getArgument(0));
+ return assigned;
+ });
+ assignment = new SplitAssignment(policy, node, (owner, properties,
split, keys, admission) ->
+ new
TScanRangeLocations().setLocations(ImmutableList.of(new TScanRangeLocation()
+ .setBackendId(Long.parseLong(((FileSplit)
split).getPartitionValues().get(0))))),
+ Collections.emptyMap(), Collections.emptyList(), true, 8,
128);
+ node.attach(assignment);
+ consumer = new SplitSource(backend, assignment, 5000);
+ }
+
+ void start() throws Exception {
+ environment = Mockito.mockStatic(Env.class);
+ environment.when(Env::getCurrentEnv).thenReturn(env);
+ Assertions.assertTrue(node.isBatchMode());
+ node.startSplit(1);
+ }
+
+ List<Long> drain() throws Exception {
+ List<Long> values = new ArrayList<>();
+ for (int rounds = 0; rounds < 10000 && !consumer.isLastBatch();
rounds++) {
+ splits.runAll();
+ metadata.runAll();
+ splits.runAll();
+ if (assignment.getAssignedSplits(backend) != null
+ && assignment.getAssignedSplits(backend).isEmpty() &&
metadata.pendingTasks() > 0) {
+ continue;
+ }
+ for (TScanRangeLocations range : consumer.getNextBatch(128)) {
+ values.add(range.getLocations().get(0).getBackendId());
+ }
+ }
+ Assertions.assertTrue(consumer.isLastBatch());
+ return values;
+ }
+
+ @Override
+ public void close() {
+ assignment.stop();
+ metadata.runAll();
+ splits.runAll();
+ if (environment != null) {
+ environment.close();
+ }
+ }
+
+ private static List<HivePartition> partitions(NameMapping mapping,
List<List<String>> values) {
+ List<HivePartition> result = new ArrayList<>();
+ for (List<String> value : values) {
+ result.add(new HivePartition(mapping, false, "parquet",
"s3://bucket/p=" + value.get(0),
+ value, Collections.emptyMap()));
+ }
+ return result;
+ }
+ }
+}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/datasource/hive/source/HiveStreamingSplitTest.java
b/fe/fe-core/src/test/java/org/apache/doris/datasource/hive/source/HiveStreamingSplitTest.java
index ed3a7d41458..2d78b868887 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/datasource/hive/source/HiveStreamingSplitTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/datasource/hive/source/HiveStreamingSplitTest.java
@@ -34,6 +34,7 @@ import org.apache.doris.datasource.SplitProducer;
import org.apache.doris.datasource.SplitSource;
import org.apache.doris.datasource.SplitSourceManager;
import org.apache.doris.datasource.hive.HMSExternalCatalog;
+import org.apache.doris.datasource.hive.HMSExternalDatabase;
import org.apache.doris.datasource.hive.HMSExternalTable;
import org.apache.doris.datasource.hive.HiveExternalMetaCache;
import org.apache.doris.datasource.hive.HivePartition;
@@ -524,7 +525,15 @@ public class HiveStreamingSplitTest {
context.setStatementContext(statement);
context.setThreadLocalInfo();
HMSExternalCatalog catalog =
Mockito.mock(HMSExternalCatalog.class);
+ HMSExternalDatabase database =
Mockito.mock(HMSExternalDatabase.class);
Mockito.when(table.getCatalog()).thenReturn(catalog);
+ // Mode selection resolves the statement snapshot before loading
partition metadata.
+ // Keep the mocked table's identity complete, as it is on a real
analyzed scan.
+ Mockito.doReturn(database).when(table).getDatabase();
+ Mockito.doReturn(catalog).when(database).getCatalog();
+ Mockito.when(catalog.getName()).thenReturn("hms");
+ Mockito.when(database.getFullName()).thenReturn("db");
+ Mockito.when(table.getName()).thenReturn("streaming_table");
Mockito.when(catalog.bindBrokerName()).thenReturn("");
Mockito.when(table.getFileFormatType(Mockito.any())).thenReturn(TFileFormatType.FORMAT_PARQUET);
org.apache.doris.catalog.Env env =
Mockito.mock(org.apache.doris.catalog.Env.class);
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/planner/FederationBackendPolicyTest.java
b/fe/fe-core/src/test/java/org/apache/doris/planner/FederationBackendPolicyTest.java
index f6e8efd5294..f5a6d613a1b 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/planner/FederationBackendPolicyTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/planner/FederationBackendPolicyTest.java
@@ -24,6 +24,7 @@ import org.apache.doris.common.util.LocationPath;
import org.apache.doris.datasource.FederationBackendPolicy;
import org.apache.doris.datasource.FileSplit;
import org.apache.doris.datasource.NodeSelectionStrategy;
+import org.apache.doris.datasource.SplitWeight;
import org.apache.doris.resource.computegroup.ComputeGroupMgr;
import org.apache.doris.spi.Split;
import org.apache.doris.system.Backend;
@@ -51,11 +52,129 @@ import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
+import java.util.concurrent.atomic.AtomicInteger;
public class FederationBackendPolicyTest {
@Mocked
private Env env;
+ @Test
+ public void testSingleBackendRemoteBatchesSkipHashing() throws
UserException {
+ Backend backend = mockSingleBackend();
+ boolean previousLocalScheduling =
Config.split_assigner_optimized_local_scheduling;
+ try {
+ for (boolean localScheduling : new boolean[] {false, true}) {
+ Config.split_assigner_optimized_local_scheduling =
localScheduling;
+ for (NodeSelectionStrategy strategy :
NodeSelectionStrategy.values()) {
+ FederationBackendPolicy policy = new
FederationBackendPolicy(strategy);
+ policy.init();
+ AtomicInteger hashReads = new AtomicInteger();
+ long expectedWeight = 0;
+ for (int batchSize : new int[] {0, 1, 8, 128, 3}) {
+ List<Split> splits = new ArrayList<>();
+ for (int i = 0; i < batchSize; i++) {
+ SplitWeight weight = SplitWeight.fromProportion((i
% 4 + 1) / 4.0);
+ String[] hosts = i % 2 == 0 ? new String[]
{backend.getHost()} : null;
+ FileSplit split = new
FileSplit(LocationPath.of("s3://bucket/file-" + i),
+ 0, 100, 100, 0, hosts,
Collections.emptyList()) {
+ @Override
+ public SplitWeight getSplitWeight() {
+ return weight;
+ }
+
+ @Override
+ public String getConsistentHashString() {
+ hashReads.incrementAndGet();
+ return super.getConsistentHashString();
+ }
+ };
+
split.setAlternativeHosts(Collections.singletonList("stale-host"));
+ splits.add(split);
+ expectedWeight += weight.getRawValue();
+ }
+ List<Split> expectedOrder = new ArrayList<>(splits);
+ Collections.shuffle(expectedOrder, new
Random(123456789L));
+ Multimap<Backend, Split> assignment =
policy.computeScanRangeAssignment(splits);
+ Assert.assertEquals(batchSize, assignment.size());
+ Assert.assertEquals(expectedOrder, new
ArrayList<>(assignment.get(backend)));
+ Assert.assertEquals(expectedWeight,
+
policy.getAssignedWeightPerBackend().get(backend).longValue());
+ for (Split split : splits) {
+ Assert.assertEquals(Collections.emptyList(),
split.getAlternativeHosts());
+ }
+ }
+ Assert.assertEquals("One eligible backend does not need
split hashing", 0, hashReads.get());
+ }
+ }
+ } finally {
+ Config.split_assigner_optimized_local_scheduling =
previousLocalScheduling;
+ }
+ }
+
+ @Test
+ public void testSingleBackendPreservesLocalOnlySplitChecks() throws
UserException {
+ Backend backend = mockSingleBackend();
+ for (NodeSelectionStrategy strategy : NodeSelectionStrategy.values()) {
+ FederationBackendPolicy policy = new
FederationBackendPolicy(strategy);
+ policy.init();
+ FileSplit localSplit = localOnlySplit(backend.getHost());
+ FileSplit remoteSplit = genFileSplit("s3://bucket/remote", 100,
100);
+ List<Split> splits = new ArrayList<>();
+ splits.add(localSplit);
+ splits.add(remoteSplit);
+ Multimap<Backend, Split> assignment =
policy.computeScanRangeAssignment(splits);
+ Assert.assertEquals(2, assignment.get(backend).size());
+ Assert.assertTrue(assignment.get(backend).contains(localSplit));
+ Assert.assertTrue(assignment.get(backend).contains(remoteSplit));
+ Assertions.assertThrows(UserException.class, () ->
policy.computeScanRangeAssignment(
+ new
ArrayList<>(Collections.singletonList(localOnlySplit("unavailable-host")))));
+ }
+ }
+
+ @Test
+ public void testSingleBackendWeightOverflow() throws UserException {
+ Backend backend = mockSingleBackend();
+ FederationBackendPolicy policy = new FederationBackendPolicy();
+ policy.init();
+ policy.getAssignedWeightPerBackend().put(backend, Long.MAX_VALUE);
+ Assertions.assertThrows(ArithmeticException.class, () ->
policy.computeScanRangeAssignment(
+ new
ArrayList<>(Collections.singletonList(genFileSplit("s3://bucket/remote", 100,
100)))));
+ Assert.assertEquals(Long.MAX_VALUE,
policy.getAssignedWeightPerBackend().get(backend).longValue());
+ }
+
+ private Backend mockSingleBackend() {
+ SystemInfoService service = new SystemInfoService();
+ Backend backend = new Backend(10002L, "172.30.0.100", 9050);
+ backend.setAlive(true);
+ service.addBackend(backend);
+ ComputeGroupMgr cgmgr = new ComputeGroupMgr(service);
+ new MockUp<Env>() {
+ @Mock
+ public SystemInfoService getCurrentSystemInfo() {
+ return service;
+ }
+
+ @Mock
+ public ComputeGroupMgr getComputeGroupMgr() {
+ return cgmgr;
+ }
+ };
+ return backend;
+ }
+
+ private FileSplit localOnlySplit(String host) {
+ FileSplit split = new FileSplit(LocationPath.of("file:///local/file"),
0, 100, 100, 0,
+ new String[] {host}, Collections.emptyList()) {
+ @Override
+ public boolean isRemotelyAccessible() {
+ return false;
+ }
+ };
+ split.setSelfSplitWeight(100L);
+ split.setTargetSplitSize(100L);
+ return split;
+ }
+
@Test
public void testRemoteSplits() throws UserException {
SystemInfoService service = new SystemInfoService();
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]