diff --git a/processing/src/main/java/org/apache/druid/segment/CursorFactory.java b/processing/src/main/java/org/apache/druid/segment/CursorFactory.java
index 486625bb7f3b..e6665f13c411 100644
--- a/processing/src/main/java/org/apache/druid/segment/CursorFactory.java
+++ b/processing/src/main/java/org/apache/druid/segment/CursorFactory.java
@@ -54,6 +54,20 @@ default AsyncCursorHolder makeCursorHolderAsync(CursorBuildSpec spec)
);
}
+ /**
+ * Optional preloading for a given {@link CursorBuildSpec}, which starts doing the loading that a later
+ * {@link #makeCursorHolderAsync(CursorBuildSpec)} would otherwise do on demand. See {@link CursorPrefetch} for the
+ * lifecycle of the returned handle, in particular that it must stay open for the warmed-up parts to stay resident.
+ *
+ * A warm-up that cannot be started, for instance because the segment cache has no room for what it would load, is
+ * reported through the returned handle rather than thrown. This method throws only for a spec that the factory
+ * cannot serve at all (which {@link #makeCursorHolderAsync(CursorBuildSpec)} would reject the same way).
+ */
+ default CursorPrefetch prefetch(CursorBuildSpec spec)
+ {
+ return CursorPrefetch.none();
+ }
+
/**
* Returns the {@link RowSignature} of the data available from this cursor factory. For mutable segments, even though
* the signature may evolve over time, any particular object returned by this method is an immutable snapshot.
diff --git a/processing/src/main/java/org/apache/druid/segment/CursorPrefetch.java b/processing/src/main/java/org/apache/druid/segment/CursorPrefetch.java
new file mode 100644
index 000000000000..32bcf867a916
--- /dev/null
+++ b/processing/src/main/java/org/apache/druid/segment/CursorPrefetch.java
@@ -0,0 +1,87 @@
+/*
+ * 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.druid.segment;
+
+import org.apache.druid.common.asyncresource.SettableAsyncResource;
+
+import javax.annotation.Nullable;
+import java.util.List;
+
+/**
+ * Handle on a best-effort warm-up started by {@link CursorFactory#prefetch(CursorBuildSpec)}, which does actions such
+ * as downloading column files and deserializing column holders.
+ *
+ *
Lifecycle
+ *
+ *
The handle is ready ({@link #isReady()}) once the warm-up is complete, whether it succeeded or failed;
+ * {@link #get()} returns {@link Stats} on success and throws the failure otherwise.
+ *
Keep the handle open for as long as the warmed-up parts should stay resident. Closing it after it is ready
+ * releases the holds that pin them. The cursor build that benefits from the warm-up takes its own pins on the
+ * calling thread, so close the handle only once that {@code makeCursorHolderAsync} call has returned, or the parts
+ * may be evicted in between and loaded twice.
+ *
Closing the handle before it is ready cancels the warm-up, pending downloads are canceled and the pins
+ * released, and {@link #get()} then throws
+ * {@link org.apache.druid.common.asyncresource.AsyncResourceCanceledException}.
+ *
Close is not idempotent; close exactly once.
+ *
+ */
+public class CursorPrefetch extends SettableAsyncResource
+{
+ /**
+ * Stats about the prefetch plan.
+ */
+ public record Stats(List bundles, int plannedRuns, long plannedBytes)
+ {
+ public static final Stats NONE = new Stats(List.of(), 0, 0L);
+ }
+
+ /**
+ * @param canceler optional callback invoked from {@link #close()} when the handle is closed before the warm-up has
+ * completed for producers that support cancellation.
+ */
+ public CursorPrefetch(@Nullable Runnable canceler)
+ {
+ super(false);
+ if (canceler != null) {
+ setCanceler(canceler);
+ }
+ }
+
+ /**
+ * An already-complete prefetch that did nothing and pins nothing, for sources that are always fully resident.
+ */
+ public static CursorPrefetch none()
+ {
+ final CursorPrefetch prefetch = new CursorPrefetch(null);
+ prefetch.set(Stats.NONE, null);
+ return prefetch;
+ }
+
+ /**
+ * An already-complete prefetch whose warm-up could not be started, so it pins nothing; {@link #get()} throws
+ * {@code failure}.
+ */
+ public static CursorPrefetch failed(Throwable failure)
+ {
+ final CursorPrefetch prefetch = new CursorPrefetch(null);
+ prefetch.setException(failure);
+ return prefetch;
+ }
+}
diff --git a/processing/src/main/java/org/apache/druid/segment/FilteredCursorFactory.java b/processing/src/main/java/org/apache/druid/segment/FilteredCursorFactory.java
index 41ceec5048f1..ae0d8a8ca226 100644
--- a/processing/src/main/java/org/apache/druid/segment/FilteredCursorFactory.java
+++ b/processing/src/main/java/org/apache/druid/segment/FilteredCursorFactory.java
@@ -41,21 +41,19 @@ public FilteredCursorFactory(CursorFactory delegate, @Nullable DimFilter filter)
@Override
public CursorHolder makeCursorHolder(CursorBuildSpec spec)
{
- if (filter == null) {
- return delegate.makeCursorHolder(spec);
- } else {
- return delegate.makeCursorHolder(specWithFilter(spec));
- }
+ return delegate.makeCursorHolder(delegateSpec(spec));
}
@Override
public AsyncCursorHolder makeCursorHolderAsync(CursorBuildSpec spec)
{
- if (filter == null) {
- return delegate.makeCursorHolderAsync(spec);
- } else {
- return delegate.makeCursorHolderAsync(specWithFilter(spec));
- }
+ return delegate.makeCursorHolderAsync(delegateSpec(spec));
+ }
+
+ @Override
+ public CursorPrefetch prefetch(CursorBuildSpec spec)
+ {
+ return delegate.prefetch(delegateSpec(spec));
}
@Override
@@ -71,8 +69,11 @@ public ColumnCapabilities getColumnCapabilities(String column)
return delegate.getColumnCapabilities(column);
}
- private CursorBuildSpec specWithFilter(final CursorBuildSpec spec)
+ private CursorBuildSpec delegateSpec(final CursorBuildSpec spec)
{
+ if (filter == null) {
+ return spec;
+ }
return CursorBuildSpec.builder(spec).andBaseFilter(Filters.toFilter(filter)).build();
}
}
diff --git a/processing/src/main/java/org/apache/druid/segment/PartialQueryableIndexCursorFactory.java b/processing/src/main/java/org/apache/druid/segment/PartialQueryableIndexCursorFactory.java
index faab37ce673c..870587b53505 100644
--- a/processing/src/main/java/org/apache/druid/segment/PartialQueryableIndexCursorFactory.java
+++ b/processing/src/main/java/org/apache/druid/segment/PartialQueryableIndexCursorFactory.java
@@ -19,8 +19,10 @@
package org.apache.druid.segment;
+import org.apache.druid.collections.ResourceHolder;
import org.apache.druid.common.asyncresource.AsyncResource;
import org.apache.druid.common.asyncresource.AsyncResources;
+import org.apache.druid.common.asyncresource.SettableAsyncResource;
import org.apache.druid.error.DruidException;
import org.apache.druid.java.util.common.io.Closer;
import org.apache.druid.query.Order;
@@ -76,6 +78,10 @@
* {@link org.apache.druid.segment.loading.AcquireMode#PARTIAL_RULE_HELD}), both paths plan only over the bundles it
* accepts, and a spec that nothing servable can answer gets an {@link EmptyCursorHolder}. Accepted bundles that are not
* resident are still downloaded by the async path as usual.
+ *
+ * Prefetch. {@link #prefetch} shares the async path's machinery but, instead of a cursor holder, produces a
+ * {@link CursorPrefetch} that owns the bundle holds. A later {@link #makeCursorHolderAsync} for the same spec (made
+ * while the prefetch is still open) plans no downloads as everything is resident.
*/
public class PartialQueryableIndexCursorFactory implements CursorFactory
{
@@ -157,130 +163,196 @@ public AsyncCursorHolder makeCursorHolderAsync(CursorBuildSpec spec)
);
}
+ @Override
+ public CursorPrefetch prefetch(CursorBuildSpec spec)
+ {
+ final PartialQueryableIndex.CursorPrefetchPlan plan = index.planCursorPrefetch(spec, servableBundles);
+ if (plan.bundles().isEmpty()) {
+ return CursorPrefetch.none();
+ }
+ final PendingDownloads pending;
+ try {
+ pending = acquireHoldsAndSubmitRuns(plan.bundles());
+ }
+ catch (Throwable t) {
+ return CursorPrefetch.failed(t);
+ }
+ final CursorPrefetch prefetch = new CursorPrefetch(pending.canceler());
+ completeOnDownloadExecutor(
+ pending,
+ prefetch,
+ () -> {
+ materializeRequiredColumns(plan.bundles());
+ final Closeable holds = releasers(pending.holdReleases());
+ return new ResourceHolder<>()
+ {
+ @Override
+ public CursorPrefetch.Stats get()
+ {
+ return pending.stats();
+ }
+
+ @Override
+ public void close()
+ {
+ CloseableUtils.closeAndWrapExceptions(holds);
+ }
+ };
+ }
+ );
+ return prefetch;
+ }
+
/**
- * Generalized async-holder build over one or more bundles. Each {@link PartialQueryableIndex.PrefetchBundle}
- * mounts its cache-layer bundle (its own {@link BundleHoldRelease}, since eviction is per-bundle) and submits one
- * download task per planned range read. Once every run of every bundle is resident, {@link #produceHolder} runs as
- * its own download-executor task and materializes each bundle's required columns and builds the cursor holder, all
- * inside every bundle's hold handshake (deserialization and holder construction both touch the container mmaps, see
- * {@link #buildHolderUnderHolds}); the produced holder takes ownership of {@code inner} plus every bundle hold.
+ * Builds an async-holder of one or more bundles using {@link #acquireHoldsAndSubmitRuns} on the calling
+ * thread, then {@link #completeOnDownloadExecutor} with a continuation that materializes each bundle's required
+ * columns and builds the cursor holder. The produced holder takes ownership of all closeables.
*/
private AsyncCursorHolder buildAsyncCursorHolder(
List bundles,
Supplier innerBuilder
)
+ {
+ final PendingDownloads pending = acquireHoldsAndSubmitRuns(bundles);
+ final AsyncCursorHolder asyncHolder = new AsyncCursorHolder(pending.canceler());
+ completeOnDownloadExecutor(
+ pending,
+ asyncHolder,
+ () -> {
+ materializeRequiredColumns(bundles);
+ final CursorHolder inner = innerBuilder.get();
+ return ResourceHolder.fromCloseable(wrapWithBundleRelease(inner, releasers(pending.holdReleases())));
+ }
+ );
+ return asyncHolder;
+ }
+
+ /**
+ * The calling-thread half of a cursor build or prefetch. Each {@link PartialQueryableIndex.PrefetchBundle} mounts
+ * its cache-layer bundle (its own {@link BundleHoldRelease}, since eviction is per-bundle) and submits one download
+ * task per planned range read under that hold. Returns the holds and the collected downloads.
+ */
+ private PendingDownloads acquireHoldsAndSubmitRuns(List bundles)
{
final List holdReleases = new ArrayList<>(bundles.size());
+ final List> runDownloads = new ArrayList<>();
try {
- final List> runDownloads = new ArrayList<>();
+ final List bundleNames = new ArrayList<>(bundles.size());
+ long plannedBytes = 0;
for (PartialQueryableIndex.PrefetchBundle bundle : bundles) {
final BundleHoldRelease holdRelease = new BundleHoldRelease(bundleAcquirer.acquire(bundle.bundleName()));
holdReleases.add(holdRelease);
+ bundleNames.add(bundle.bundleName());
// Plan the bundle's range reads only now, under its freshly-acquired hold
for (PartialSegmentFileMapperV10.PlannedFetch fetch : bundle.planFetches()) {
+ plannedBytes += fetch.run().length();
runDownloads.add(submitRunFetch(bundle.bundleName(), fetch, holdRelease));
}
}
- final AsyncResource> downloaded = AsyncResources.collect(runDownloads);
-
- // Canceler runs if the awaiter closes this holder before it's ready (e.g. query cancel/timeout). Close the
- // collected resource to cancel every run download that hasn't begun its deep-storage read yet (queued tasks
- // are skipped; tasks parked on the download executor's permit are interrupted out of the interruptible wait
- // before doing any I/O), then request the hold release on every bundle through the handshake. Once the holder is
- // produced and handed to set(), ownership transfers to the awaiter, which drains it via close() (cancel) or
- // release() (success); each bundle's once-guard keeps its hold release safe across all of these paths.
- final AsyncCursorHolder asyncHolder = new AsyncCursorHolder(() -> {
- CloseableUtils.closeAndSuppressExceptions(downloaded, ignored -> {});
- holdReleases.forEach(BundleHoldRelease::requestRelease);
- });
- // This callback can run on ANY thread: the download-executor thread that completed the last run, or, whenever
- // every run finished before registration (always true when there was nothing to download, since an empty
- // collect completes in its constructor), synchronously on THIS thread, because addReadyCallback on an
- // already-ready resource fires inline. So do no real work here: propagate failure/cancellation inline, and hop
- // the success path to the download executor, where the body deserializes columns and may even hit deep storage,
- // neither of which may run on a processing thread.
- downloaded.addReadyCallback(() -> {
- try {
- // ready, so never blocks; throws the run-download failure (or cancellation) if any. Failing here rather
- // than in the continuation keeps a canceled build from queueing a pointless continuation task.
- downloaded.get();
- }
- catch (Throwable t) {
- failHolder(holdReleases, asyncHolder, t);
- return;
- }
- try {
- bundleAcquirer.submitDownload(() -> {
- produceHolder(downloaded, holdReleases, bundles, innerBuilder, asyncHolder);
- return "produce";
- });
- }
- catch (Throwable t) {
- // the continuation couldn't even be submitted (e.g. executor shutdown rejection)
- failHolder(holdReleases, asyncHolder, t);
- }
- });
- return asyncHolder;
+ return new PendingDownloads(
+ holdReleases,
+ AsyncResources.collect(runDownloads),
+ new CursorPrefetch.Stats(List.copyOf(bundleNames), runDownloads.size(), plannedBytes)
+ );
}
catch (Throwable t) {
- // Failure while submitting downloads / wiring up the holder (e.g. submitDownload shutdown rejection). A run
- // download submitted before the failure may already be in flight, so release every bundle hold through the
- // handshake (requestRelease defers to the last in-flight body) rather than dropping it directly mid-mapFile().
- throw CloseableUtils.closeAndWrapInCatch(t, () -> holdReleases.forEach(BundleHoldRelease::requestRelease));
+ // Failure while acquiring holds or submitting downloads (e.g. a bundle reservation finding no room, or a
+ // submitDownload shutdown rejection). Unwind what was set up before it: cancel every run download submitted so
+ // far (the collect never took them over, so they are still ours to close), then release every bundle hold through
+ // the handshake (requestRelease defers to the last in-flight body) rather than dropping it directly
+ // mid-mapFile().
+ throw CloseableUtils.closeAndWrapInCatch(
+ t,
+ () -> {
+ runDownloads.forEach(run -> CloseableUtils.closeAndSuppressExceptions(run, ignored -> {}));
+ holdReleases.forEach(BundleHoldRelease::requestRelease);
+ }
+ );
}
}
/**
- * Continuation of {@link #buildAsyncCursorHolder} once every run download is ready, always running as its own task
- * on the download executor (never on the thread that observed readiness): surface any download failure, materialize
- * columns and build the cursor holder under every hold, and hand the result to the async holder.
+ * The asynchronous half of a cursor build or prefetch, once every run download is ready, runs
+ * {@code produceUnderHolds} as its own download-executor task inside every bundle's hold handshake (see
+ * {@link #produce}) and hand what it produced to {@code target}, which takes ownership of it (closing it releases
+ * every bundle hold, so the producer must fold {@link #releasers} into it).
*/
- private void produceHolder(
- AsyncResource> downloaded,
- List holdReleases,
- List bundles,
- Supplier innerBuilder,
- AsyncCursorHolder asyncHolder
+ private void completeOnDownloadExecutor(
+ PendingDownloads pending,
+ SettableAsyncResource target,
+ Supplier> produceUnderHolds
)
{
- final CursorHolder holder;
+ // This callback can run on ANY thread: the download-executor thread that completed the last run, or, whenever
+ // every run finished before registration, synchronously on THIS thread, because addReadyCallback on an
+ // already-ready resource fires inline. So do no real work here: propagate failure/cancellation inline, and hop
+ // the success path to the download executor.
+ pending.downloaded().addReadyCallback(() -> {
+ try {
+ // ready, so never blocks; throws the run-download failure (or cancellation) if any. Failing here rather
+ // than in the continuation keeps a canceled build from queueing a pointless continuation task.
+ pending.downloaded().get();
+ }
+ catch (Throwable t) {
+ fail(pending, target, t);
+ return;
+ }
+ try {
+ bundleAcquirer.submitDownload(() -> {
+ produce(pending, target, produceUnderHolds);
+ return "produce";
+ });
+ }
+ catch (Throwable t) {
+ // the continuation couldn't even be submitted (e.g. executor shutdown rejection)
+ fail(pending, target, t);
+ }
+ });
+ }
+
+ /**
+ * Continuation of {@link #completeOnDownloadExecutor} once every run download is ready, always running as its own
+ * task on the download executor (never on the thread that observed readiness). The hand-off happens only after the
+ * handshakes are closed again.
+ */
+ private static void produce(
+ PendingDownloads pending,
+ SettableAsyncResource target,
+ Supplier> produceUnderHolds
+ )
+ {
+ final ResourceHolder produced;
try {
- // the ready callback only submits this continuation on success, but the awaiter may close the resource in the
- // window before this task runs; re-checking surfaces that cancellation instead of building a doomed holder
- downloaded.get();
- holder = buildHolderUnderHolds(holdReleases, 0, bundles, innerBuilder);
- if (holder == null) {
+ // the ready callback only submits this continuation on success, but the consumer may close the target in the
+ // window before this task runs; re-checking surfaces such a cancellation
+ pending.downloaded().get();
+ produced = runUnderHolds(pending.holdReleases(), 0, produceUnderHolds);
+ if (produced == null) {
// a concurrent cancel requested a hold release before we could open the handshake on every bundle; the
- // awaiter is gone, so release the rest of the holds and surface the cancellation
- failHolder(
- holdReleases,
- asyncHolder,
- DruidException.defensive("Async cursor holder was closed before the cursor holder could be built")
- );
+ // consumer is gone, so release the rest of the holds and surface the cancellation
+ fail(pending, target, DruidException.defensive("Async resource was closed before it could be produced"));
return;
}
}
catch (Throwable t) {
- failHolder(holdReleases, asyncHolder, t);
+ fail(pending, target, t);
return;
}
- if (!asyncHolder.set(holder)) {
- // wrapper was closed (awaiter canceled) while we were producing the holder; close it ourselves so the
- // holder, its inner, and the bundle holds don't leak.
- holder.close();
+ if (!target.set(produced)) {
+ // the target was closed (consumer canceled) while we were producing; close what we produced ourselves so it,
+ // and the bundle holds it owns, don't leak.
+ produced.close();
}
}
/**
- * Shared failure path: request every bundle hold's release and fail the async holder. Releases go through the
- * {@link BundleHoldRelease} handshake (never dropped directly) because failure can be observed while a sibling
- * download is still mid-{@code mapFile()}; setException on an already-closed async holder is a silent no-op, which
- * is the desired behavior when the awaiter canceled.
+ * Shared failure path: unwind the downloads and holds (see {@link PendingDownloads#unwind}) and fail the target.
+ * Failing the target clears its canceler, so this is the only chance to cancel the sibling runs of a failed one.
*/
- private static void failHolder(List holdReleases, AsyncCursorHolder asyncHolder, Throwable t)
+ private static void fail(PendingDownloads pending, SettableAsyncResource> target, Throwable t)
{
- holdReleases.forEach(BundleHoldRelease::requestRelease);
- asyncHolder.setException(t);
+ pending.unwind();
+ target.setException(t);
}
@Override
@@ -396,31 +468,95 @@ private static Closeable releasers(List holdReleases)
}
/**
- * Recursively nest {@link BundleHoldRelease#runDownloadBody(Supplier)} across every hold, then (with all handshakes
- * open) materialize each bundle's required columns, build the inner cursor holder, and wrap it with ownership of
- * every hold. Returns {@code null} if any hold had already been requested released (concurrent cancel), the mmaps
- * it guards may be about to unmap, so nothing may be read and no holder can be built.
+ * Runs {@code body} with every bundle's handshake open, by nesting one {@link BundleHoldRelease#runDownloadBody}
+ * per hold. Returns {@code null} without running {@code body} if any hold has already been asked to release
+ * (concurrent cancel), since its mmaps may be about to go away.
*/
@Nullable
- private static CursorHolder buildHolderUnderHolds(
- List holdReleases,
- int nextHold,
- List bundles,
- Supplier innerBuilder
- )
+ private static T runUnderHolds(List holdReleases, int nextHold, Supplier body)
{
if (nextHold < holdReleases.size()) {
- return holdReleases.get(nextHold)
- .runDownloadBody(() -> buildHolderUnderHolds(holdReleases, nextHold + 1, bundles, innerBuilder));
+ return holdReleases.get(nextHold).runDownloadBody(() -> runUnderHolds(holdReleases, nextHold + 1, body));
}
+ return body.get();
+ }
+
+ /**
+ * Materialize (deserialize and memoize) each bundle's required columns. Touches the container mmaps, so call only
+ * with every bundle's handshake open (see {@link #runUnderHolds}).
+ */
+ private static void materializeRequiredColumns(List bundles)
+ {
for (PartialQueryableIndex.PrefetchBundle bundle : bundles) {
for (String column : bundle.requiredColumns()) {
bundle.rowSelector().getColumnHolder(column);
}
}
- final CursorHolder inner = innerBuilder.get();
- // The produced holder takes ownership of inner and every bundle hold; closing it releases all of them.
- return wrapWithBundleRelease(inner, releasers(holdReleases));
+ }
+
+ /**
+ * The calling-thread result of {@link #acquireHoldsAndSubmitRuns}: every bundle's hold, the collected run
+ * downloads submitted under them, and what was planned (for {@link CursorPrefetch.Stats}).
+ */
+ private static final class PendingDownloads
+ {
+ private final List holdReleases;
+ private final AsyncResource> downloaded;
+ private final CursorPrefetch.Stats stats;
+ private final AtomicBoolean downloadsClosed = new AtomicBoolean(false);
+
+ PendingDownloads(
+ List holdReleases,
+ AsyncResource> downloaded,
+ CursorPrefetch.Stats stats
+ )
+ {
+ this.holdReleases = holdReleases;
+ this.downloaded = downloaded;
+ this.stats = stats;
+ }
+
+ List holdReleases()
+ {
+ return holdReleases;
+ }
+
+ AsyncResource> downloaded()
+ {
+ return downloaded;
+ }
+
+ CursorPrefetch.Stats stats()
+ {
+ return stats;
+ }
+
+ /**
+ * Canceler for the resource being produced, run if its consumer closes it before it's ready (e.g. query
+ * cancel/timeout): {@link #unwind}. Once the result is produced and handed to set(), ownership transfers to the
+ * consumer, which drains it via close() (cancel) or release() (success); each bundle's once-guard keeps its hold
+ * release safe across all of these paths.
+ */
+ Runnable canceler()
+ {
+ return this::unwind;
+ }
+
+ /**
+ * Unwinds the downloads and holds because the consumer canceled or a run download failed. Closes the collected
+ * resource to cancel every download that hasn't begun its deep-storage read yet (queued tasks are skipped;
+ * tasks parked on the load permit are interrupted out of the interruptible wait before doing any I/O), then
+ * requests the hold release on every bundle through the handshake. Safe to reach more than once, and from inside
+ * itself: closing the collected resource fails it, which runs the failure path inline. The close happens at most
+ * once and the release requests are idempotent.
+ */
+ void unwind()
+ {
+ if (downloadsClosed.compareAndSet(false, true)) {
+ CloseableUtils.closeAndSuppressExceptions(downloaded, ignored -> {});
+ }
+ holdReleases.forEach(BundleHoldRelease::requestRelease);
+ }
}
/**
diff --git a/processing/src/main/java/org/apache/druid/segment/ProjectCursorFactory.java b/processing/src/main/java/org/apache/druid/segment/ProjectCursorFactory.java
index e6674c9a5f04..c2c9ba8ceddc 100644
--- a/processing/src/main/java/org/apache/druid/segment/ProjectCursorFactory.java
+++ b/processing/src/main/java/org/apache/druid/segment/ProjectCursorFactory.java
@@ -53,6 +53,12 @@ public AsyncCursorHolder makeCursorHolderAsync(final CursorBuildSpec spec)
return delegate.makeCursorHolderAsync(delegateSpec(spec));
}
+ @Override
+ public CursorPrefetch prefetch(final CursorBuildSpec spec)
+ {
+ return delegate.prefetch(delegateSpec(spec));
+ }
+
@Override
public RowSignature getRowSignature()
{
diff --git a/processing/src/main/java/org/apache/druid/segment/RestrictedCursorFactory.java b/processing/src/main/java/org/apache/druid/segment/RestrictedCursorFactory.java
index f2c56ecb78a2..85dbcee3dfe5 100644
--- a/processing/src/main/java/org/apache/druid/segment/RestrictedCursorFactory.java
+++ b/processing/src/main/java/org/apache/druid/segment/RestrictedCursorFactory.java
@@ -56,13 +56,19 @@ public RestrictedCursorFactory(
@Override
public CursorHolder makeCursorHolder(CursorBuildSpec spec)
{
- return delegate.makeCursorHolder(policy.visit(spec));
+ return delegate.makeCursorHolder(delegateSpec(spec));
}
@Override
public AsyncCursorHolder makeCursorHolderAsync(CursorBuildSpec spec)
{
- return delegate.makeCursorHolderAsync(policy.visit(spec));
+ return delegate.makeCursorHolderAsync(delegateSpec(spec));
+ }
+
+ @Override
+ public CursorPrefetch prefetch(CursorBuildSpec spec)
+ {
+ return delegate.prefetch(delegateSpec(spec));
}
@Override
@@ -77,4 +83,9 @@ public ColumnCapabilities getColumnCapabilities(String column)
{
return delegate.getColumnCapabilities(column);
}
+
+ private CursorBuildSpec delegateSpec(CursorBuildSpec spec)
+ {
+ return policy.visit(spec);
+ }
}
diff --git a/processing/src/main/java/org/apache/druid/segment/UnnestCursorFactory.java b/processing/src/main/java/org/apache/druid/segment/UnnestCursorFactory.java
index a8897d565db9..7a27a6fbf622 100644
--- a/processing/src/main/java/org/apache/druid/segment/UnnestCursorFactory.java
+++ b/processing/src/main/java/org/apache/druid/segment/UnnestCursorFactory.java
@@ -79,7 +79,7 @@ public UnnestCursorFactory(
public CursorHolder makeCursorHolder(CursorBuildSpec spec)
{
final UnnestFilterSplit filterSplit = computeFilterSplit(spec);
- final CursorBuildSpec unnestBuildSpec = transformCursorBuildSpec(spec, unnestColumn, filterSplit.getBaseTableFilter());
+ final CursorBuildSpec unnestBuildSpec = delegateSpec(spec, filterSplit);
final Closer closer = Closer.create();
// base holder is built lazily on first asCursor()/getOrdering() and registered for close at that point
@@ -93,7 +93,7 @@ public CursorHolder makeCursorHolder(CursorBuildSpec spec)
public AsyncCursorHolder makeCursorHolderAsync(CursorBuildSpec spec)
{
final UnnestFilterSplit filterSplit = computeFilterSplit(spec);
- final CursorBuildSpec unnestBuildSpec = transformCursorBuildSpec(spec, unnestColumn, filterSplit.getBaseTableFilter());
+ final CursorBuildSpec unnestBuildSpec = delegateSpec(spec, filterSplit);
// Build the base-table holder asynchronously (a partial base segment downloads its required columns here), then
// wrap the ready holder in the unnest holder, which owns closing it.
@@ -102,6 +102,23 @@ public AsyncCursorHolder makeCursorHolderAsync(CursorBuildSpec spec)
.transform(baseHolder -> unnestCursorHolder(spec, filterSplit, baseHolder, Suppliers.ofInstance(baseHolder)));
}
+ @Override
+ public CursorPrefetch prefetch(CursorBuildSpec spec)
+ {
+ // the base table is the only part that loads on demand, so warm it up with exactly the spec the async build uses
+ return baseCursorFactory.prefetch(delegateSpec(spec));
+ }
+
+ private CursorBuildSpec delegateSpec(CursorBuildSpec spec)
+ {
+ return delegateSpec(spec, computeFilterSplit(spec));
+ }
+
+ private CursorBuildSpec delegateSpec(CursorBuildSpec spec, UnnestFilterSplit filterSplit)
+ {
+ return transformCursorBuildSpec(spec, unnestColumn, filterSplit.getBaseTableFilter());
+ }
+
/**
* Split the spec's filters into base-table and post-unnest filters (see
* {@link #computeBaseAndPostUnnestFilters}). Cheap and metadata-only; shared by the sync and async holder paths.
diff --git a/processing/src/main/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactory.java b/processing/src/main/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactory.java
index fe06846f86b4..7a286917a7d4 100644
--- a/processing/src/main/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactory.java
+++ b/processing/src/main/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactory.java
@@ -32,6 +32,7 @@
import org.apache.druid.segment.CursorBuildSpec;
import org.apache.druid.segment.CursorFactory;
import org.apache.druid.segment.CursorHolder;
+import org.apache.druid.segment.CursorPrefetch;
import org.apache.druid.segment.Cursors;
import org.apache.druid.segment.VirtualColumn;
import org.apache.druid.segment.VirtualColumns;
@@ -77,17 +78,14 @@ public HashJoinSegmentCursorFactory(
@Override
public CursorHolder makeCursorHolder(CursorBuildSpec spec)
{
- final Filter combinedFilter = baseFilterAnd(spec.getFilter());
- final Set physicalColumns = computeBasePhysicalColumns(spec, combinedFilter);
-
+ final JoinCursorPlan plan = planCursor(spec);
if (clauses.isEmpty()) {
// if there are no clauses, we can just use the base cursor directly if we apply the combined filter
- return baseCursorFactory.makeCursorHolder(noClausesBaseSpec(spec, combinedFilter, physicalColumns));
+ return baseCursorFactory.makeCursorHolder(plan.baseBuildSpec);
}
// else we need to wipe out the grouping, aggregations, and ordering
final Closer joinablesCloser = Closer.create();
- final JoinCursorPlan plan = planJoinCursor(spec, combinedFilter, physicalColumns);
final CursorHolder baseCursorHolder = joinablesCloser.register(
baseCursorFactory.makeCursorHolder(plan.baseBuildSpec)
);
@@ -97,16 +95,13 @@ public CursorHolder makeCursorHolder(CursorBuildSpec spec)
@Override
public AsyncCursorHolder makeCursorHolderAsync(CursorBuildSpec spec)
{
- final Filter combinedFilter = baseFilterAnd(spec.getFilter());
- final Set physicalColumns = computeBasePhysicalColumns(spec, combinedFilter);
-
+ // Join filter analysis + base-spec computation are CPU-only; do them synchronously to learn the base spec.
+ final JoinCursorPlan plan = planCursor(spec);
if (clauses.isEmpty()) {
- return baseCursorFactory.makeCursorHolderAsync(noClausesBaseSpec(spec, combinedFilter, physicalColumns));
+ return baseCursorFactory.makeCursorHolderAsync(plan.baseBuildSpec);
}
final Closer joinablesCloser = Closer.create();
- // Join filter analysis + base-spec computation are CPU-only; do them synchronously to learn the base spec.
- final JoinCursorPlan plan = planJoinCursor(spec, combinedFilter, physicalColumns);
// Build the left/base holder asynchronously (a partial base segment downloads its required columns here); the
// join's build-side joinables are already-resident in-memory tables, so the base is the only async piece. Once it's
@@ -116,6 +111,35 @@ public AsyncCursorHolder makeCursorHolderAsync(CursorBuildSpec spec)
.transform(baseHolder -> joinCursorHolder(plan, joinablesCloser, joinablesCloser.register(baseHolder)));
}
+ @Override
+ public CursorPrefetch prefetch(CursorBuildSpec spec)
+ {
+ // The left/base side is the only part that loads on demand (the build-side joinables are resident in-memory
+ // tables), so warm it up with exactly the base spec the async build computes. Nothing of the join itself is
+ // created here: no joinables closer, no per-cursor matchers.
+ return baseCursorFactory.prefetch(delegateSpec(spec));
+ }
+
+ private CursorBuildSpec delegateSpec(CursorBuildSpec spec)
+ {
+ return planCursor(spec).baseBuildSpec;
+ }
+
+ /**
+ * Plans a cursor over this factory for {@code spec}, shared by every holder path: with no clauses, just the base
+ * spec (the original spec with the combined filter and base physical columns); otherwise the join filter
+ * pre-analysis and split too (see {@link #planJoinCursor}).
+ */
+ private JoinCursorPlan planCursor(CursorBuildSpec spec)
+ {
+ final Filter combinedFilter = baseFilterAnd(spec.getFilter());
+ final Set physicalColumns = computeBasePhysicalColumns(spec, combinedFilter);
+ if (clauses.isEmpty()) {
+ return new JoinCursorPlan(null, null, noClausesBaseSpec(spec, combinedFilter, physicalColumns));
+ }
+ return planJoinCursor(spec, combinedFilter, physicalColumns);
+ }
+
/**
* Physical columns to pass to the base cursor: a copy of the spec's physical columns plus any columns required by
* the combined filter (null when the spec didn't declare physical columns, meaning "all"). Shared by the no-clauses
@@ -377,8 +401,9 @@ private List computeOrdering(final List baseOrdering, final Vi
}
/**
- * Outputs of {@link #planJoinCursor}: the (possibly re-computed) join filter pre-analysis and split needed when the
- * join cursor is actually constructed, plus the base-table cursor build spec used to open the left-side holder.
+ * Outputs of {@link #planCursor}: the (possibly re-computed) join filter pre-analysis and split needed when the
+ * join cursor is actually constructed, plus the base-table cursor build spec used to open the left-side holder. The
+ * analysis and split are null when there are no clauses, since no join cursor is constructed then.
*/
private static final class JoinCursorPlan
{
@@ -386,12 +411,14 @@ private static final class JoinCursorPlan
* Typically the same as {@link HashJoinSegmentCursorFactory#joinFilterPreAnalysis}, but may differ when an unnest
* datasource is layered on top of a join datasource.
*/
+ @Nullable
private final JoinFilterPreAnalysis actualPreAnalysis;
/**
* Result of {@link JoinFilterAnalyzer#splitFilter} on {@link #actualPreAnalysis} and
* {@link HashJoinSegmentCursorFactory#baseFilter}.
*/
+ @Nullable
private final JoinFilterSplit joinFilterSplit;
/**
@@ -400,8 +427,8 @@ private static final class JoinCursorPlan
private final CursorBuildSpec baseBuildSpec;
private JoinCursorPlan(
- JoinFilterPreAnalysis actualPreAnalysis,
- JoinFilterSplit joinFilterSplit,
+ @Nullable JoinFilterPreAnalysis actualPreAnalysis,
+ @Nullable JoinFilterSplit joinFilterSplit,
CursorBuildSpec baseBuildSpec
)
{
diff --git a/processing/src/test/java/org/apache/druid/segment/CursorPrefetchTest.java b/processing/src/test/java/org/apache/druid/segment/CursorPrefetchTest.java
new file mode 100644
index 000000000000..8220fd104be7
--- /dev/null
+++ b/processing/src/test/java/org/apache/druid/segment/CursorPrefetchTest.java
@@ -0,0 +1,130 @@
+/*
+ * 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.druid.segment;
+
+import org.apache.druid.common.asyncresource.AsyncResourceCanceledException;
+import org.apache.druid.segment.column.ColumnCapabilities;
+import org.apache.druid.segment.column.RowSignature;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import javax.annotation.Nullable;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+class CursorPrefetchTest
+{
+ @Test
+ void testNoneIsReadyWithNoStats()
+ {
+ try (CursorPrefetch prefetch = CursorPrefetch.none()) {
+ Assertions.assertTrue(prefetch.isReady());
+ Assertions.assertEquals(CursorPrefetch.Stats.NONE, prefetch.get());
+ }
+ }
+
+ @Test
+ void testCloseBeforeReadyRunsCancelerAndReportsCancellation()
+ {
+ final AtomicBoolean canceled = new AtomicBoolean(false);
+ final AtomicBoolean fired = new AtomicBoolean(false);
+ final CursorPrefetch prefetch = new CursorPrefetch(() -> canceled.set(true));
+ prefetch.addReadyCallback(() -> fired.set(true));
+ Assertions.assertFalse(prefetch.isReady());
+
+ prefetch.close();
+ Assertions.assertTrue(canceled.get(), "closing before ready must run the canceler");
+ Assertions.assertTrue(fired.get(), "closing before ready must wake waiters");
+ Assertions.assertTrue(prefetch.isReady(), "a canceled prefetch is over");
+ Assertions.assertThrows(AsyncResourceCanceledException.class, prefetch::get);
+
+ // the canceler is not consulted again by a late completion, which is dropped
+ Assertions.assertFalse(prefetch.set(CursorPrefetch.Stats.NONE, null));
+ }
+
+ @Test
+ void testCloseAfterReadyReleasesPins()
+ {
+ final AtomicInteger pinReleases = new AtomicInteger();
+ final AtomicBoolean canceled = new AtomicBoolean(false);
+ final CursorPrefetch prefetch = new CursorPrefetch(() -> canceled.set(true));
+ final CursorPrefetch.Stats stats = new CursorPrefetch.Stats(List.of("__base"), 1, 10L);
+ Assertions.assertTrue(prefetch.set(stats, pinReleases::incrementAndGet));
+ Assertions.assertTrue(prefetch.isReady());
+ Assertions.assertEquals(stats, prefetch.get());
+ Assertions.assertEquals(0, pinReleases.get(), "pins stay held while the handle is open");
+
+ prefetch.close();
+ Assertions.assertEquals(1, pinReleases.get(), "closing a ready handle releases its pins");
+ Assertions.assertFalse(canceled.get(), "nothing to cancel once ready");
+ }
+
+ @Test
+ void testFailureSurfacesFromGet()
+ {
+ final CursorPrefetch prefetch = new CursorPrefetch(null);
+ prefetch.setException(new IllegalStateException("deep storage went away"));
+ Assertions.assertTrue(prefetch.isReady());
+ final IllegalStateException e = Assertions.assertThrows(IllegalStateException.class, prefetch::get);
+ Assertions.assertEquals("deep storage went away", e.getMessage());
+ prefetch.close();
+ }
+
+ @Test
+ void testFailedIsReadyAndThrowsFromGet()
+ {
+ final CursorPrefetch prefetch = CursorPrefetch.failed(new IllegalStateException("no room"));
+ Assertions.assertTrue(prefetch.isReady());
+ final IllegalStateException e = Assertions.assertThrows(IllegalStateException.class, prefetch::get);
+ Assertions.assertEquals("no room", e.getMessage());
+ prefetch.close();
+ }
+
+ @Test
+ void testCursorFactoryDefaultIsReadyNoOp()
+ {
+ final CursorFactory resident = new CursorFactory()
+ {
+ @Override
+ public CursorHolder makeCursorHolder(CursorBuildSpec spec)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public RowSignature getRowSignature()
+ {
+ return RowSignature.empty();
+ }
+
+ @Nullable
+ @Override
+ public ColumnCapabilities getColumnCapabilities(String column)
+ {
+ return null;
+ }
+ };
+ try (CursorPrefetch prefetch = resident.prefetch(CursorBuildSpec.FULL_SCAN)) {
+ Assertions.assertTrue(prefetch.isReady());
+ Assertions.assertEquals(CursorPrefetch.Stats.NONE, prefetch.get());
+ }
+ }
+}
diff --git a/processing/src/test/java/org/apache/druid/segment/DeferredCursorFactory.java b/processing/src/test/java/org/apache/druid/segment/DeferredCursorFactory.java
index e9e9305e6f3d..cb94cedc20b0 100644
--- a/processing/src/test/java/org/apache/druid/segment/DeferredCursorFactory.java
+++ b/processing/src/test/java/org/apache/druid/segment/DeferredCursorFactory.java
@@ -35,8 +35,11 @@ public class DeferredCursorFactory implements CursorFactory
{
private final CursorFactory delegate;
public final AtomicBoolean canceled = new AtomicBoolean(false);
+ public final AtomicBoolean prefetchCanceled = new AtomicBoolean(false);
private AsyncCursorHolder pending;
private CursorBuildSpec pendingSpec;
+ private CursorPrefetch pendingPrefetch;
+ private CursorBuildSpec prefetchSpec;
public DeferredCursorFactory(CursorFactory delegate)
{
@@ -57,6 +60,18 @@ public AsyncCursorHolder makeCursorHolderAsync(CursorBuildSpec spec)
return pending;
}
+ /**
+ * Hands back an unfinished {@link CursorPrefetch}, recording the spec, so a test can assert a wrapping factory
+ * delegates the prefetch with the same spec as its async holder build; {@link #completePrefetch()} finishes it.
+ */
+ @Override
+ public CursorPrefetch prefetch(CursorBuildSpec spec)
+ {
+ prefetchSpec = spec;
+ pendingPrefetch = new CursorPrefetch(() -> prefetchCanceled.set(true));
+ return pendingPrefetch;
+ }
+
/**
* Completes the most recent {@link #makeCursorHolderAsync} holder by building the delegate's holder for the spec it
* was called with.
@@ -66,6 +81,30 @@ public void complete()
pending.set(delegate.makeCursorHolder(pendingSpec));
}
+ /**
+ * Completes the most recent {@link #prefetch} handle.
+ */
+ public void completePrefetch()
+ {
+ pendingPrefetch.set(CursorPrefetch.Stats.NONE, null);
+ }
+
+ /**
+ * The spec of the most recent {@link #makeCursorHolderAsync} call.
+ */
+ public CursorBuildSpec getPendingSpec()
+ {
+ return pendingSpec;
+ }
+
+ /**
+ * The spec of the most recent {@link #prefetch} call.
+ */
+ public CursorBuildSpec getPrefetchSpec()
+ {
+ return prefetchSpec;
+ }
+
@Override
public RowSignature getRowSignature()
{
diff --git a/processing/src/test/java/org/apache/druid/segment/FilteredCursorFactoryTest.java b/processing/src/test/java/org/apache/druid/segment/FilteredCursorFactoryTest.java
index 118c1b088e22..1f443ababe15 100644
--- a/processing/src/test/java/org/apache/druid/segment/FilteredCursorFactoryTest.java
+++ b/processing/src/test/java/org/apache/druid/segment/FilteredCursorFactoryTest.java
@@ -42,15 +42,49 @@
public class FilteredCursorFactoryTest extends InitializedNullHandlingTest
{
private static final Closer CLOSER = Closer.create();
+ private static CursorFactory base;
private static FilteredCursorFactory filtered;
@BeforeAll
public static void setUpClass(@TempDir final File tempDir)
{
- filtered = new FilteredCursorFactory(
- new QueryableIndexCursorFactory(CLOSER.register(SmallSegmentTestHelper.makeIndex(tempDir))),
- new EqualityFilter("dim", ColumnType.STRING, "b", null)
- );
+ base = new QueryableIndexCursorFactory(CLOSER.register(SmallSegmentTestHelper.makeIndex(tempDir)));
+ filtered = new FilteredCursorFactory(base, new EqualityFilter("dim", ColumnType.STRING, "b", null));
+ }
+
+ @Test
+ public void test_prefetch_delegatesSameSpecAsAsyncBuild()
+ {
+ final DeferredCursorFactory deferred = new DeferredCursorFactory(base);
+ final FilteredCursorFactory factory =
+ new FilteredCursorFactory(deferred, new EqualityFilter("dim", ColumnType.STRING, "b", null));
+ final CursorBuildSpec spec = spec("v");
+
+ factory.makeCursorHolderAsync(spec).close();
+ final CursorPrefetch prefetch = factory.prefetch(spec);
+ try {
+ Assertions.assertEquals(deferred.getPendingSpec(), deferred.getPrefetchSpec());
+ Assertions.assertNotEquals(spec, deferred.getPrefetchSpec(), "the filter is folded into the delegate's spec");
+ Assertions.assertFalse(prefetch.isReady());
+ deferred.completePrefetch();
+ Assertions.assertTrue(prefetch.isReady());
+ }
+ finally {
+ prefetch.close();
+ }
+ }
+
+ @Test
+ public void test_prefetch_withoutFilterPassesSpecThrough()
+ {
+ final DeferredCursorFactory deferred = new DeferredCursorFactory(base);
+ final FilteredCursorFactory factory = new FilteredCursorFactory(deferred, null);
+ final CursorBuildSpec spec = spec("v");
+
+ final CursorPrefetch prefetch = factory.prefetch(spec);
+ Assertions.assertSame(spec, deferred.getPrefetchSpec());
+ prefetch.close();
+ Assertions.assertTrue(deferred.prefetchCanceled.get(), "closing before ready cancels the delegate's prefetch");
}
@AfterAll
diff --git a/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexCursorFactoryClusteredTest.java b/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexCursorFactoryClusteredTest.java
index 87a71f9c9ebc..1aefe25fb85e 100644
--- a/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexCursorFactoryClusteredTest.java
+++ b/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexCursorFactoryClusteredTest.java
@@ -202,6 +202,40 @@ void testFilterOnClusteringColumnDownloadsOnlySurvivingGroup() throws IOExceptio
}
}
+ @Test
+ void testPrefetchAcquiresAndDownloadsOnlySurvivingGroups() throws IOException
+ {
+ final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir);
+ final CountingBundleAcquirer acquirer = new CountingBundleAcquirer(directExec());
+ try (IndexAndMapper opened = openIndex(rangeReader, "prefetch_acme")) {
+ final PartialQueryableIndexCursorFactory factory = new PartialQueryableIndexCursorFactory(
+ opened.index(),
+ QueryableIndexTimeBoundaryInspector.create(opened.index()),
+ acquirer
+ );
+ final CursorBuildSpec spec = CursorBuildSpec.builder()
+ .setFilter(new EqualityFilter("tenant", ColumnType.STRING, "acme", null))
+ .build();
+
+ final CursorPrefetch prefetch = factory.prefetch(spec);
+ Assertions.assertTrue(prefetch.isReady());
+ Assertions.assertEquals(List.of(ACME_BUNDLE), prefetch.get().bundles());
+ Assertions.assertEquals(1, acquirer.acquiredCount(ACME_BUNDLE), "only the surviving group is held");
+ Assertions.assertEquals(0, acquirer.acquiredCount(GLOBEX_BUNDLE), "the pruned group is never touched");
+
+ final Set downloaded = opened.mapper().getDownloadedFiles();
+ Assertions.assertTrue(downloaded.contains(ACME_BUNDLE + "/region"), "got: " + downloaded);
+ Assertions.assertTrue(
+ downloaded.stream().noneMatch(f -> f.startsWith(GLOBEX_BUNDLE + "/")),
+ "globex group must not be downloaded; got: " + downloaded
+ );
+
+ Assertions.assertEquals(0, acquirer.releasedCount(ACME_BUNDLE));
+ prefetch.close();
+ Assertions.assertEquals(1, acquirer.releasedCount(ACME_BUNDLE), "closing the handle releases the group hold");
+ }
+ }
+
@Test
void testFilterMatchingNoGroupDownloadsNothing() throws IOException
{
diff --git a/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexCursorFactoryTest.java b/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexCursorFactoryTest.java
index 8e443c2b74ea..a6be37085190 100644
--- a/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexCursorFactoryTest.java
+++ b/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexCursorFactoryTest.java
@@ -25,6 +25,7 @@
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import org.apache.druid.common.asyncresource.AsyncResource;
+import org.apache.druid.common.asyncresource.AsyncResourceCanceledException;
import org.apache.druid.common.asyncresource.AsyncResources;
import org.apache.druid.data.input.InputRow;
import org.apache.druid.data.input.ListBasedInputRow;
@@ -76,6 +77,7 @@
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
+import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -909,6 +911,558 @@ public AsyncResource submitDownload(Callable task)
}
}
+ @Test
+ void testRunFailureCancelsSiblingRunsAndReleasesHoldsOnce() throws IOException
+ {
+ // The async build shares the prefetch's failure path (see
+ // testPrefetchHandleRunFailureCancelsSiblingRunsAndReleasesHoldsOnce): one failed run cancels the rest and releases
+ // every hold, and closing the failed holder afterwards releases nothing more.
+ final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir);
+ try (IndexAndMapper opened = openIndex(rangeReader, "build_sibling_cancel")) {
+ final PartialQueryableIndex index = opened.index();
+ final List> submitted = new ArrayList<>();
+ final AtomicInteger holdReleases = new AtomicInteger(0);
+ final PartialQueryableIndexCursorFactory factory = new PartialQueryableIndexCursorFactory(
+ index,
+ QueryableIndexTimeBoundaryInspector.create(index),
+ recordingAcquirer(submitted, holdReleases)
+ );
+
+ final AsyncCursorHolder asyncHolder = factory.makeCursorHolderAsync(projectionAggSpec());
+ Assertions.assertTrue(submitted.size() >= 2, "the projection and its parent bundle each submit a run");
+ Assertions.assertFalse(asyncHolder.isReady());
+
+ submitted.get(0).setException(new IOException("deep storage went away"));
+ Assertions.assertTrue(asyncHolder.isReady(), "a failed run download completes the holder");
+ Assertions.assertThrows(RuntimeException.class, asyncHolder::release);
+ for (SettableFuture> sibling : submitted.subList(1, submitted.size())) {
+ Assertions.assertTrue(sibling.isCancelled(), "sibling run downloads must be cancelled by the failure");
+ }
+ Assertions.assertEquals(2, holdReleases.get(), "both bundle holds are released once the runs are unwound");
+
+ asyncHolder.close();
+ Assertions.assertEquals(2, holdReleases.get(), "closing the failed holder releases nothing twice");
+ }
+ }
+
+ @Test
+ void testSubmitRejectionAfterPartialSubmissionCancelsSubmittedRunsAndThrows() throws IOException
+ {
+ // The async build's setup fails the same way as the prefetch's (see
+ // testPrefetchHandleSubmitRejectionAfterPartialSubmissionCancelsSubmittedRuns), except that it throws, there being
+ // no handle to report through yet: nothing it submitted or held may outlive the throw.
+ final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir);
+ try (IndexAndMapper opened = openIndex(rangeReader, "build_submit_rejected")) {
+ final PartialQueryableIndex index = opened.index();
+ final List> submitted = new ArrayList<>();
+ final AtomicInteger holdReleases = new AtomicInteger();
+ final PartialQueryableIndexCursorFactory factory = new PartialQueryableIndexCursorFactory(
+ index,
+ QueryableIndexTimeBoundaryInspector.create(index),
+ rejectingAfterFirstBundleAcquirer(submitted, holdReleases)
+ );
+
+ Assertions.assertThrows(
+ RejectedExecutionException.class,
+ () -> factory.makeCursorHolderAsync(projectionAggSpec())
+ );
+ Assertions.assertFalse(submitted.isEmpty(), "the projection bundle's runs were submitted before the rejection");
+ submitted.forEach(f -> Assertions.assertTrue(f.isCancelled(), "submitted runs are cancelled"));
+ Assertions.assertEquals(2, holdReleases.get(), "both holds taken before the rejection are released");
+ }
+ }
+
+ @Test
+ void testPrefetchHandleDownloadsExactlyRequiredFiles() throws IOException
+ {
+ final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir);
+ try (IndexAndMapper opened = openIndex(rangeReader, "prefetch_files")) {
+ final PartialQueryableIndex index = opened.index();
+ final PartialSegmentFileMapperV10 mapper = opened.mapper();
+ final PartialQueryableIndexCursorFactory factory = new PartialQueryableIndexCursorFactory(
+ index,
+ QueryableIndexTimeBoundaryInspector.create(index),
+ noOpAcquirer(directExec())
+ );
+ rangeReader.resetCount();
+
+ final CursorBuildSpec spec = CursorBuildSpec.builder().setPhysicalColumns(Set.of("dim1")).build();
+ try (CursorPrefetch prefetch = factory.prefetch(spec)) {
+ Assertions.assertTrue(prefetch.isReady(), "the direct executor completes the prefetch inline");
+ final CursorPrefetch.Stats stats = prefetch.get();
+ Assertions.assertEquals(List.of(Projections.BASE_TABLE_PROJECTION_NAME), stats.bundles());
+ Assertions.assertEquals(rangeReader.getReadCount(), stats.plannedRuns(), "one deep-storage read per run");
+ Assertions.assertTrue(stats.plannedBytes() > 0);
+
+ final String basePrefix = Projections.BASE_TABLE_PROJECTION_NAME + "/";
+ final Set downloaded = mapper.getDownloadedFiles();
+ Assertions.assertTrue(
+ downloaded.contains(basePrefix + ColumnHolder.TIME_COLUMN_NAME),
+ "expected base __time; got: " + downloaded
+ );
+ Assertions.assertTrue(downloaded.contains(basePrefix + "dim1"), "expected base dim1; got: " + downloaded);
+ Assertions.assertFalse(
+ downloaded.contains(basePrefix + "metric1"),
+ "expected base metric1 NOT to be downloaded; got: " + downloaded
+ );
+ }
+ }
+ }
+
+ @Test
+ void testPrefetchHandleThenCursorBuildDownloadsNothingAndReusesHolders() throws IOException
+ {
+ // A cursor build for the same spec, made while the prefetch handle is still open, has nothing left to download
+ // (so it submits only its holder-producing continuation) and finds the column holders the prefetch materialized.
+ final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir);
+ try (IndexAndMapper opened = openIndex(rangeReader, "prefetch_then_build")) {
+ final PartialQueryableIndex index = opened.index();
+ final ListeningExecutorService exec = directExec();
+ final AtomicInteger submits = new AtomicInteger();
+ final PartialBundleAcquirer acquirer = new PartialBundleAcquirer()
+ {
+ @Override
+ public Closeable acquire(String bundleName)
+ {
+ return () -> {};
+ }
+
+ @Override
+ public AsyncResource submitDownload(Callable task)
+ {
+ submits.incrementAndGet();
+ return AsyncResources.fromFutureUnmanaged(exec.submit(task));
+ }
+ };
+ final PartialQueryableIndexCursorFactory factory = new PartialQueryableIndexCursorFactory(
+ index,
+ QueryableIndexTimeBoundaryInspector.create(index),
+ acquirer
+ );
+ final CursorBuildSpec spec = CursorBuildSpec.builder().setPhysicalColumns(Set.of("dim1")).build();
+
+ try (CursorPrefetch prefetch = factory.prefetch(spec)) {
+ Assertions.assertTrue(prefetch.isReady());
+ final int prefetchSubmits = submits.get();
+ Assertions.assertTrue(prefetchSubmits >= 2, "at least one run download plus the materialization continuation");
+ final ColumnHolder warm = index.getColumnHolder("dim1");
+ rangeReader.resetCount();
+
+ try (AsyncCursorHolder asyncHolder = factory.makeCursorHolderAsync(spec);
+ CursorHolder holder = asyncHolder.release()) {
+ Assertions.assertEquals(0, rangeReader.getReadCount(), "nothing left to download after the prefetch");
+ Assertions.assertEquals(
+ prefetchSubmits + 1,
+ submits.get(),
+ "the cursor build submits only its holder-producing continuation"
+ );
+ Assertions.assertSame(warm, index.getColumnHolder("dim1"), "the memoized holder is reused");
+
+ final Cursor cursor = holder.asCursor();
+ final ColumnValueSelector> dim1 = cursor.getColumnSelectorFactory().makeColumnValueSelector("dim1");
+ final List