This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-7122-f863ad26ddb3083bf2cc7e4105255e1010a8bbf0
in repository https://gitbox.apache.org/repos/asf/texera.git

commit 6597c1b2cbb446da4cae4c8b6bbc0dafcf010232
Author: Martin Vu <[email protected]>
AuthorDate: Mon Nov 16 07:21:28 2026 +0000

    fix(amber): prevent region termination retry hang (#7122)
    
    ### What changes were proposed in this PR?
    
    This PR fixes a region termination hang caused by unresponsive
    `EndWorker` RPC calls.
    
    Previously, `Future.collect(endWorkerRequests)` could wait forever if a
    worker never responded. This prevented the termination retry mechanism
    from running because the failure was never propagated, causing the
    workflow to silently stall.
    
    This change adds a 6s timeout around each termination attempt (5s
    gracefulStop + 1s drain allowance) so stuck EndWorker and gracefulStop
    operations fail and trigger the existing retry budget.
    
    Cleanup of actor references and control channels is now delayed until
    graceful termination succeeds and is performed on the coordinator actor
    thread via a CleanupWorkerChannels message. The termination future
    awaits the cleanup Promise, ensuring the channels are removed before
    termination is considered complete.
    
    **Before:** gracefulStop timeout → silent hang forever.
    <img width="1327" height="619" alt="Screenshot 2026-07-29 at 1 26 05 AM"
    
src="https://github.com/user-attachments/assets/e5ca9a61-057a-4533-a79f-94ce83fedd2f";
    />
    
    **After:** timeout → 4 attempts total → error.
    <img width="1338" height="359" alt="Screenshot 2026-07-29 at 11 21
    16 PM"
    
src="https://github.com/user-attachments/assets/1d299430-fdd9-42bd-8268-3248f7fcca25";
    />
    
    ### Any related issues, documentation, discussions?
    
    Fixes #6920
    
    ### How was this PR tested?
    
    
    - **Unit test added:** `"retry EndWorker when the termination timeout
    expires"` in `RegionExecutionManagerSpec.scala` verifies that a
    non‑responding `EndWorker` triggers a timeout and retry.
    - **Existing tests updated:** backoff tests now use
    `terminationTimeoutMs = Long.MaxValue` to isolate the retry logic.
    - **Manual verification:** Simulated slow worker shutdown (> 5s delay).
    Confirmed retry loop executes all 4 attempts and error fires with stuck
    workers listed. No silent hang.
    - Ran the `RegionExecutionManagerSpec` test suite locally — all tests
    pass.
    
    ### Was this PR authored or co-authored using generative AI tooling?
    
    Generated-by: ChatGPT (5.5-mini)
    
    ---------
    
    Signed-off-by: Martin Vu <[email protected]>
    Co-authored-by: Claude Sonnet 5 <[email protected]>
---
 .../architecture/coordinator/Coordinator.scala     |  44 +++++-
 .../scheduling/RegionExecutionManager.scala        |  92 ++++++++-----
 .../scheduling/RegionExecutionManagerSpec.scala    | 152 +++++++++++++++++++--
 .../RegionExecutionManagerTestSupport.scala        |  62 +++++++--
 .../scheduling/WorkflowExecutionManagerSpec.scala  |   2 +-
 5 files changed, 294 insertions(+), 58 deletions(-)

diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/Coordinator.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/Coordinator.scala
index 167602113e..6030e6748e 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/Coordinator.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/Coordinator.scala
@@ -27,6 +27,7 @@ import 
org.apache.texera.amber.core.virtualidentity.ChannelIdentity
 import org.apache.texera.amber.core.workflow.{PhysicalPlan, WorkflowContext}
 import 
org.apache.texera.amber.engine.architecture.common.WorkflowActor.NetworkAck
 import org.apache.texera.amber.engine.architecture.common.{ExecutorDeployment, 
WorkflowActor}
+import 
org.apache.texera.amber.engine.architecture.common.PekkoActorRefMappingService
 import 
org.apache.texera.amber.engine.architecture.coordinator.execution.OperatorExecution
 import org.apache.texera.amber.engine.architecture.rpc.controlcommands.{
   ControlInvocation,
@@ -41,9 +42,12 @@ import org.apache.texera.amber.engine.common.ambermessage.{
   DirectControlMessagePayload,
   WorkflowFIFOMessage
 }
+import org.apache.texera.amber.engine.common.rpc.AsyncRPCClient
 import org.apache.texera.amber.engine.common.virtualidentity.util.{CLIENT, 
COORDINATOR, SELF}
 import org.apache.texera.amber.engine.common.{CheckpointState, SerializedState}
 import org.apache.texera.web.SessionState
+import org.apache.texera.amber.core.virtualidentity.ActorVirtualIdentity
+import com.twitter.util.Promise
 
 import scala.concurrent.duration.DurationInt
 
@@ -66,6 +70,29 @@ final case class CoordinatorConfig(
 )
 
 object Coordinator {
+  // Removing a worker's actorRef stops other actors from reaching it. 
Restarted regions reuse
+  // actorId, so the control channels must go too: otherwise the coordinator 
resumes the old
+  // control-message sequence numbers and the new worker discards its commands 
as duplicates.
+  //
+  // `forceTerminateWorkers` must run on the coordinator thread because it 
mutates worker state,
+  // which can otherwise race with concurrent worker state updates.
+  case class CleanupWorkerChannels(
+      workerIds: Seq[ActorVirtualIdentity],
+      forceTerminateWorkers: () => Unit,
+      completionPromise: Promise[Unit]
+  )
+
+  def cleanupWorkerChannels(
+      workerIds: Seq[ActorVirtualIdentity],
+      asyncRPCClient: AsyncRPCClient,
+      actorRefService: PekkoActorRefMappingService
+  ): Unit = {
+    workerIds.foreach { workerId =>
+      asyncRPCClient.inputGateway.removeControlChannel(workerId)
+      asyncRPCClient.outputGateway.removeControlChannel(workerId)
+      actorRefService.removeActorRef(workerId)
+    }
+  }
 
   def props(
       workflowContext: WorkflowContext,
@@ -189,10 +216,23 @@ class Coordinator(
       globalReplayManager.markRecoveryStatus(id, status)
   }
 
-  override def receive: Receive = {
-    super.receive orElse handleDirectInvocation orElse handleReplayMessages
+  private def handleCleanupWorkerChannels: Receive = {
+    case Coordinator.CleanupWorkerChannels(workerIds, forceTerminateWorkers, 
completionPromise) =>
+      forceTerminateWorkers()
+      Coordinator.cleanupWorkerChannels(
+        workerIds,
+        cp.asyncRPCClient,
+        cp.actorRefService
+      )
+      completionPromise.setDone()
   }
 
+  override def receive: Receive =
+    handleCleanupWorkerChannels orElse
+      super.receive orElse
+      handleDirectInvocation orElse
+      handleReplayMessages
+
   /** flow-control */
   override def getQueuedCredit(channelId: ChannelIdentity): Long = {
     0 // no queued credit for coordinator
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionExecutionManager.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionExecutionManager.scala
index 51910a5041..a012538a5b 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionExecutionManager.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionExecutionManager.scala
@@ -19,8 +19,8 @@
 
 package org.apache.texera.amber.engine.architecture.scheduling
 
-import org.apache.pekko.pattern.gracefulStop
 import com.twitter.util.{Future, JavaTimer, Promise, Return, Throw, Timer}
+import org.apache.pekko.pattern.gracefulStop
 import org.apache.texera.amber.core.WorkflowRuntimeException
 import org.apache.texera.amber.core.state.State
 import org.apache.texera.amber.core.storage.{DocumentFactory, 
RepositoryMountManager, VFSURIFactory}
@@ -31,6 +31,7 @@ import org.apache.texera.amber.engine.architecture.common.{
   PekkoActorService,
   ExecutorDeployment
 }
+import org.apache.texera.amber.engine.architecture.coordinator.Coordinator
 import org.apache.texera.amber.engine.architecture.coordinator.execution.{
   OperatorExecution,
   RegionExecution,
@@ -67,12 +68,19 @@ object RegionExecutionManager {
 
   // Terminating a region is deterministic: `EndWorker` plus `gracefulStop` 
either succeed, or the
   // engine has a bug that retrying cannot fix. Retries therefore only ride 
out a transient
-  // failure. With `Utils.retry`'s doubling backoff, 4 attempts from a 200ms 
base wait
-  // 200 + 400 + 800 ms = 1.4s in the worst case, where the former 150 
attempts at a flat 200ms
-  // held a whole region's teardown for ~30s before the failure surfaced.
+  // failure. With `Utils.retry`'s doubling backoff and a 6s timeout per 
attempt
+  // (5s gracefulStop + 1s drain allowance), 4 attempts take ~25.4s
+  // in the worst case (4 × 6s + 1.4s backoff), compared with the former
+  // 150 attempts at a flat 200ms, which held a whole region's teardown for 
~30s before failure.
   private[scheduling] val DefaultMaxTerminationAttempts: Int = 4
 
   private[scheduling] val DefaultKillRetryBaseBackoffMs: Long = 200L
+
+  private[scheduling] val DefaultGracefulStopTimeoutMs: Long = 5000L
+  private[scheduling] val DefaultTerminationDrainAllowanceMs: Long = 1000L
+
+  private[scheduling] val DefaultTerminationTimeoutMs: Long =
+    DefaultGracefulStopTimeoutMs + DefaultTerminationDrainAllowanceMs
 }
 
 /**
@@ -114,6 +122,7 @@ class RegionExecutionManager(
     maxTerminationAttempts: Int = 
RegionExecutionManager.DefaultMaxTerminationAttempts,
     killRetryBaseBackoffMs: Long = 
RegionExecutionManager.DefaultKillRetryBaseBackoffMs,
     killRetryTimer: Timer = new JavaTimer(true),
+    terminationTimeoutMs: Long = 
RegionExecutionManager.DefaultTerminationTimeoutMs,
     // Loop bookkeeping addresses (Loop Start logical op id -> its input
     // port's BASE materialization URI), shipped to every worker in
     // InitializeExecutorRequest. See 
WorkflowExecutionManager.loopStartPortUris.
@@ -191,7 +200,9 @@ class RegionExecutionManager(
   }
 
   private def terminateWorkers(regionExecution: RegionExecution) = {
-    // 1. Send EndWorkers to every worker
+    implicit val timer: Timer = killRetryTimer
+    val killTimeout = 
com.twitter.util.Duration.fromMilliseconds(terminationTimeoutMs)
+    // 1. Send EndWorkers to every worker.
     val endWorkerRequests =
       regionExecution.getAllOperatorExecutions.flatMap {
         case (_, opExec) =>
@@ -201,41 +212,52 @@ class RegionExecutionManager(
           }
       }.toSeq
 
-    val endWorkerFuture: Future[Unit] =
-      Future.collect(endWorkerRequests).unit
-
-    // 2. Send GracefulStops only after 1 has finished
-    val gracefulStopRequests: Future[Unit] =
-      endWorkerFuture.flatMap { _ =>
-        val gracefulStops =
-          regionExecution.getAllOperatorExecutions.flatMap {
-            case (_, opExec) =>
-              opExec.getWorkerIds.map { workerId =>
-                val actorRef = actorRefService.getActorRef(workerId)
-                // Remove the actorRef so that no other actors can find the 
worker and send messages.
-                actorRefService.removeActorRef(workerId)
-                // Restarted regions reuse actorId. Remove stale control 
channels so the
-                // coordinator does not reuse old control-message sequence 
numbers for new workers.
-                asyncRPCClient.inputGateway.removeControlChannel(workerId)
-                asyncRPCClient.outputGateway.removeControlChannel(workerId)
-                gracefulStop(actorRef, ScalaDuration(5, 
TimeUnit.SECONDS)).asTwitter()
-              }
-          }.toSeq
+    val terminationAttempt =
+      Future
+        .collect(endWorkerRequests)
+        .unit
+        .flatMap { _ =>
+          // 2. Only send GracefulStops after all EndWorkers have succeeded.
+          val gracefulStopRequests =
+            regionExecution.getAllOperatorExecutions.flatMap {
+              case (_, opExec) =>
+                opExec.getWorkerIds.map { workerId =>
+                  val actorRef = actorRefService.getActorRef(workerId)
+                  gracefulStop(
+                    actorRef,
+                    ScalaDuration(
+                      RegionExecutionManager.DefaultGracefulStopTimeoutMs,
+                      TimeUnit.MILLISECONDS
+                    )
+                  ).asTwitter()
+                }
+            }.toSeq
 
-        Future.collect(gracefulStops).unit
-      }
+          Future.collect(gracefulStopRequests).unit
+        }
+        .within(killTimeout)
 
-    // 3. Log whether the kills were successful
-    gracefulStopRequests.transform {
+    // 3. Clean up only after graceful termination succeeds, and only on the 
coordinator's own
+    // thread
+    terminationAttempt.transform {
       case Return(_) =>
         logger.debug(s"Region ${region.id.id} successfully terminated.")
-        regionExecution.getAllOperatorExecutions.foreach {
-          case (_, opExec) =>
-            opExec.getWorkerIds.foreach { workerId =>
-              opExec.getWorkerExecution(workerId).forceTerminate()
-            }
+        val allWorkerIds = 
regionExecution.getAllOperatorExecutions.toSeq.flatMap {
+          case (_, opExec) => opExec.getWorkerIds
         }
-        Future.Unit // propagate success
+        val cleanupPromise = Promise[Unit]()
+        actorService.self ! Coordinator.CleanupWorkerChannels(
+          allWorkerIds,
+          forceTerminateWorkers = () =>
+            regionExecution.getAllOperatorExecutions.foreach {
+              case (_, opExec) =>
+                opExec.getWorkerIds.foreach { workerId =>
+                  opExec.getWorkerExecution(workerId).forceTerminate()
+                }
+            },
+          cleanupPromise
+        )
+        cleanupPromise
       case Throw(err) =>
         logger.warn(s"Error when terminating region ${region.id}.")
         Future.exception(err) // propagate failure
diff --git 
a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionExecutionManagerSpec.scala
 
b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionExecutionManagerSpec.scala
index afd3836a68..c0cfee552b 100644
--- 
a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionExecutionManagerSpec.scala
+++ 
b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionExecutionManagerSpec.scala
@@ -20,7 +20,7 @@
 package org.apache.texera.amber.engine.architecture.scheduling
 
 import com.twitter.util.{Future, JavaTimer, Time, Timer}
-import org.apache.pekko.actor.ActorSystem
+import org.apache.pekko.actor.{ActorSystem, Props}
 import org.apache.pekko.testkit.TestKit
 import org.apache.texera.amber.core.executor.{OpExecInitInfo, 
OpExecWithClassName}
 import org.apache.texera.amber.core.storage.VFSURIFactory
@@ -193,6 +193,127 @@ class RegionExecutionManagerSpec
     assert(workerState(fixture) == WorkerState.TERMINATED)
   }
 
+  it should "retry EndWorker when the termination timeout expires" in {
+    val fixture = createSingleRegionFixture(
+      endWorkerResponse = _ => None,
+      maxTerminationAttempts = 2,
+      killRetryBaseBackoffMs = fastRetryBackoffMs,
+      terminationTimeoutMs = 10L
+    )
+
+    launchRegion(fixture.manager)
+    val completion = requestRegionCompletion(fixture.manager)
+
+    val failure = intercept[IllegalStateException] {
+      await(completion)
+    }
+
+    assert(failure.getMessage.contains("could not be terminated after 2 
attempts"))
+    assert(fixture.rpcProbe.endWorkerCalls.size == 2)
+    assert(!fixture.manager.isCompleted)
+  }
+
+  it should "complete once a retry succeeds after the termination timeout 
expired" in {
+    // First attempt times out; the retry succeeds.
+    val attempts = new atomic.AtomicInteger(0)
+    val fixture = createSingleRegionFixture(
+      endWorkerResponse = _ => if (attempts.incrementAndGet() == 1) None else 
Some(EmptyReturn()),
+      maxTerminationAttempts = 2,
+      killRetryBaseBackoffMs = fastRetryBackoffMs,
+      terminationTimeoutMs = 50L
+    )
+
+    launchRegion(fixture.manager)
+    val completion = requestRegionCompletion(fixture.manager)
+    await(completion)
+
+    assert(fixture.manager.isCompleted)
+    assert(fixture.rpcProbe.endWorkerCalls.size == 2)
+    assert(!fixture.actorRefService.hasActorRef(fixture.workerId))
+    assert(workerState(fixture) == WorkerState.TERMINATED)
+  }
+
+  it should "leave the actor ref and control channels in place when 
gracefulStop itself times out" in {
+    // Block the worker so gracefulStop times out. Cleanup should not happen 
on failure.
+    val blockGate = new CountDownLatch(1)
+    val physicalOp = createSourceOp("test-op")
+    val workerId = createWorkerId(physicalOp)
+    val region = createSingleWorkerRegion(1, physicalOp, workerId)
+
+    val workflowExecution = WorkflowExecution()
+    seedReusableWorkerExecution(workflowExecution, seedRegionId = 0, 
physicalOp, workerId)
+    workflowExecution.initRegionExecution(region)
+
+    val rpcProbe = new CoordinatorRpcProbe(_ => Some(EmptyReturn()))
+    val coordinator = createCoordinatorHarness(rpcProbe)
+    val workerRef = system.actorOf(Props(new BlockingActor(blockGate)))
+    coordinator.actorRefService.registerActorRef(workerId, workerRef)
+    workerRef ! BlockingActor.Block
+
+    val controlChannelId = ChannelIdentity(workerId, COORDINATOR, isControl = 
true)
+    rpcProbe.inputGateway.getChannel(controlChannelId)
+    rpcProbe.outputGateway.getSequenceNumber(
+      ChannelIdentity(COORDINATOR, workerId, isControl = true)
+    )
+
+    val manager = new RegionExecutionManager(
+      region,
+      isRestart = false,
+      workflowExecution,
+      rpcProbe.asyncRPCClient,
+      CoordinatorConfig(None, None, None, None),
+      coordinator.actorService,
+      coordinator.actorRefService,
+      maxTerminationAttempts = 1,
+      killRetryBaseBackoffMs = fastRetryBackoffMs,
+      killRetryTimer = new JavaTimer(true),
+      terminationTimeoutMs = 50L
+    )
+
+    try {
+      await(manager.syncStatusAndTransitionRegionExecutionPhase())
+      val failure = intercept[IllegalStateException] {
+        await(manager.syncStatusAndTransitionRegionExecutionPhase())
+      }
+
+      assert(failure.getMessage.contains("could not be terminated after 1 
attempt"))
+      assert(!manager.isCompleted)
+      assert(coordinator.actorRefService.hasActorRef(workerId))
+      assert(rpcProbe.inputGateway.getAllControlChannels.exists(_.channelId == 
controlChannelId))
+    } finally {
+      blockGate.countDown()
+    }
+  }
+
+  it should "not complete the region until the coordinator has processed the 
cleanup message" in {
+    // Hold cleanup on the coordinator thread and verify completion waits for 
it.
+    val cleanupStarted = new CountDownLatch(1)
+    val cleanupGate = new CountDownLatch(1)
+    val fixture = createSingleRegionFixture(
+      endWorkerResponse = _ => None,
+      beforeCleanup = () => {
+        cleanupStarted.countDown()
+        cleanupGate.await()
+      }
+    )
+
+    launchRegion(fixture.manager)
+    val completion = requestRegionCompletion(fixture.manager)
+    fixture.rpcProbe.fulfill(fixture.rpcProbe.onlyEndWorkerCall, EmptyReturn())
+
+    assert(
+      cleanupStarted.await(testTimeout.inMilliseconds, TimeUnit.MILLISECONDS),
+      "cleanup was never attempted"
+    )
+    assert(completion.poll.isEmpty, "region completed before the coordinator 
processed cleanup")
+    assert(!fixture.manager.isCompleted)
+
+    cleanupGate.countDown()
+    await(completion)
+
+    assert(fixture.manager.isCompleted)
+  }
+
   it should "give up with a descriptive error once the EndWorker retry budget 
is exhausted" in {
     // EndWorker always fails: a worker that never finishes draining.
     val fixture = createSingleRegionFixture(
@@ -286,12 +407,14 @@ class RegionExecutionManagerSpec
     assert(fixture.rpcProbe.endWorkerCalls.size == fixture.workerIds.size * 2)
   }
 
-  it should "default to a bounded ~1.4s termination budget" in {
-    // 4 attempts from a 200 ms base, doubling: 200 + 400 + 800 ms = ~1.4 s of 
waiting, not the
-    // former 150 x 200 ms (~30 s). This is the documented contract for how 
long a stuck region
-    // blocks before failing loudly; pin it so changes are deliberate.
+  it should "default to a bounded ~25.4s termination budget" in {
+    // 4 attempts from a 200 ms base, doubling: 200 + 400 + 800 ms = ~1.4 s of 
backoff, plus
+    // a 6 s timeout per attempt. Worst-case teardown is ~25.4 s. This is the 
documented
+    // contract for how long a stuck region blocks before failing loudly; pin 
it so changes
+    // are deliberate.
     assert(RegionExecutionManager.DefaultMaxTerminationAttempts == 4)
     assert(RegionExecutionManager.DefaultKillRetryBaseBackoffMs == 200L)
+    assert(RegionExecutionManager.DefaultTerminationTimeoutMs == 6000L)
   }
 
   it should "back off exponentially and stop once the retry budget is 
exhausted" in {
@@ -303,7 +426,9 @@ class RegionExecutionManagerSpec
     Time.withCurrentTimeFrozen { _ =>
       val fixture = createSingleRegionFixture(
         endWorkerResponse = _ => Some(transientEndWorkerFailure),
-        killRetryTimer = timer
+        killRetryTimer = timer,
+        // Disable the termination timeout for this frozen-time retry test.
+        terminationTimeoutMs = Long.MaxValue
       )
 
       launchRegion(fixture.manager)
@@ -327,7 +452,9 @@ class RegionExecutionManagerSpec
         endWorkerResponse = _ =>
           if (attempts.incrementAndGet() == 1) Some(transientEndWorkerFailure)
           else Some(EmptyReturn()),
-        killRetryTimer = timer
+        killRetryTimer = timer,
+        // Disable the termination timeout for this frozen-time retry test.
+        terminationTimeoutMs = Long.MaxValue
       )
 
       launchRegion(fixture.manager)
@@ -404,7 +531,7 @@ class RegionExecutionManagerSpec
     workflowExecution.initRegionExecution(region)
 
     val rpcProbe = new CoordinatorRpcProbe(_ => None)
-    val coordinator = createCoordinatorHarness()
+    val coordinator = createCoordinatorHarness(rpcProbe)
     registerLiveWorker(coordinator.actorRefService, workerId)
 
     new RegionExecutionManager(
@@ -433,8 +560,10 @@ class RegionExecutionManagerSpec
       maxTerminationAttempts: Int = 
RegionExecutionManager.DefaultMaxTerminationAttempts,
       killRetryBaseBackoffMs: Long = 
RegionExecutionManager.DefaultKillRetryBaseBackoffMs,
       killRetryTimer: Timer = new JavaTimer(true),
+      terminationTimeoutMs: Long = 
RegionExecutionManager.DefaultTerminationTimeoutMs,
       physicalOp: PhysicalOp = createSourceOp("test-op"),
-      ensureMounted: Set[String] => Unit = _ => ()
+      ensureMounted: Set[String] => Unit = _ => (),
+      beforeCleanup: () => Unit = () => ()
   ): SingleRegionFixture = {
     val workerId = createWorkerId(physicalOp)
     val region = createSingleWorkerRegion(1, physicalOp, workerId)
@@ -444,7 +573,7 @@ class RegionExecutionManagerSpec
     workflowExecution.initRegionExecution(region)
 
     val rpcProbe = new CoordinatorRpcProbe(endWorkerResponse)
-    val coordinator = createCoordinatorHarness()
+    val coordinator = createCoordinatorHarness(rpcProbe, beforeCleanup)
     registerLiveWorker(coordinator.actorRefService, workerId)
 
     // Seed stale control channels to verify that successful termination 
removes them.
@@ -464,6 +593,7 @@ class RegionExecutionManagerSpec
       maxTerminationAttempts,
       killRetryBaseBackoffMs,
       killRetryTimer,
+      terminationTimeoutMs = terminationTimeoutMs,
       ensureMounted = ensureMounted
     )
 
@@ -500,7 +630,7 @@ class RegionExecutionManagerSpec
     workflowExecution.initRegionExecution(region)
 
     val rpcProbe = new CoordinatorRpcProbe(_ => 
Some(transientEndWorkerFailure))
-    val coordinator = createCoordinatorHarness()
+    val coordinator = createCoordinatorHarness(rpcProbe)
     workerIds.foreach(registerLiveWorker(coordinator.actorRefService, _))
 
     val manager = new RegionExecutionManager(
diff --git 
a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionExecutionManagerTestSupport.scala
 
b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionExecutionManagerTestSupport.scala
index 7eb9a480b8..104a8bac1d 100644
--- 
a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionExecutionManagerTestSupport.scala
+++ 
b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionExecutionManagerTestSupport.scala
@@ -19,9 +19,9 @@
 
 package org.apache.texera.amber.engine.architecture.scheduling
 
-import com.twitter.util.{Await, Duration, Future}
+import com.twitter.util.{Await, Duration, Future, Promise}
 import org.apache.pekko.actor.{Actor, ActorRef, Props}
-import org.apache.pekko.testkit.{TestActorRef, TestKit}
+import org.apache.pekko.testkit.TestKit
 import org.apache.texera.amber.core.executor.OpExecWithClassName
 import org.apache.texera.amber.core.virtualidentity.{
   ActorVirtualIdentity,
@@ -39,6 +39,7 @@ import org.apache.texera.amber.engine.architecture.common.{
   PekkoActorService,
   WorkflowActor
 }
+import org.apache.texera.amber.engine.architecture.coordinator.Coordinator
 import 
org.apache.texera.amber.engine.architecture.coordinator.execution.WorkflowExecution
 import org.apache.texera.amber.engine.architecture.messaginglayer.{
   NetworkInputGateway,
@@ -58,6 +59,7 @@ import 
org.apache.texera.amber.engine.common.rpc.AsyncRPCClient
 import org.apache.texera.amber.engine.common.virtualidentity.util.COORDINATOR
 import org.apache.texera.amber.util.VirtualIdentityUtils
 
+import java.util.concurrent.CountDownLatch
 import scala.collection.mutable
 
 object RegionExecutionManagerTestSupport {
@@ -161,7 +163,29 @@ object RegionExecutionManagerTestSupport {
     override def receive: Receive = { case _ => () }
   }
 
-  class CoordinatorHarness extends WorkflowActor(None, COORDINATOR) {
+  object BlockingActor {
+    case object Block
+  }
+
+  /**
+    * Stays alive but jams its own mailbox on `Block`, so a `PoisonPill` sent 
afterward (e.g. by
+    * `gracefulStop`) queues behind it and is never processed until `gate` 
counts down. Lets a test
+    * force `gracefulStop` itself to time out deterministically, rather than 
racing a real actor
+    * stop against a short test timeout.
+    */
+  class BlockingActor(gate: CountDownLatch) extends Actor {
+    override def receive: Receive = {
+      case BlockingActor.Block => gate.await()
+    }
+  }
+
+  class CoordinatorHarness(
+      rpcProbe: CoordinatorRpcProbe,
+      beforeCleanup: () => Unit,
+      servicesPromise: Promise[(PekkoActorService, 
PekkoActorRefMappingService)]
+  ) extends WorkflowActor(None, COORDINATOR) {
+    servicesPromise.setValue((actorService, actorRefMappingService))
+
     override def handleInputMessage(id: Long, workflowMsg: 
WorkflowFIFOMessage): Unit = ()
 
     override def getQueuedCredit(channelId: ChannelIdentity): Long = 0
@@ -171,6 +195,21 @@ object RegionExecutionManagerTestSupport {
     override def initState(): Unit = ()
 
     override def loadFromCheckpoint(chkpt: CheckpointState): Unit = ()
+
+    override def receive: Receive =
+      handleCleanupWorkerChannels orElse super.receive
+
+    private def handleCleanupWorkerChannels: Receive = {
+      case Coordinator.CleanupWorkerChannels(workerIds, forceTerminateWorkers, 
completionPromise) =>
+        beforeCleanup()
+        forceTerminateWorkers()
+        Coordinator.cleanupWorkerChannels(
+          workerIds,
+          rpcProbe.asyncRPCClient,
+          actorRefMappingService
+        )
+        completionPromise.setDone()
+    }
   }
 
   def createSourceOp(logicalOpId: String): PhysicalOp =
@@ -249,13 +288,18 @@ object RegionExecutionManagerTestSupport {
 trait RegionExecutionManagerTestSupport { self: TestKit =>
   import RegionExecutionManagerTestSupport._
 
-  protected def createCoordinatorHarness(): CoordinatorHarnessFixture = {
-    val coordinatorRef = TestActorRef(new CoordinatorHarness)
-    coordinatorRef.underlyingActor.actorService.getAvailableNodeAddressesFunc 
= () =>
-      Array(coordinatorRef.path.address)
+  protected def createCoordinatorHarness(
+      rpcProbe: CoordinatorRpcProbe = new CoordinatorRpcProbe(_ => None),
+      beforeCleanup: () => Unit = () => ()
+  ): CoordinatorHarnessFixture = {
+    val servicesPromise = Promise[(PekkoActorService, 
PekkoActorRefMappingService)]()
+    val coordinatorRef =
+      system.actorOf(Props(new CoordinatorHarness(rpcProbe, beforeCleanup, 
servicesPromise)))
+    val (harnessActorService, harnessActorRefService) = 
Await.result(servicesPromise, testTimeout)
+    harnessActorService.getAvailableNodeAddressesFunc = () => 
Array(coordinatorRef.path.address)
     CoordinatorHarnessFixture(
-      actorService = coordinatorRef.underlyingActor.actorService,
-      actorRefService = coordinatorRef.underlyingActor.actorRefMappingService
+      actorService = harnessActorService,
+      actorRefService = harnessActorRefService
     )
   }
 
diff --git 
a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/WorkflowExecutionManagerSpec.scala
 
b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/WorkflowExecutionManagerSpec.scala
index 141de24460..f6c4487af0 100644
--- 
a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/WorkflowExecutionManagerSpec.scala
+++ 
b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/WorkflowExecutionManagerSpec.scala
@@ -132,7 +132,7 @@ class WorkflowExecutionManagerSpec
     val rpcProbe = new CoordinatorRpcProbe(
       endWorkerResponse = call => if (call.receiver == firstWorkerId) None 
else Some(EmptyReturn())
     )
-    val coordinator = createCoordinatorHarness()
+    val coordinator = createCoordinatorHarness(rpcProbe)
     registerLiveWorker(coordinator.actorRefService, firstWorkerId)
     registerLiveWorker(coordinator.actorRefService, secondWorkerId)
 

Reply via email to