From c7913041e5de0d7f9ea4b4ed19eaa127d75cfda1 Mon Sep 17 00:00:00 2001 From: Clint Wylie Date: Fri, 13 Nov 2026 00:48:24 -0800 Subject: [PATCH 1/3] feat: add async cursor prefetch mechanism --- .../apache/druid/segment/CursorFactory.java | 10 + .../apache/druid/segment/CursorPrefetch.java | 76 ++++ .../druid/segment/FilteredCursorFactory.java | 23 +- .../PartialQueryableIndexCursorFactory.java | 279 ++++++++----- .../druid/segment/ProjectCursorFactory.java | 6 + .../segment/RestrictedCursorFactory.java | 19 +- .../druid/segment/UnnestCursorFactory.java | 29 +- .../join/HashJoinSegmentCursorFactory.java | 60 ++- .../druid/segment/CursorPrefetchTest.java | 120 ++++++ .../druid/segment/DeferredCursorFactory.java | 39 ++ .../segment/FilteredCursorFactoryTest.java | 42 +- ...ryableIndexCursorFactoryClusteredTest.java | 34 ++ ...artialQueryableIndexCursorFactoryTest.java | 378 ++++++++++++++++++ ...tialQueryableIndexServableBundlesTest.java | 21 + .../segment/ProjectCursorFactoryTest.java | 31 ++ .../segment/RestrictedCursorFactoryTest.java | 102 +++++ .../segment/UnnestCursorFactoryTest.java | 44 ++ .../HashJoinSegmentCursorFactoryTest.java | 66 +++ 18 files changed, 1251 insertions(+), 128 deletions(-) create mode 100644 processing/src/main/java/org/apache/druid/segment/CursorPrefetch.java create mode 100644 processing/src/test/java/org/apache/druid/segment/CursorPrefetchTest.java create mode 100644 processing/src/test/java/org/apache/druid/segment/RestrictedCursorFactoryTest.java 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..5ae1a8687205 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,16 @@ 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. + */ + 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..25f3c62b5eb6 --- /dev/null +++ b/processing/src/main/java/org/apache/druid/segment/CursorPrefetch.java @@ -0,0 +1,76 @@ +/* + * 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

+ * + */ +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; + } +} 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..57e1357fbcc4 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,188 @@ 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 = acquireHoldsAndSubmitRuns(plan.bundles()); + 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()); 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(). + // Failure while acquiring holds or submitting downloads (e.g. a bundle reservation finding no room, or a + // 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)); } } /** - * 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 + ) + { + // 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.holdReleases(), 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.holdReleases(), 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 CursorHolder holder; + 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.holdReleases(), + target, + DruidException.defensive("Async resource was closed before it could be produced") ); return; } } catch (Throwable t) { - failHolder(holdReleases, asyncHolder, t); + fail(pending.holdReleases(), 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 + * Shared failure path: request every bundle hold's release and fail the target. 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. + * download is still mid-{@code mapFile()}. */ - private static void failHolder(List holdReleases, AsyncCursorHolder asyncHolder, Throwable t) + private static void fail(List holdReleases, SettableAsyncResource target, Throwable t) { holdReleases.forEach(BundleHoldRelease::requestRelease); - asyncHolder.setException(t); + target.setException(t); } @Override @@ -396,31 +460,58 @@ 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 record PendingDownloads( + List holdReleases, + AsyncResource> downloaded, + CursorPrefetch.Stats stats + ) + { + /** + * Canceler for the resource being produced, run if its consumer closes it before it's ready (e.g. query + * cancel/timeout). Closes 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 requests the hold release on every bundle through the handshake. + * 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 () -> { + 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..c3bcbae1b359 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,28 @@ 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)); + } + + /** + * The spec passed to the delegate: the caller's spec with {@link #policy} applied. Used by every delegating method + * here. + */ + private CursorBuildSpec delegateSpec(CursorBuildSpec spec) + { + return policy.visit(spec); } @Override 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..94344cf350c1 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,31 @@ 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)); + } + + /** + * The spec passed to the base cursor factory for {@code spec}, computing the filter split itself. + */ + private CursorBuildSpec delegateSpec(CursorBuildSpec spec) + { + return delegateSpec(spec, computeFilterSplit(spec)); + } + + /** + * The spec passed to the base cursor factory: the caller's spec rewritten for the unnest input column, with only + * the base-table half of its filters (see {@link #computeFilterSplit}). Shared by every holder path, which also need + * {@code filterSplit} for the post-unnest half. + */ + 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..b7cce6ed30ab 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,38 @@ 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)); + } + + /** + * The spec passed to the base cursor factory for {@code spec}; see {@link #planCursor}. + */ + 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 +404,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 +414,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 +430,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..3b812afcf205 --- /dev/null +++ b/processing/src/test/java/org/apache/druid/segment/CursorPrefetchTest.java @@ -0,0 +1,120 @@ +/* + * 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 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..561d01a891f3 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; @@ -909,6 +910,383 @@ public AsyncResource submitDownload(Callable task) } } + @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 values = new ArrayList<>(); + while (!cursor.isDone()) { + values.add(dim1.getObject()); + cursor.advance(); + } + Assertions.assertEquals(List.of("a", "a", "b", "b"), values); + } + } + } + } + + @Test + void testPrefetchHandleHoldsBundleUntilClosed() throws IOException + { + final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir); + try (IndexAndMapper opened = openIndex(rangeReader, "prefetch_hold")) { + final PartialQueryableIndex index = opened.index(); + final ListeningExecutorService exec = directExec(); + final AtomicInteger holdReleases = new AtomicInteger(); + final PartialBundleAcquirer acquirer = new PartialBundleAcquirer() + { + @Override + public Closeable acquire(String bundleName) + { + return holdReleases::incrementAndGet; + } + + @Override + public AsyncResource submitDownload(Callable task) + { + return AsyncResources.fromFutureUnmanaged(exec.submit(task)); + } + }; + final PartialQueryableIndexCursorFactory factory = new PartialQueryableIndexCursorFactory( + index, + QueryableIndexTimeBoundaryInspector.create(index), + acquirer + ); + + final CursorPrefetch prefetch = factory.prefetch(CursorBuildSpec.FULL_SCAN); + Assertions.assertTrue(prefetch.isReady()); + Assertions.assertEquals(0, holdReleases.get(), "the handle owns the bundle hold while it is open"); + prefetch.close(); + Assertions.assertEquals(1, holdReleases.get(), "closing the handle releases the bundle hold exactly once"); + } + } + + @Test + void testPrefetchHandleMatchedProjectionHoldsParentBundle() throws IOException + { + // Same plan as the async build: the matched projection's bundle plus the __base bundle for the parent columns its + // required columns read through; both are held by the handle and released together when it closes. + final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir); + try (IndexAndMapper opened = openIndex(rangeReader, "prefetch_projection")) { + final PartialQueryableIndex index = opened.index(); + final PartialSegmentFileMapperV10 mapper = opened.mapper(); + final ListeningExecutorService exec = directExec(); + final Set acquired = new TreeSet<>(); + final AtomicInteger holdReleases = new AtomicInteger(); + final PartialBundleAcquirer acquirer = new PartialBundleAcquirer() + { + @Override + public Closeable acquire(String bundleName) + { + acquired.add(bundleName); + return holdReleases::incrementAndGet; + } + + @Override + public AsyncResource submitDownload(Callable task) + { + return AsyncResources.fromFutureUnmanaged(exec.submit(task)); + } + }; + final PartialQueryableIndexCursorFactory factory = new PartialQueryableIndexCursorFactory( + index, + QueryableIndexTimeBoundaryInspector.create(index), + acquirer + ); + final CursorBuildSpec aggSpec = CursorBuildSpec.builder() + .setGroupingColumns(List.of("dim1")) + .setAggregators(List.of( + new LongSumAggregatorFactory("_metric1_sum", "metric1") + )) + .setPhysicalColumns(Set.of("dim1", "metric1")) + .build(); + + final CursorPrefetch prefetch = factory.prefetch(aggSpec); + Assertions.assertTrue(prefetch.isReady()); + Assertions.assertEquals(new TreeSet<>(Set.of(PROJECTION_NAME, Projections.BASE_TABLE_PROJECTION_NAME)), acquired); + Assertions.assertEquals(List.of(PROJECTION_NAME, Projections.BASE_TABLE_PROJECTION_NAME), prefetch.get().bundles()); + + final String projPrefix = PROJECTION_NAME + "/"; + final String basePrefix = Projections.BASE_TABLE_PROJECTION_NAME + "/"; + final Set downloaded = mapper.getDownloadedFiles(); + Assertions.assertTrue(downloaded.contains(projPrefix + "dim1"), "expected projection dim1; got: " + downloaded); + Assertions.assertTrue( + downloaded.contains(projPrefix + "_metric1_sum"), + "expected projection _metric1_sum; got: " + downloaded + ); + Assertions.assertFalse( + downloaded.contains(projPrefix + "_count"), + "expected projection _count NOT to be downloaded; got: " + downloaded + ); + Assertions.assertFalse( + downloaded.contains(basePrefix + "metric1"), + "expected base metric1 NOT to be downloaded; got: " + downloaded + ); + + Assertions.assertEquals(0, holdReleases.get()); + prefetch.close(); + Assertions.assertEquals(2, holdReleases.get(), "both bundle holds release when the handle closes"); + } + } + + @Test + void testPrefetchHandleCloseBeforeReadyCancelsRunsAndReleasesHoldOnce() throws IOException + { + final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir); + try (IndexAndMapper opened = openIndex(rangeReader, "prefetch_cancel")) { + final PartialQueryableIndex index = opened.index(); + final List> submitted = new ArrayList<>(); + final AtomicInteger holdReleases = new AtomicInteger(0); + final PartialBundleAcquirer acquirer = new PartialBundleAcquirer() + { + @Override + public Closeable acquire(String bundleName) + { + return holdReleases::incrementAndGet; + } + + @Override + public AsyncResource submitDownload(Callable task) + { + final SettableFuture future = SettableFuture.create(); + submitted.add(future); + return AsyncResources.fromFutureUnmanaged(future); + } + }; + final PartialQueryableIndexCursorFactory factory = new PartialQueryableIndexCursorFactory( + index, + V10TimeBoundaryInspector.forBaseProjection(index.getBaseProjectionMetadata(), index.getDataInterval()), + acquirer + ); + + final CursorPrefetch prefetch = factory.prefetch(CursorBuildSpec.FULL_SCAN); + Assertions.assertFalse(prefetch.isReady(), "downloads never complete, so the prefetch must not be ready"); + Assertions.assertFalse(submitted.isEmpty(), "at least one run download should have been submitted"); + Assertions.assertEquals(0, holdReleases.get(), "hold must still be held while the prefetch is loading"); + + prefetch.close(); + + submitted.forEach(f -> Assertions.assertTrue(f.isCancelled(), "pending run downloads must be cancelled")); + Assertions.assertEquals(1, holdReleases.get(), "bundle hold must be released exactly once"); + Assertions.assertThrows(AsyncResourceCanceledException.class, prefetch::get); + } + } + + @Test + void testPrefetchHandleDownloadFailureReleasesHoldsAndGetThrows() throws IOException + { + final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir); + try (IndexAndMapper opened = openIndex(rangeReader, "prefetch_fail")) { + final PartialQueryableIndex index = opened.index(); + final List> submitted = new ArrayList<>(); + final AtomicInteger holdReleases = new AtomicInteger(0); + final PartialBundleAcquirer acquirer = new PartialBundleAcquirer() + { + @Override + public Closeable acquire(String bundleName) + { + return holdReleases::incrementAndGet; + } + + @Override + public AsyncResource submitDownload(Callable task) + { + final SettableFuture future = SettableFuture.create(); + submitted.add(future); + return AsyncResources.fromFutureUnmanaged(future); + } + }; + final PartialQueryableIndexCursorFactory factory = new PartialQueryableIndexCursorFactory( + index, + V10TimeBoundaryInspector.forBaseProjection(index.getBaseProjectionMetadata(), index.getDataInterval()), + acquirer + ); + + try (CursorPrefetch prefetch = factory.prefetch(CursorBuildSpec.FULL_SCAN)) { + Assertions.assertFalse(prefetch.isReady()); + submitted.get(0).setException(new IOException("deep storage went away")); + Assertions.assertTrue(prefetch.isReady(), "a failed run download completes the prefetch"); + Assertions.assertThrows(RuntimeException.class, prefetch::get); + Assertions.assertEquals(1, holdReleases.get(), "a failed prefetch releases its holds"); + } + Assertions.assertEquals(1, holdReleases.get(), "closing a failed prefetch releases nothing twice"); + } + } + + @Test + void testPrefetchHandleAlreadyResidentStillMaterializesOnDownloadExecutor() throws Exception + { + // Nothing to download, so the empty collect is ready inline; the materialization must still hop to the download + // executor rather than deserialize columns on the calling thread. + final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir); + final CountDownLatch gate = new CountDownLatch(1); + final ExecutorService rawExec = Execs.singleThreaded("partial-prefetch-resident-%d"); + final ListeningExecutorService gatedExec = MoreExecutors.listeningDecorator(rawExec); + try (IndexAndMapper opened = openIndex(rangeReader, "prefetch_resident")) { + opened.mapper().ensureAllDownloaded(); + final PartialQueryableIndex index = opened.index(); + final PartialQueryableIndexCursorFactory factory = new PartialQueryableIndexCursorFactory( + index, + QueryableIndexTimeBoundaryInspector.create(index), + noOpAcquirer(gatedExec) + ); + + @SuppressWarnings("unused") + ListenableFuture unused = gatedExec.submit(() -> { + try { + gate.await(); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + + try (CursorPrefetch prefetch = factory.prefetch(CursorBuildSpec.FULL_SCAN)) { + Assertions.assertFalse(prefetch.isReady(), "must not become ready inline even with nothing to download"); + + final CountDownLatch ready = new CountDownLatch(1); + final AtomicReference readyThread = new AtomicReference<>(); + prefetch.addReadyCallback(() -> { + readyThread.set(Thread.currentThread().getName()); + ready.countDown(); + }); + gate.countDown(); + Assertions.assertTrue(ready.await(5, TimeUnit.SECONDS), "ready callback must fire once the executor drains"); + Assertions.assertTrue( + readyThread.get().startsWith("partial-prefetch-resident"), + "columns must be materialized on the download executor, not thread[" + readyThread.get() + "]" + ); + Assertions.assertEquals(0, prefetch.get().plannedRuns(), "nothing was planned for download"); + } + } + finally { + gatedExec.shutdownNow(); + rawExec.shutdownNow(); + } + } + + @Test + void testPrefetchHandleEmptyPlanIsReadyNoOp() throws IOException + { + final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir); + try (IndexAndMapper opened = openIndex(rangeReader, "prefetch_empty")) { + final PartialQueryableIndex index = opened.index(); + final Set acquired = new TreeSet<>(); + final PartialBundleAcquirer acquirer = new PartialBundleAcquirer() + { + @Override + public Closeable acquire(String bundleName) + { + acquired.add(bundleName); + return () -> {}; + } + + @Override + public AsyncResource submitDownload(Callable task) + { + throw new AssertionError("nothing to download"); + } + }; + // nothing is servable, so the plan has no bundles + final PartialQueryableIndexCursorFactory factory = new PartialQueryableIndexCursorFactory( + index, + QueryableIndexTimeBoundaryInspector.create(index), + acquirer, + bundleName -> false + ); + + try (CursorPrefetch prefetch = factory.prefetch(CursorBuildSpec.FULL_SCAN)) { + Assertions.assertTrue(prefetch.isReady()); + Assertions.assertEquals(CursorPrefetch.Stats.NONE, prefetch.get()); + Assertions.assertTrue(acquired.isEmpty(), "no bundle is held for an empty plan"); + } + } + } + @Test void testPrefetchUsesCoalescedRangeReads() throws IOException { diff --git a/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexServableBundlesTest.java b/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexServableBundlesTest.java index e448569d905f..a78aa0e7af5a 100644 --- a/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexServableBundlesTest.java +++ b/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexServableBundlesTest.java @@ -405,6 +405,27 @@ void testNoProjectionsWithNothingServableSkipsUseProjection() throws IOException } } + @Test + void testPrefetchHonorsServableBundles() throws IOException + { + // prefetch plans over the same restricted view as the cursor build: the served projection plus the base parent of + // its required columns, never the unserved best match. + final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir); + try (IndexAndMapper opened = openIndex(rangeReader, "prefetch_servable")) { + final RecordingAcquirer acquirer = new RecordingAcquirer(directExec()); + final PartialQueryableIndexCursorFactory factory = factory(opened.index(), acquirer, BIG_PROJECTION::equals); + try (CursorPrefetch prefetch = factory.prefetch(COUNT_BY_DIM1)) { + Assertions.assertTrue(prefetch.isReady()); + Assertions.assertEquals(List.of(BIG_PROJECTION, BASE), prefetch.get().bundles()); + } + Assertions.assertEquals(new TreeSet<>(Set.of(BIG_PROJECTION, BASE)), acquirer.acquired); + Assertions.assertTrue( + opened.mapper().getDownloadedFiles().stream().noneMatch(f -> f.startsWith(SMALL_PROJECTION + "/")), + "the unserved projection must not be touched; got: " + opened.mapper().getDownloadedFiles() + ); + } + } + private static PartialQueryableIndexCursorFactory factory( PartialQueryableIndex index, PartialBundleAcquirer acquirer, diff --git a/processing/src/test/java/org/apache/druid/segment/ProjectCursorFactoryTest.java b/processing/src/test/java/org/apache/druid/segment/ProjectCursorFactoryTest.java index aff64bf95d0b..b67ad8aad502 100644 --- a/processing/src/test/java/org/apache/druid/segment/ProjectCursorFactoryTest.java +++ b/processing/src/test/java/org/apache/druid/segment/ProjectCursorFactoryTest.java @@ -142,6 +142,37 @@ public void test_rejectQueryVirtualColumnShadowingColumnWeRead() message, Assertions.assertThrows(DruidException.class, () -> factory.makeCursorHolderAsync(spec)).getMessage() ); + Assertions.assertEquals( + message, + Assertions.assertThrows(DruidException.class, () -> factory.prefetch(spec)).getMessage() + ); + } + + @Test + public void test_prefetch_delegatesSameSpecAsAsyncBuild() + { + final DeferredCursorFactory deferred = new DeferredCursorFactory(new QueryableIndexCursorFactory(index)); + final CursorFactory projected = new ProjectCursorFactory( + deferred, + VirtualColumns.create(expression("doubled", "num * 2")) + ); + final CursorBuildSpec spec = spec(expression("v0", "concat(out, '!')")); + + projected.makeCursorHolderAsync(spec).close(); + final CursorPrefetch prefetch = projected.prefetch(spec); + try { + Assertions.assertEquals(deferred.getPendingSpec(), deferred.getPrefetchSpec()); + Assertions.assertTrue( + deferred.getPrefetchSpec().getVirtualColumns().exists("doubled"), + "our virtual columns are folded into the delegate's spec" + ); + Assertions.assertFalse(prefetch.isReady()); + deferred.completePrefetch(); + Assertions.assertTrue(prefetch.isReady()); + } + finally { + prefetch.close(); + } } @Test diff --git a/processing/src/test/java/org/apache/druid/segment/RestrictedCursorFactoryTest.java b/processing/src/test/java/org/apache/druid/segment/RestrictedCursorFactoryTest.java new file mode 100644 index 000000000000..9034d5d1b19b --- /dev/null +++ b/processing/src/test/java/org/apache/druid/segment/RestrictedCursorFactoryTest.java @@ -0,0 +1,102 @@ +/* + * 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.java.util.common.io.Closer; +import org.apache.druid.query.filter.EqualityFilter; +import org.apache.druid.query.policy.NoRestrictionPolicy; +import org.apache.druid.query.policy.RowFilterPolicy; +import org.apache.druid.segment.column.ColumnType; +import org.apache.druid.testing.InitializedNullHandlingTest; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +public class RestrictedCursorFactoryTest extends InitializedNullHandlingTest +{ + private static final Closer CLOSER = Closer.create(); + private static CursorFactory base; + + @BeforeAll + public static void setUpClass(@TempDir final File tempDir) + { + base = new QueryableIndexCursorFactory(CLOSER.register(SmallSegmentTestHelper.makeIndex(tempDir))); + } + + @AfterAll + public static void tearDownClass() throws IOException + { + CLOSER.close(); + } + + @Test + public void test_rowFilterPolicy_filtersRows() + { + final RestrictedCursorFactory restricted = new RestrictedCursorFactory( + base, + RowFilterPolicy.from(new EqualityFilter("dim", ColumnType.STRING, "b", null)) + ); + Assertions.assertEquals( + List.of(List.of("b")), + SmallSegmentTestHelper.readRows(restricted, CursorBuildSpec.FULL_SCAN, "dim") + ); + } + + @Test + public void test_prefetch_delegatesSameSpecAsAsyncBuild() + { + final DeferredCursorFactory deferred = new DeferredCursorFactory(base); + final RestrictedCursorFactory restricted = new RestrictedCursorFactory( + deferred, + RowFilterPolicy.from(new EqualityFilter("dim", ColumnType.STRING, "b", null)) + ); + + restricted.makeCursorHolderAsync(CursorBuildSpec.FULL_SCAN).close(); + final CursorPrefetch prefetch = restricted.prefetch(CursorBuildSpec.FULL_SCAN); + try { + Assertions.assertEquals(deferred.getPendingSpec(), deferred.getPrefetchSpec()); + Assertions.assertNotNull(deferred.getPrefetchSpec().getFilter(), "the policy's row filter is applied"); + Assertions.assertFalse(prefetch.isReady()); + deferred.completePrefetch(); + Assertions.assertTrue(prefetch.isReady()); + } + finally { + prefetch.close(); + } + } + + @Test + public void test_prefetch_noRestrictionPassesSpecThrough() + { + final DeferredCursorFactory deferred = new DeferredCursorFactory(base); + final RestrictedCursorFactory restricted = new RestrictedCursorFactory(deferred, NoRestrictionPolicy.instance()); + + final CursorPrefetch prefetch = restricted.prefetch(CursorBuildSpec.FULL_SCAN); + Assertions.assertEquals(CursorBuildSpec.FULL_SCAN, deferred.getPrefetchSpec()); + prefetch.close(); + Assertions.assertTrue(deferred.prefetchCanceled.get(), "closing before ready cancels the delegate's prefetch"); + } +} diff --git a/processing/src/test/java/org/apache/druid/segment/UnnestCursorFactoryTest.java b/processing/src/test/java/org/apache/druid/segment/UnnestCursorFactoryTest.java index 2f6004dd441e..d8930688ea3c 100644 --- a/processing/src/test/java/org/apache/druid/segment/UnnestCursorFactoryTest.java +++ b/processing/src/test/java/org/apache/druid/segment/UnnestCursorFactoryTest.java @@ -316,6 +316,50 @@ public void test_unnest_factory_async_awaits_base_then_produces_unnest_cursor() } } + @Test + public void test_unnest_factory_prefetch_delegates_base_spec() + { + // prefetch must warm the base with exactly the spec the async build hands it (rewritten for the unnest input + // column), and the handle tracks the base's handle. + final DeferredCursorFactory base = new DeferredCursorFactory(INCREMENTAL_INDEX_CURSOR_FACTORY); + final UnnestCursorFactory unnest = new UnnestCursorFactory( + base, + new ExpressionVirtualColumn(OUTPUT_COLUMN_NAME, "\"" + INPUT_COLUMN_NAME + "\"", null, ExprMacroTable.nil()), + null + ); + final CursorBuildSpec spec = CursorBuildSpec.builder().setPhysicalColumns(Set.of(OUTPUT_COLUMN_NAME)).build(); + + unnest.makeCursorHolderAsync(spec).close(); + final CursorPrefetch prefetch = unnest.prefetch(spec); + try { + Assertions.assertEquals(base.getPendingSpec(), base.getPrefetchSpec(), "prefetch spec must match the build spec"); + Assertions.assertNotEquals(spec, base.getPrefetchSpec(), "the base sees the rewritten spec, not the caller's"); + Assertions.assertFalse(prefetch.isReady(), "prefetch waits for the base"); + base.completePrefetch(); + Assertions.assertTrue(prefetch.isReady()); + } + finally { + prefetch.close(); + } + Assertions.assertFalse(base.prefetchCanceled.get()); + } + + @Test + public void test_unnest_factory_prefetch_close_before_ready_cancels_base() + { + final DeferredCursorFactory base = new DeferredCursorFactory(INCREMENTAL_INDEX_CURSOR_FACTORY); + final UnnestCursorFactory unnest = new UnnestCursorFactory( + base, + new ExpressionVirtualColumn(OUTPUT_COLUMN_NAME, "\"" + INPUT_COLUMN_NAME + "\"", null, ExprMacroTable.nil()), + null + ); + + final CursorPrefetch prefetch = unnest.prefetch(CursorBuildSpec.FULL_SCAN); + Assertions.assertFalse(prefetch.isReady()); + prefetch.close(); + Assertions.assertTrue(base.prefetchCanceled.get(), "closing the prefetch before it's ready cancels the base"); + } + @Test public void test_unnest_factory_async_close_before_ready_cancels_base() { diff --git a/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactoryTest.java b/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactoryTest.java index 98dbd1613aae..6212627449dd 100644 --- a/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactoryTest.java +++ b/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactoryTest.java @@ -37,6 +37,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.DeferredCursorFactory; import org.apache.druid.segment.ReferenceCountedSegmentProvider; import org.apache.druid.segment.TopNOptimizationInspector; @@ -54,6 +55,7 @@ import java.util.Arrays; import java.util.List; +import java.util.Set; public class HashJoinSegmentCursorFactoryTest extends BaseHashJoinSegmentCursorFactoryTest { @@ -290,6 +292,70 @@ public void test_makeCursorAsync_factToCountryLeft_awaitsBaseThenJoins() } } + @Test + public void test_prefetch_factToCountryLeft_delegatesBaseSpec() + { + // prefetch must warm the left/base side with exactly the base spec the async build computes (join filter + // pushdown, base physical columns, no join prefixes), and track the base's handle. + final List joinableClauses = ImmutableList.of(factToCountryOnIsoCode(JoinType.LEFT)); + final JoinFilterPreAnalysis joinFilterPreAnalysis = + makeDefaultConfigPreAnalysis(null, joinableClauses, VirtualColumns.EMPTY); + final DeferredCursorFactory base = new DeferredCursorFactory(factSegment.as(CursorFactory.class)); + final HashJoinSegmentCursorFactory factory = new HashJoinSegmentCursorFactory( + base, + null, + joinableClauses, + joinFilterPreAnalysis + ); + final CursorBuildSpec spec = CursorBuildSpec.builder() + .setPhysicalColumns(Set.of("countryIsoCode", "c1.countryName")) + .build(); + + factory.makeCursorHolderAsync(spec).close(); + final CursorPrefetch prefetch = factory.prefetch(spec); + try { + Assertions.assertEquals(base.getPendingSpec(), base.getPrefetchSpec(), "prefetch spec must match the build spec"); + Assertions.assertEquals( + Set.of("countryIsoCode"), + base.getPrefetchSpec().getPhysicalColumns(), + "the base is asked only for base-table columns" + ); + Assertions.assertFalse(prefetch.isReady(), "prefetch waits for the base"); + base.completePrefetch(); + Assertions.assertTrue(prefetch.isReady()); + } + finally { + prefetch.close(); + } + } + + @Test + public void test_prefetch_noClauses_delegatesBaseSpec() + { + final JoinFilterPreAnalysis joinFilterPreAnalysis = + makeDefaultConfigPreAnalysis(null, ImmutableList.of(), VirtualColumns.EMPTY); + final DeferredCursorFactory base = new DeferredCursorFactory(factSegment.as(CursorFactory.class)); + final HashJoinSegmentCursorFactory factory = new HashJoinSegmentCursorFactory( + base, + null, + ImmutableList.of(), + joinFilterPreAnalysis + ); + + factory.makeCursorHolderAsync(CursorBuildSpec.FULL_SCAN).close(); + final CursorPrefetch prefetch = factory.prefetch(CursorBuildSpec.FULL_SCAN); + try { + Assertions.assertEquals(base.getPendingSpec(), base.getPrefetchSpec()); + Assertions.assertFalse(prefetch.isReady()); + prefetch.close(); + Assertions.assertTrue(base.prefetchCanceled.get(), "closing the prefetch before it's ready cancels the base"); + } + catch (Throwable t) { + prefetch.close(); + throw t; + } + } + @Test public void test_makeCursorAsync_factToCountry_closeBeforeReadyCancelsBase() { From 5283291895807f6bc336c48320533b3683075347 Mon Sep 17 00:00:00 2001 From: Clint Wylie Date: Wed, 18 Nov 2026 14:27:46 -0800 Subject: [PATCH 2/3] review adjustments --- .../apache/druid/segment/CursorFactory.java | 4 ++ .../apache/druid/segment/CursorPrefetch.java | 11 ++++ .../PartialQueryableIndexCursorFactory.java | 8 ++- .../segment/RestrictedCursorFactory.java | 14 ++--- .../druid/segment/UnnestCursorFactory.java | 8 --- .../join/HashJoinSegmentCursorFactory.java | 3 - .../druid/segment/CursorPrefetchTest.java | 10 ++++ ...artialQueryableIndexCursorFactoryTest.java | 55 +++++++++++++++++++ .../HashJoinSegmentCursorFactoryTest.java | 4 +- 9 files changed, 94 insertions(+), 23 deletions(-) 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 5ae1a8687205..e6665f13c411 100644 --- a/processing/src/main/java/org/apache/druid/segment/CursorFactory.java +++ b/processing/src/main/java/org/apache/druid/segment/CursorFactory.java @@ -58,6 +58,10 @@ 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) { diff --git a/processing/src/main/java/org/apache/druid/segment/CursorPrefetch.java b/processing/src/main/java/org/apache/druid/segment/CursorPrefetch.java index 25f3c62b5eb6..32bcf867a916 100644 --- a/processing/src/main/java/org/apache/druid/segment/CursorPrefetch.java +++ b/processing/src/main/java/org/apache/druid/segment/CursorPrefetch.java @@ -73,4 +73,15 @@ public static CursorPrefetch none() 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/PartialQueryableIndexCursorFactory.java b/processing/src/main/java/org/apache/druid/segment/PartialQueryableIndexCursorFactory.java index 57e1357fbcc4..0a3bd6403b81 100644 --- a/processing/src/main/java/org/apache/druid/segment/PartialQueryableIndexCursorFactory.java +++ b/processing/src/main/java/org/apache/druid/segment/PartialQueryableIndexCursorFactory.java @@ -170,7 +170,13 @@ public CursorPrefetch prefetch(CursorBuildSpec spec) if (plan.bundles().isEmpty()) { return CursorPrefetch.none(); } - final PendingDownloads pending = acquireHoldsAndSubmitRuns(plan.bundles()); + final PendingDownloads pending; + try { + pending = acquireHoldsAndSubmitRuns(plan.bundles()); + } + catch (Throwable t) { + return CursorPrefetch.failed(t); + } final CursorPrefetch prefetch = new CursorPrefetch(pending.canceler()); completeOnDownloadExecutor( pending, 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 c3bcbae1b359..85dbcee3dfe5 100644 --- a/processing/src/main/java/org/apache/druid/segment/RestrictedCursorFactory.java +++ b/processing/src/main/java/org/apache/druid/segment/RestrictedCursorFactory.java @@ -71,15 +71,6 @@ public CursorPrefetch prefetch(CursorBuildSpec spec) return delegate.prefetch(delegateSpec(spec)); } - /** - * The spec passed to the delegate: the caller's spec with {@link #policy} applied. Used by every delegating method - * here. - */ - private CursorBuildSpec delegateSpec(CursorBuildSpec spec) - { - return policy.visit(spec); - } - @Override public RowSignature getRowSignature() { @@ -92,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 94344cf350c1..7a27a6fbf622 100644 --- a/processing/src/main/java/org/apache/druid/segment/UnnestCursorFactory.java +++ b/processing/src/main/java/org/apache/druid/segment/UnnestCursorFactory.java @@ -109,19 +109,11 @@ public CursorPrefetch prefetch(CursorBuildSpec spec) return baseCursorFactory.prefetch(delegateSpec(spec)); } - /** - * The spec passed to the base cursor factory for {@code spec}, computing the filter split itself. - */ private CursorBuildSpec delegateSpec(CursorBuildSpec spec) { return delegateSpec(spec, computeFilterSplit(spec)); } - /** - * The spec passed to the base cursor factory: the caller's spec rewritten for the unnest input column, with only - * the base-table half of its filters (see {@link #computeFilterSplit}). Shared by every holder path, which also need - * {@code filterSplit} for the post-unnest half. - */ private CursorBuildSpec delegateSpec(CursorBuildSpec spec, UnnestFilterSplit filterSplit) { return transformCursorBuildSpec(spec, unnestColumn, filterSplit.getBaseTableFilter()); 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 b7cce6ed30ab..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 @@ -120,9 +120,6 @@ public CursorPrefetch prefetch(CursorBuildSpec spec) return baseCursorFactory.prefetch(delegateSpec(spec)); } - /** - * The spec passed to the base cursor factory for {@code spec}; see {@link #planCursor}. - */ private CursorBuildSpec delegateSpec(CursorBuildSpec spec) { return planCursor(spec).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 index 3b812afcf205..8220fd104be7 100644 --- a/processing/src/test/java/org/apache/druid/segment/CursorPrefetchTest.java +++ b/processing/src/test/java/org/apache/druid/segment/CursorPrefetchTest.java @@ -88,6 +88,16 @@ void testFailureSurfacesFromGet() 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() { 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 561d01a891f3..b835d1483ac5 100644 --- a/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexCursorFactoryTest.java +++ b/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexCursorFactoryTest.java @@ -1197,6 +1197,61 @@ public AsyncResource submitDownload(Callable task) } } + @Test + void testPrefetchHandleHoldAcquisitionFailureIsReportedThroughHandle() throws IOException + { + // The matched projection's bundle is held, then the parent __base bundle's reservation finds no room. The warm-up + // cannot start, so prefetch() returns a failed handle rather than throwing, and the hold already taken is released. + final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir); + try (IndexAndMapper opened = openIndex(rangeReader, "prefetch_no_room")) { + final PartialQueryableIndex index = opened.index(); + final ListeningExecutorService exec = directExec(); + final List acquired = new ArrayList<>(); + final AtomicInteger holdReleases = new AtomicInteger(); + final PartialBundleAcquirer acquirer = new PartialBundleAcquirer() + { + @Override + public Closeable acquire(String bundleName) + { + acquired.add(bundleName); + if (Projections.BASE_TABLE_PROJECTION_NAME.equals(bundleName)) { + throw DruidException.forPersona(DruidException.Persona.USER) + .ofCategory(DruidException.Category.CAPACITY_EXCEEDED) + .build("No room for bundle[%s]", bundleName); + } + return holdReleases::incrementAndGet; + } + + @Override + public AsyncResource submitDownload(Callable task) + { + return AsyncResources.fromFutureUnmanaged(exec.submit(task)); + } + }; + final PartialQueryableIndexCursorFactory factory = new PartialQueryableIndexCursorFactory( + index, + QueryableIndexTimeBoundaryInspector.create(index), + acquirer + ); + final CursorBuildSpec aggSpec = CursorBuildSpec.builder() + .setGroupingColumns(List.of("dim1")) + .setAggregators(List.of( + new LongSumAggregatorFactory("_metric1_sum", "metric1") + )) + .setPhysicalColumns(Set.of("dim1", "metric1")) + .build(); + + final CursorPrefetch prefetch = factory.prefetch(aggSpec); + Assertions.assertEquals(List.of(PROJECTION_NAME, Projections.BASE_TABLE_PROJECTION_NAME), acquired); + Assertions.assertTrue(prefetch.isReady(), "a warm-up that could not start is complete"); + final DruidException e = Assertions.assertThrows(DruidException.class, prefetch::get); + Assertions.assertEquals(DruidException.Category.CAPACITY_EXCEEDED, e.getCategory()); + Assertions.assertEquals(1, holdReleases.get(), "the hold taken before the failure is released"); + prefetch.close(); + Assertions.assertEquals(1, holdReleases.get(), "closing the failed handle releases nothing more"); + } + } + @Test void testPrefetchHandleAlreadyResidentStillMaterializesOnDownloadExecutor() throws Exception { diff --git a/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactoryTest.java b/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactoryTest.java index 6212627449dd..5470e8aac142 100644 --- a/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactoryTest.java +++ b/processing/src/test/java/org/apache/druid/segment/join/HashJoinSegmentCursorFactoryTest.java @@ -347,13 +347,13 @@ public void test_prefetch_noClauses_delegatesBaseSpec() try { Assertions.assertEquals(base.getPendingSpec(), base.getPrefetchSpec()); Assertions.assertFalse(prefetch.isReady()); - prefetch.close(); - Assertions.assertTrue(base.prefetchCanceled.get(), "closing the prefetch before it's ready cancels the base"); } catch (Throwable t) { prefetch.close(); throw t; } + prefetch.close(); + Assertions.assertTrue(base.prefetchCanceled.get(), "closing the prefetch before it's ready cancels the base"); } @Test From 24098a041e7b69ec94ee1b8504215f90c2c470f9 Mon Sep 17 00:00:00 2001 From: Clint Wylie Date: Thu, 19 Nov 2026 20:37:40 -0800 Subject: [PATCH 3/3] fix pre-existing things --- .../PartialQueryableIndexCursorFactory.java | 103 ++++++--- ...artialQueryableIndexCursorFactoryTest.java | 213 +++++++++++++++++- 2 files changed, 274 insertions(+), 42 deletions(-) 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 0a3bd6403b81..870587b53505 100644 --- a/processing/src/main/java/org/apache/druid/segment/PartialQueryableIndexCursorFactory.java +++ b/processing/src/main/java/org/apache/druid/segment/PartialQueryableIndexCursorFactory.java @@ -235,8 +235,8 @@ private AsyncCursorHolder buildAsyncCursorHolder( 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) { @@ -257,10 +257,17 @@ private PendingDownloads acquireHoldsAndSubmitRuns(List holdReleases.forEach(BundleHoldRelease::requestRelease)); + // 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); + } + ); } } @@ -287,7 +294,7 @@ private void completeOnDownloadExecutor( pending.downloaded().get(); } catch (Throwable t) { - fail(pending.holdReleases(), target, t); + fail(pending, target, t); return; } try { @@ -298,7 +305,7 @@ private void completeOnDownloadExecutor( } catch (Throwable t) { // the continuation couldn't even be submitted (e.g. executor shutdown rejection) - fail(pending.holdReleases(), target, t); + fail(pending, target, t); } }); } @@ -323,16 +330,12 @@ private static void produce( if (produced == null) { // a concurrent cancel requested a hold release before we could open the handshake on every bundle; the // consumer is gone, so release the rest of the holds and surface the cancellation - fail( - pending.holdReleases(), - target, - DruidException.defensive("Async resource was closed before it could be produced") - ); + fail(pending, target, DruidException.defensive("Async resource was closed before it could be produced")); return; } } catch (Throwable t) { - fail(pending.holdReleases(), target, t); + fail(pending, target, t); return; } if (!target.set(produced)) { @@ -343,13 +346,12 @@ private static void produce( } /** - * Shared failure path: request every bundle hold's release and fail the target. Releases go through the - * {@link BundleHoldRelease} handshake (never dropped directly) because failure can be observed while a sibling - * download is still mid-{@code mapFile()}. + * 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 fail(List holdReleases, SettableAsyncResource target, Throwable t) + private static void fail(PendingDownloads pending, SettableAsyncResource target, Throwable t) { - holdReleases.forEach(BundleHoldRelease::requestRelease); + pending.unwind(); target.setException(t); } @@ -496,27 +498,64 @@ private static void materializeRequiredColumns(List holdReleases, - AsyncResource> downloaded, - CursorPrefetch.Stats 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). Closes 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 requests the hold release on every bundle through the handshake. - * 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. + * 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 () -> { + 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); - }; + } + holdReleases.forEach(BundleHoldRelease::requestRelease); } } 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 b835d1483ac5..a6be37085190 100644 --- a/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexCursorFactoryTest.java +++ b/processing/src/test/java/org/apache/druid/segment/PartialQueryableIndexCursorFactoryTest.java @@ -77,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; @@ -910,6 +911,67 @@ 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 { @@ -1197,6 +1259,40 @@ public AsyncResource submitDownload(Callable task) } } + @Test + void testPrefetchHandleRunFailureCancelsSiblingRunsAndReleasesHoldsOnce() throws IOException + { + // Runs for two bundles are in flight when one of them fails. The failure completes the handle, after which closing + // it no longer runs the canceler, so the failure path itself must cancel the sibling runs rather than leave them + // to carry on for a warm-up nobody is waiting on. + final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir); + try (IndexAndMapper opened = openIndex(rangeReader, "prefetch_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 CursorPrefetch prefetch = factory.prefetch(projectionAggSpec()); + Assertions.assertTrue(submitted.size() >= 2, "the projection and its parent bundle each submit a run"); + Assertions.assertFalse(prefetch.isReady()); + + submitted.get(0).setException(new IOException("deep storage went away")); + Assertions.assertTrue(prefetch.isReady(), "a failed run download completes the prefetch"); + Assertions.assertThrows(RuntimeException.class, prefetch::get); + 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"); + + prefetch.close(); + Assertions.assertEquals(2, holdReleases.get(), "closing the failed handle releases nothing twice"); + } + } + @Test void testPrefetchHandleHoldAcquisitionFailureIsReportedThroughHandle() throws IOException { @@ -1205,8 +1301,8 @@ void testPrefetchHandleHoldAcquisitionFailureIsReportedThroughHandle() throws IO final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir); try (IndexAndMapper opened = openIndex(rangeReader, "prefetch_no_room")) { final PartialQueryableIndex index = opened.index(); - final ListeningExecutorService exec = directExec(); final List acquired = new ArrayList<>(); + final List> submitted = new ArrayList<>(); final AtomicInteger holdReleases = new AtomicInteger(); final PartialBundleAcquirer acquirer = new PartialBundleAcquirer() { @@ -1225,7 +1321,9 @@ public Closeable acquire(String bundleName) @Override public AsyncResource submitDownload(Callable task) { - return AsyncResources.fromFutureUnmanaged(exec.submit(task)); + final SettableFuture future = SettableFuture.create(); + submitted.add(future); + return AsyncResources.fromFutureUnmanaged(future); } }; final PartialQueryableIndexCursorFactory factory = new PartialQueryableIndexCursorFactory( @@ -1233,25 +1331,48 @@ public AsyncResource submitDownload(Callable task) QueryableIndexTimeBoundaryInspector.create(index), acquirer ); - final CursorBuildSpec aggSpec = CursorBuildSpec.builder() - .setGroupingColumns(List.of("dim1")) - .setAggregators(List.of( - new LongSumAggregatorFactory("_metric1_sum", "metric1") - )) - .setPhysicalColumns(Set.of("dim1", "metric1")) - .build(); - final CursorPrefetch prefetch = factory.prefetch(aggSpec); + final CursorPrefetch prefetch = factory.prefetch(projectionAggSpec()); Assertions.assertEquals(List.of(PROJECTION_NAME, Projections.BASE_TABLE_PROJECTION_NAME), acquired); Assertions.assertTrue(prefetch.isReady(), "a warm-up that could not start is complete"); final DruidException e = Assertions.assertThrows(DruidException.class, prefetch::get); Assertions.assertEquals(DruidException.Category.CAPACITY_EXCEEDED, e.getCategory()); + Assertions.assertFalse(submitted.isEmpty(), "the projection bundle's runs were submitted before the failure"); + submitted.forEach(f -> Assertions.assertTrue(f.isCancelled(), "runs submitted before the failure are cancelled")); Assertions.assertEquals(1, holdReleases.get(), "the hold taken before the failure is released"); prefetch.close(); Assertions.assertEquals(1, holdReleases.get(), "closing the failed handle releases nothing more"); } } + @Test + void testPrefetchHandleSubmitRejectionAfterPartialSubmissionCancelsSubmittedRuns() throws IOException + { + // The projection bundle's runs are submitted, then the download executor rejects the parent bundle's first run + // (e.g. a shutdown). The warm-up cannot start: the runs already submitted are cancelled rather than left running + // with no owner, every hold taken is released, and the rejection is reported through the handle. + final CountingRangeReader rangeReader = new CountingRangeReader(segmentDir); + try (IndexAndMapper opened = openIndex(rangeReader, "prefetch_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) + ); + + final CursorPrefetch prefetch = factory.prefetch(projectionAggSpec()); + Assertions.assertTrue(prefetch.isReady(), "a warm-up that could not start is complete"); + Assertions.assertThrows(RejectedExecutionException.class, prefetch::get); + 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"); + prefetch.close(); + Assertions.assertEquals(2, holdReleases.get(), "closing the failed handle releases nothing more"); + } + } + @Test void testPrefetchHandleAlreadyResidentStillMaterializesOnDownloadExecutor() throws Exception { @@ -1499,6 +1620,78 @@ void testOldMetadataWithoutColumnFilesFallsBackToWholeBundleDownload() throws IO } } + /** + * The spec the fixture's projection matches: its bundle plus the {@code __base} bundle for the parent columns its + * required columns read through, so a build or prefetch submits run downloads for two bundles. + */ + private static CursorBuildSpec projectionAggSpec() + { + return CursorBuildSpec.builder() + .setGroupingColumns(List.of("dim1")) + .setAggregators(List.of(new LongSumAggregatorFactory("_metric1_sum", "metric1"))) + .setPhysicalColumns(Set.of("dim1", "metric1")) + .build(); + } + + /** + * An acquirer whose bundle holds count their releases and whose download tasks never run: each is recorded as a + * never-completing future for the test to fail or cancel, and to observe cancellation on. + */ + private static PartialBundleAcquirer recordingAcquirer( + List> submitted, + AtomicInteger holdReleases + ) + { + return new PartialBundleAcquirer() + { + @Override + public Closeable acquire(String bundleName) + { + return holdReleases::incrementAndGet; + } + + @Override + public AsyncResource submitDownload(Callable task) + { + final SettableFuture future = SettableFuture.create(); + submitted.add(future); + return AsyncResources.fromFutureUnmanaged(future); + } + }; + } + + /** + * Like {@link #recordingAcquirer}, except that the download executor rejects every submission once a second bundle + * hold has been taken, modeling a shutdown partway through a multi-bundle setup. + */ + private static PartialBundleAcquirer rejectingAfterFirstBundleAcquirer( + List> submitted, + AtomicInteger holdReleases + ) + { + final AtomicInteger acquired = new AtomicInteger(); + return new PartialBundleAcquirer() + { + @Override + public Closeable acquire(String bundleName) + { + acquired.incrementAndGet(); + return holdReleases::incrementAndGet; + } + + @Override + public AsyncResource submitDownload(Callable task) + { + if (acquired.get() > 1) { + throw new RejectedExecutionException("download executor is shut down"); + } + final SettableFuture future = SettableFuture.create(); + submitted.add(future); + return AsyncResources.fromFutureUnmanaged(future); + } + }; + } + private File buildNestedSegment() throws IOException { final File tmpDir = temporaryFolder.newFolder(