← Back to Pull requests

fix: Do not block in ChainedProcessorManager.next(). #20321

Open
gianm opened this pull request with 399 lines diff across 5 files
View on GitHub
gianm gianm commented on Sep 10, 2026 18:06 UTC
Author

Previously, a blocking Future wait ran inside next(), which could cause a processing thread to block while waiting for the next processor to be ready. This patch fixes it by moving resolution to a callback.

Diff: 399 lines (+363 / -36) across 5 files Reviewer: clintropolis Review duration: 103770m
All Vouch review confidence checks passed
Residual risk 0.07 = Change Risk (0.52) × (1 − Review Confidence (0.87)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 399 lines diff across 5 files
0.52
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.86 · 5 substantive comment(s)
0.86
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
86%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.358
Real PR Conversation Timeline
10 items
FrankChen021 FrankChen021 commented on code on Sep 11, 2026 02:53 UTC
Code Review
multi-stage-query/src/main/java/org/apache/druid/msq/querykit/ChainedProcessorManager.java:1
@@ -88,32 +111,70 @@ public ChainedProcessorManager(
   @Override
   public ListenableFuture<Optional<ProcessorAndCallback<Object>>> next()
   {
-    if (closed) {
-      throw new IllegalStateException();
-    } else if (first != null) {
-      Optional<ProcessorAndCallback<A>> processorAndCallbackOptional = Futures.getUnchecked(first.next());
-      if (processorAndCallbackOptional.isPresent()) {
-        // More processors left to run.
-        firstProcessorCount.incrementAndGet();
-        ProcessorAndCallback<A> aProcessorAndCallback = processorAndCallbackOptional.get();
-        //noinspection unchecked
-        return Futures.immediateFuture(Optional.of((ProcessorAndCallback<Object>) aProcessorAndCallback));
-      } else {
-        first = null;
-        checkFirstProcessorComplete();
+    final ListenableFuture<Optional<ProcessorAndCallback<A>>> nextFromFirst;
+
+    synchronized (lock) {
+      if (closed) {
+        throw new IllegalStateException();
+      } else if (first == null) {
+        return nextFromRest();
       }
+
+      nextFromFirst = first.next();
     }
 
-    //noinspection unchecked
+    return FutureUtils.transformAsync(
+        nextFromFirst,
+        processorAndCallback -> {
+          synchronized (lock) {
+            if (!closed) {
+              if (processorAndCallback.isPresent()) {
+                // More processors left to run.
+                firstProcessorCount++;
+                //noinspection unchecked
+                return Futures.immediateFuture(Optional.of((ProcessorAndCallback<Object>) processorAndCallback.get()));
+              } else {
+                first = null;
+                checkFirstProcessorComplete();
+                return nextFromRest();
+              }
+            }
+          }
+
+          // Closed while we were waiting. Clean up the processor we were handed.
+          if (processorAndCallback.isPresent()) {
+            final FrameProcessor<A> processor = processorAndCallback.get().processor();
+            CloseableUtils.closeAndSuppressExceptions(
+                processor::cleanup,
+                e -> log.noStackTrace().warn(e, "Failed to clean up processor[%s] after close", processor)
+            );
+          }
+
+          return Futures.immediateFuture(Optional.empty());
+        }
+    );
+  }
+
+  /**
+   * Returns the next processor from {@link #restFuture}, once that manager is available.
+   */
+  private ListenableFuture<Optional<ProcessorAndCallback<Object>>> nextFromRest()
+  {
+    //noinspection unchecked, rawtypes
     return FutureUtils.transformAsync(

[P2] Clean up rest processors that arrive after close

Once restFuture has already been resolved, close() cannot cancel it; a pending rest.next() can therefore still resolve with a ProcessorAndCallback after the manager is closed. nextFromRest() forwards that value without checking closed or cleaning up the returned FrameProcessor, unlike the first-phase callback above. During a failure or cancellation, RunAllFullyWidget can discard this late processor after its manager has been closed, leaving its channels or other resources uncleaned. Route rest.next() through the same post-close cleanup path (or otherwise cancel/track the in-flight future).

FrankChen021 FrankChen021 commented on Sep 11, 2026 02:53 UTC
Reviewer

🟡 Changes recommended

The change removes the blocking wait from the first phase and synchronizes the phase transition correctly. One cleanup race remains in the asynchronous rest phase: after the rest manager has been created, a pending rest.next() can resolve after close and return a processor that is no longer owned by the executor. That processor needs the same post-close cleanup handling as processors returned by the first phase.

Reviewed 2 of 2 changed files. This was a static review; no local build or test commands were run.

| Severity | Findings |
| --- | ---: |
| P0 | 0 |
| P1 | 0 |
| P2 | 1 |
| P3 | 0 |
| Total | 1 |

<!-- mergelens:review -->

---

This is an automated review by Codex GPT-5.6 Luna(Max)

After addressing the findings or replying to the comments, you can request another review from me to trigger a new automated review.

gianm gianm commented on code on Nov 04, 2026 19:37 UTC
Code Review
multi-stage-query/src/main/java/org/apache/druid/msq/querykit/ChainedProcessorManager.java:1
@@ -88,32 +111,70 @@ public ChainedProcessorManager(
   @Override
   public ListenableFuture<Optional<ProcessorAndCallback<Object>>> next()
   {
-    if (closed) {
-      throw new IllegalStateException();
-    } else if (first != null) {
-      Optional<ProcessorAndCallback<A>> processorAndCallbackOptional = Futures.getUnchecked(first.next());
-      if (processorAndCallbackOptional.isPresent()) {
-        // More processors left to run.
-        firstProcessorCount.incrementAndGet();
-        ProcessorAndCallback<A> aProcessorAndCallback = processorAndCallbackOptional.get();
-        //noinspection unchecked
-        return Futures.immediateFuture(Optional.of((ProcessorAndCallback<Object>) aProcessorAndCallback));
-      } else {
-        first = null;
-        checkFirstProcessorComplete();
+    final ListenableFuture<Optional<ProcessorAndCallback<A>>> nextFromFirst;
+
+    synchronized (lock) {
+      if (closed) {
+        throw new IllegalStateException();
+      } else if (first == null) {
+        return nextFromRest();
       }
+
+      nextFromFirst = first.next();
     }
 
-    //noinspection unchecked
+    return FutureUtils.transformAsync(
+        nextFromFirst,
+        processorAndCallback -> {
+          synchronized (lock) {
+            if (!closed) {
+              if (processorAndCallback.isPresent()) {
+                // More processors left to run.
+                firstProcessorCount++;
+                //noinspection unchecked
+                return Futures.immediateFuture(Optional.of((ProcessorAndCallback<Object>) processorAndCallback.get()));
+              } else {
+                first = null;
+                checkFirstProcessorComplete();
+                return nextFromRest();
+              }
+            }
+          }
+
+          // Closed while we were waiting. Clean up the processor we were handed.
+          if (processorAndCallback.isPresent()) {
+            final FrameProcessor<A> processor = processorAndCallback.get().processor();
+            CloseableUtils.closeAndSuppressExceptions(
+                processor::cleanup,
+                e -> log.noStackTrace().warn(e, "Failed to clean up processor[%s] after close", processor)
+            );
+          }
+
+          return Futures.immediateFuture(Optional.empty());
+        }
+    );
+  }
+
+  /**
+   * Returns the next processor from {@link #restFuture}, once that manager is available.
+   */
+  private ListenableFuture<Optional<ProcessorAndCallback<Object>>> nextFromRest()
+  {
+    //noinspection unchecked, rawtypes
     return FutureUtils.transformAsync(

Fixed this by adjusting the contract so RunAllFullyWidget handles the closing.

FrankChen021 FrankChen021 commented on code on Nov 05, 2026 12:51 UTC
Code Review
multi-stage-query/src/main/java/org/apache/druid/msq/querykit/ChainedProcessorManager.java:1
@@ -88,32 +111,70 @@ public ChainedProcessorManager(
   @Override
   public ListenableFuture<Optional<ProcessorAndCallback<Object>>> next()
   {
-    if (closed) {
-      throw new IllegalStateException();
-    } else if (first != null) {
-      Optional<ProcessorAndCallback<A>> processorAndCallbackOptional = Futures.getUnchecked(first.next());
-      if (processorAndCallbackOptional.isPresent()) {
-        // More processors left to run.
-        firstProcessorCount.incrementAndGet();
-        ProcessorAndCallback<A> aProcessorAndCallback = processorAndCallbackOptional.get();
-        //noinspection unchecked
-        return Futures.immediateFuture(Optional.of((ProcessorAndCallback<Object>) aProcessorAndCallback));
-      } else {
-        first = null;
-        checkFirstProcessorComplete();
+    final ListenableFuture<Optional<ProcessorAndCallback<A>>> nextFromFirst;
+
+    synchronized (lock) {
+      if (closed) {
+        throw new IllegalStateException();
+      } else if (first == null) {
+        return nextFromRest();
       }
+
+      nextFromFirst = first.next();
     }
 
-    //noinspection unchecked
+    return FutureUtils.transformAsync(
+        nextFromFirst,
+        processorAndCallback -> {
+          synchronized (lock) {
+            if (!closed) {
+              if (processorAndCallback.isPresent()) {
+                // More processors left to run.
+                firstProcessorCount++;
+                //noinspection unchecked
+                return Futures.immediateFuture(Optional.of((ProcessorAndCallback<Object>) processorAndCallback.get()));
+              } else {
+                first = null;
+                checkFirstProcessorComplete();
+                return nextFromRest();
+              }
+            }
+          }
+
+          // Closed while we were waiting. Clean up the processor we were handed.
+          if (processorAndCallback.isPresent()) {
+            final FrameProcessor<A> processor = processorAndCallback.get().processor();
+            CloseableUtils.closeAndSuppressExceptions(
+                processor::cleanup,
+                e -> log.noStackTrace().warn(e, "Failed to clean up processor[%s] after close", processor)
+            );
+          }
+
+          return Futures.immediateFuture(Optional.empty());
+        }
+    );
+  }
+
+  /**
+   * Returns the next processor from {@link #restFuture}, once that manager is available.
+   */
+  private ListenableFuture<Optional<ProcessorAndCallback<Object>>> nextFromRest()
+  {
+    //noinspection unchecked, rawtypes
     return FutureUtils.transformAsync(

Follow-up review: this addresses my cleanup concern. RunAllFullyWidget.cleanupNextProcessor() now tracks the outstanding next() future before processorManager.close(), so a ProcessorAndCallback that resolves after close is cleaned instead of discarded. The added regression test covers this failure path. Reviewed 5 of 5 changed files.

<!-- mergelens:review -->

FrankChen021 FrankChen021 commented on code on Nov 05, 2026 13:27 UTC
Code Review
multi-stage-query/src/main/java/org/apache/druid/msq/querykit/ChainedProcessorManager.java:1
@@ -129,12 +169,18 @@ public R result()
   @Override
   public void close()
   {
-    if (!closed) {
+    synchronized (lock) {
+      if (closed) {
+        return;
+      }
       closed = true;
-      CloseableUtils.closeAndWrapExceptions(() -> CloseableUtils.closeAll(
-          first,
-          restFuture.isDone() ? FutureUtils.getUnchecked(restFuture, false) : null
-      ));
     }
+
+    // Close outside the lock: restFuture can no longer change, since checkFirstProcessorComplete() does nothing
+    // once closed.
+    CloseableUtils.closeAndWrapExceptions(() -> CloseableUtils.closeAll(
+        first,
+        restFuture.isDone() ? FutureUtils.getUnchecked(restFuture, false) : null

[P2] Complete pending next futures on close

Finding: When the first phase has returned empty but its processors are still completing, next() can already be waiting on nextFromRest(). If the run then fails or is cancelled, close() sets closed, so checkFirstProcessorComplete() will never set restFuture; because this close path no longer cancels it, the returned future remains permanently pending and retains the waiting callback.

Suggestion: Restore close-time cancellation of restFuture, or otherwise complete every outstanding nextFromRest() future after marking the manager closed.

FrankChen021 FrankChen021 commented on Nov 05, 2026 13:27 UTC
Reviewer

🟡 Changes recommended

Close-time cancellation of restFuture was removed, leaving some next() futures permanently pending after failure or cancellation. Restore completion/cancellation of those futures before merging. The prior late-processor cleanup race is addressed by cleanupNextProcessor.

Reviewed 5 of 5 changed files. This updated-since-review pass started with the supplied incremental diff, then covered the full current PR diff and relevant executor/manager code. Static review only; no build or test commands were run.

| Severity | Findings |
| --- | ---: |
| P0 | 0 |
| P1 | 0 |
| P2 | 1 |
| P3 | 0 |
| Total | 1 |

<!-- mergelens:review -->

---

This is an automated review by Codex GPT-5.6-Luna(max)

After addressing the findings or replying to the comments, you can request another review from me to trigger a new automated review.

gianm gianm commented on code on Nov 05, 2026 18:25 UTC
Code Review
multi-stage-query/src/main/java/org/apache/druid/msq/querykit/ChainedProcessorManager.java:1
@@ -129,12 +169,18 @@ public R result()
   @Override
   public void close()
   {
-    if (!closed) {
+    synchronized (lock) {
+      if (closed) {
+        return;
+      }
       closed = true;
-      CloseableUtils.closeAndWrapExceptions(() -> CloseableUtils.closeAll(
-          first,
-          restFuture.isDone() ? FutureUtils.getUnchecked(restFuture, false) : null
-      ));
     }
+
+    // Close outside the lock: restFuture can no longer change, since checkFirstProcessorComplete() does nothing
+    // once closed.
+    CloseableUtils.closeAndWrapExceptions(() -> CloseableUtils.closeAll(
+        first,
+        restFuture.isDone() ? FutureUtils.getUnchecked(restFuture, false) : null

Restored close-time cancellation of restFuture.

FrankChen021 FrankChen021 commented on Nov 06, 2026 01:09 UTC
Reviewer

🟢 Approval recommended

The prior pending-restFuture issue is fixed by canceling restFuture on close, and the new regression test covers a pending nextFromRest() future. I also reviewed the full merge-base diff, the incremental fix, the FrameProcessorExecutor/RunAllFullyWidget lifecycle, all in-repository ProcessorManager implementations, and the ChainedProcessorManager call sites. No actionable correctness, concurrency, cleanup, or compatibility issues remain.

Reviewed 5 of 5 changed files.

Validation: the local merge simulation against origin/master completed cleanly and git diff --check passed. No build or test commands were run.

<!-- mergelens:review -->

---

This is an automated review by Codex GPT-5.6 Luna(Max)

clintropolis clintropolis approved these changes on Nov 09, 2026 19:35 UTC
Approved Reviewer

Approved these changes.

Reviewers
Assignees
gianm gianm
Labels
risk: low confidence: 86.6% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 51.7% (MEDIUM) · Higher = larger blast radius
51.7%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 86.6% · Lower = rushed or shallow review
86.6%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 6.9% · Safe to merge
6.9%
Repository