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

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


The following commit(s) were added to refs/heads/main by this push:
     new 82224eaca8 refactor(amber): simplify control, scheduling, and stats 
(#9508)
82224eaca8 is described below

commit 82224eaca8d2e10a9b077cb1bf406601fdc6ff18
Author: Xinyuan Lin <[email protected]>
AuthorDate: Tue Nov 17 08:19:20 2026 +0000

    refactor(amber): simplify control, scheduling, and stats (#9508)
    
    ### What changes were proposed in this PR?
    Remove redundant passes, duplicate channel-resolution code, and repeated
    allocations across Amber's coordinator, scheduler, replay/checkpoint,
    and web-service paths without changing external behavior:
    
    - **Coordinator control & reconfiguration:** Share one control-channel
    scope resolver and source-ECM dispatcher between embedded control
    propagation and workflow reconfiguration, take in-scope data channels
    from running links whose two operators are in scope instead of parsing
    worker names, pass operator sets directly from connected components in
    FRIES instead of regrouping the sub-plan, and drop unused intermediate
    collections and request parameters.
    - **Scheduling & worker deployment:** Use O(1) frontier membership
    tracking (`inQueue`), DAG `inDegreeOf`, and shared frontier queuing in
    schedule generation; avoid redundant operator/port traversals in region
    source/starter computation; hoist invariant deployment and
    execution-scoped URI lookups outside per-worker loops.
    - **Log replay & checkpointing:** Reuse the termination sentinel and
    drain list slice directly in `AsyncReplayLogWriter`, replace the
    non-local-return closure in `ReplayLogGenerator` with an explicit loop,
    combine map lookups in worker/checkpoint state paths, skip allocating an
    empty `CheckpointState` on estimate-only global checkpoints, and reuse
    `Future.join` where return values are discarded.
    - **Console & runtime statistics:** Avoid extra `OperatorConsole` / map
    / timestamp / schema allocations, share one single-pass port-metric
    aggregation helper across live websocket updates and Iceberg
    persistence, and simplify terminal-state and stats-diff checks.
    
    ### Any related issues, documentation, discussions?
    Closes #9507.
    
    ### How was this PR tested?
    Added characterization tests upfront covering
    `RetrieveWorkflowStateHandler` reply mapping and running-region source
    selection, `Region` internal/external source links and materialized
    input starters, `ScheduleGenerator` DAG topological batching,
    `FriesReconfigurationAlgorithm` empty/multi-op/mixed-component cases,
    `EmbeddedControlMessageHandler` multi-worker source injection, and
    `ExecutionConsoleService` / `ExecutionStatsService` expression diffs and
    multi-port aggregation.
    
    Verified with `STORAGE_ICEBERG_CATALOG_TYPE=hadoop` and
    `UDF_PYTHON_PATH` set:
    
    ```bash
    sbt \
      "WorkflowExecutionService/scalafix --check" \
      "WorkflowExecutionService/Test/scalafix --check" \
      "WorkflowExecutionService/scalafmtCheck" \
      "WorkflowExecutionService/Test/scalafmtCheck" \
      "WorkflowExecutionService/testOnly *EmbeddedControlMessageHandlerSpec 
*RetrieveWorkflowStateHandlerSpec *TakeGlobalCheckpointHandlerSpec 
*FinalizeCheckpointHandlerSpec *PrepareCheckpointHandlerSpec 
*AsyncReplayLogWriterSpec *ReplayLogGeneratorSpec *ReplayLogManagerImplSpec 
*EmptyReplayLogManagerImplSpec *CheckpointSpec *CheckpointSubsystemSpec 
*FriesReconfigurationAlgorithmSpec *RegionSpec *RegionPlanSpec *ScheduleSpec 
*SchedulingConfigsSpec *SchedulingUtilsSpec *CostBasedScheduleGe [...]
    ```
    
    Observed result: 34 suites completed, 333 tests succeeded (0 failed, 0
    canceled/skipped).
    
    After review, in-scope data channels come from each running link whose
    two operators are in scope, `Region` gains no member or
    `@SerialVersionUID`, and FRIES maps each connected component once with
    `getSourceOperatorIds`. On the final head, the same command, run on JDK
    17 with freshly generated jOOQ classes, again completed 34 suites with
    all 333 tests passing.
    
    ### Was this PR authored or co-authored using generative AI tooling?
    Generated-by: Antigravity IDE (Gemini 3.8 Flash), Claude Code (Claude
    Opus 5.5)
---
 .../architecture/common/ExecutorDeployment.scala   | 35 ++++----
 .../CoordinatorAsyncRPCHandlerInitializer.scala    | 62 +++++++++++++-
 .../EmbeddedControlMessageHandler.scala            | 56 +++----------
 .../promisehandlers/ReconfigurationHandler.scala   | 67 +++++----------
 .../RetrieveWorkflowStateHandler.scala             | 15 ++--
 .../TakeGlobalCheckpointHandler.scala              | 34 ++++----
 .../logreplay/AsyncReplayLogWriter.scala           | 36 ++++----
 .../logreplay/ReplayLogGenerator.scala             | 26 +++---
 .../scheduling/CostBasedScheduleGenerator.scala    | 88 +++++++++-----------
 .../engine/architecture/scheduling/Region.scala    | 24 ++----
 .../scheduling/ScheduleGenerator.scala             | 12 ++-
 .../scheduling/config/WorkerConfig.scala           |  5 +-
 .../FinalizeCheckpointHandler.scala                | 71 ++++++++--------
 .../promisehandlers/PrepareCheckpointHandler.scala | 16 ++--
 .../amber/engine/common/CheckpointState.scala      |  9 +-
 .../common/FriesReconfigurationAlgorithm.scala     | 80 ++++++++----------
 .../web/service/ExecutionConsoleService.scala      | 20 +++--
 .../texera/web/service/ExecutionStatsService.scala | 88 ++++++++++++--------
 .../EmbeddedControlMessageHandlerSpec.scala        | 28 +++++++
 .../RetrieveWorkflowStateHandlerSpec.scala         | 95 +++++++++++++++++++++-
 .../architecture/scheduling/RegionSpec.scala       | 52 ++++++++++++
 .../architecture/scheduling/ScheduleSpec.scala     | 47 ++++++++++-
 .../common/FriesReconfigurationAlgorithmSpec.scala | 45 ++++++++++
 .../web/service/ExecutionConsoleServiceSpec.scala  | 54 +++++++++++-
 .../web/service/ExecutionStatsServiceSpec.scala    | 52 ++++++++++++
 25 files changed, 734 insertions(+), 383 deletions(-)

diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/common/ExecutorDeployment.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/common/ExecutorDeployment.scala
index 04cd7ff0dd..73e95d5ecb 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/common/ExecutorDeployment.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/common/ExecutorDeployment.scala
@@ -49,6 +49,19 @@ object ExecutorDeployment {
       coordinatorActorService.getClusterNodeAddresses,
       coordinatorActorService.self.path.address
     )
+    lazy val isPythonBased = op.isPythonBased
+    lazy val replayInit = WorkerReplayInitialization(stateRestoreConfig, 
replayLoggingConfig)
+    lazy val preferredAddressFor: Int => Address =
+      op.locationPreference.getOrElse(RoundRobinPreference) match {
+        case PreferCoordinator =>
+          _ => addressInfo.coordinatorAddress
+        case RoundRobinPreference =>
+          assert(
+            addressInfo.allAddresses.nonEmpty,
+            "Execution failed to start, no available computation nodes"
+          )
+          workerIndex => addressInfo.allAddresses(workerIndex % 
addressInfo.allAddresses.length)
+      }
 
     operatorConfig.workerConfigs.foreach(workerConfig => {
       val workerId = workerConfig.workerId
@@ -59,28 +72,12 @@ object ExecutorDeployment {
             s"Expected worker actor id when deploying executor, got: 
${workerId.name}"
           )
         )
-      val locationPreference = 
op.locationPreference.getOrElse(RoundRobinPreference)
-      val preferredAddress: Address = locationPreference match {
-        case PreferCoordinator =>
-          addressInfo.coordinatorAddress
-        case RoundRobinPreference =>
-          assert(
-            addressInfo.allAddresses.nonEmpty,
-            "Execution failed to start, no available computation nodes"
-          )
-          addressInfo.allAddresses(workerIndex % 
addressInfo.allAddresses.length)
-      }
+      val preferredAddress = preferredAddressFor(workerIndex)
 
-      val workflowWorker = if (op.isPythonBased) {
+      val workflowWorker = if (isPythonBased) {
         PythonWorkflowWorker.props(workerConfig)
       } else {
-        WorkflowWorker.props(
-          workerConfig,
-          WorkerReplayInitialization(
-            stateRestoreConfig,
-            replayLoggingConfig
-          )
-        )
+        WorkflowWorker.props(workerConfig, replayInit)
       }
       // Note: At this point, we don't know if the actor is fully initialized.
       // Thus, the ActorRef returned from `coordinatorActorService.actorOf` is 
ignored.
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/CoordinatorAsyncRPCHandlerInitializer.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/CoordinatorAsyncRPCHandlerInitializer.scala
index 131d0b7a82..c9b7efc6e6 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/CoordinatorAsyncRPCHandlerInitializer.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/CoordinatorAsyncRPCHandlerInitializer.scala
@@ -20,12 +20,22 @@
 package org.apache.texera.amber.engine.architecture.coordinator
 
 import com.twitter.util.Future
-import org.apache.texera.amber.core.virtualidentity.ActorVirtualIdentity
+import org.apache.texera.amber.core.virtualidentity.{
+  ActorVirtualIdentity,
+  ChannelIdentity,
+  EmbeddedControlMessageIdentity,
+  PhysicalOpIdentity
+}
 import 
org.apache.texera.amber.engine.architecture.coordinator.promisehandlers._
-import 
org.apache.texera.amber.engine.architecture.rpc.controlcommands.AsyncRPCContext
+import org.apache.texera.amber.engine.architecture.rpc.controlcommands.{
+  AsyncRPCContext,
+  ControlInvocation,
+  EmbeddedControlMessageType
+}
 import 
org.apache.texera.amber.engine.architecture.rpc.coordinatorservice.CoordinatorServiceFs2Grpc
 import org.apache.texera.amber.engine.common.AmberLogging
 import org.apache.texera.amber.engine.common.rpc.AsyncRPCHandlerInitializer
+import org.apache.texera.amber.engine.common.virtualidentity.util.COORDINATOR
 
 class CoordinatorAsyncRPCHandlerInitializer(
     val cp: CoordinatorProcessor
@@ -51,4 +61,52 @@ class CoordinatorAsyncRPCHandlerInitializer(
     with RetrieveWorkflowStateHandler
     with ReconfigurationHandler {
   val actorId: ActorVirtualIdentity = cp.actorId
+
+  /**
+    * Resolves in-scope data channels and control channels across running 
regions, then
+    * injects an embedded control message to each source operator's workers.
+    */
+  private[coordinator] def sendEmbeddedControlMessageToSources(
+      ecmId: EmbeddedControlMessageIdentity,
+      ecmType: EmbeddedControlMessageType,
+      scopeOps: Set[PhysicalOpIdentity],
+      sourceOps: Iterable[PhysicalOpIdentity],
+      cmdMapping: Map[String, ControlInvocation]
+  ): Unit = {
+    if (sourceOps.isEmpty) {
+      return
+    }
+    val sourceWorkers = sourceOps.iterator
+      .flatMap(source => 
cp.workflowExecution.getLatestOperatorExecution(source).getWorkerIds)
+      .toList
+    if (sourceWorkers.isEmpty) {
+      return
+    }
+
+    val channelScope = cp.workflowExecution.getRunningRegionExecutions.iterator
+      .flatMap(_.getAllLinkExecutions.iterator)
+      .collect {
+        case (link, linkExecution)
+            if scopeOps.contains(link.fromOpId) && 
scopeOps.contains(link.toOpId) =>
+          linkExecution
+      }
+      .flatMap(_.getAllChannelExecutions.iterator.map(_._1))
+    val controlChannels = sourceWorkers.iterator.flatMap { worker =>
+      Seq(
+        ChannelIdentity(COORDINATOR, worker, isControl = true),
+        ChannelIdentity(worker, COORDINATOR, isControl = true)
+      )
+    }
+    val finalScope = (channelScope ++ controlChannels).toSet
+
+    sourceWorkers.foreach { worker =>
+      sendECM(
+        ecmId,
+        ecmType,
+        finalScope,
+        cmdMapping,
+        ChannelIdentity(actorId, worker, isControl = true)
+      )
+    }
+  }
 }
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/EmbeddedControlMessageHandler.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/EmbeddedControlMessageHandler.scala
index 9e696fb928..318ee2825c 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/EmbeddedControlMessageHandler.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/EmbeddedControlMessageHandler.scala
@@ -20,7 +20,7 @@
 package org.apache.texera.amber.engine.architecture.coordinator.promisehandlers
 
 import com.twitter.util.Future
-import org.apache.texera.amber.core.virtualidentity.{ActorVirtualIdentity, 
ChannelIdentity}
+import org.apache.texera.amber.core.virtualidentity.ActorVirtualIdentity
 import 
org.apache.texera.amber.engine.architecture.coordinator.CoordinatorAsyncRPCHandlerInitializer
 import org.apache.texera.amber.engine.architecture.rpc.controlcommands.{
   AsyncRPCContext,
@@ -31,8 +31,6 @@ import 
org.apache.texera.amber.engine.architecture.rpc.controlreturns.{
   ControlReturn,
   PropagateEmbeddedControlMessageResponse
 }
-import org.apache.texera.amber.engine.common.virtualidentity.util.COORDINATOR
-import org.apache.texera.amber.util.VirtualIdentityUtils
 
 trait EmbeddedControlMessageHandler {
   this: CoordinatorAsyncRPCHandlerInitializer =>
@@ -50,54 +48,26 @@ trait EmbeddedControlMessageHandler {
         })
     }
     // step 2: packing all control commands into one compound command.
-    val cmdMapping: Map[String, ControlInvocation] = inputSet.map {
+    val cmdMapping: Map[String, ControlInvocation] = inputSet.iterator.map {
       case (workerId, (control, _)) => (workerId.name, control)
     }.toMap
-    val futures: Set[Future[(ActorVirtualIdentity, ControlReturn)]] = 
inputSet.map {
-      case (workerId, (_, future)) => future.map(ret => (workerId, 
ret.asInstanceOf[ControlReturn]))
+    val futures: Set[Future[(ActorVirtualIdentity, ControlReturn)]] = 
inputSet.iterator.map {
+      case (workerId, (_, future)) => future.map(ret => (workerId, ret))
     }.toSet
 
-    // step 3: convert scope DAG to channels.
-    val channelScope = cp.workflowExecution.getRunningRegionExecutions
-      .flatMap(regionExecution =>
-        regionExecution.getAllLinkExecutions
-          .map(_._2)
-          .flatMap(linkExecution => 
linkExecution.getAllChannelExecutions.map(_._1))
-      )
-      .filter(channelId => {
-        msg.scope
-          
.contains(VirtualIdentityUtils.getPhysicalOpId(channelId.fromWorkerId)) &&
-          msg.scope
-            
.contains(VirtualIdentityUtils.getPhysicalOpId(channelId.toWorkerId))
-      })
-    val controlChannels = msg.sourceOpToStartProp.flatMap { source =>
-      
cp.workflowExecution.getLatestOperatorExecution(source).getWorkerIds.flatMap { 
worker =>
-        Seq(
-          ChannelIdentity(COORDINATOR, worker, isControl = true),
-          ChannelIdentity(worker, COORDINATOR, isControl = true)
-        )
-      }
-    }
-
-    val finalScope = channelScope ++ controlChannels
-
-    // step 4: start prop, send ECM through control channel with the compound 
command from sources.
-    msg.sourceOpToStartProp.foreach { source =>
-      
cp.workflowExecution.getLatestOperatorExecution(source).getWorkerIds.foreach { 
worker =>
-        sendECM(
-          msg.id,
-          msg.ecmType,
-          finalScope.toSet,
-          cmdMapping,
-          ChannelIdentity(actorId, worker, isControl = true)
-        )
-      }
-    }
+    // step 3 & 4: resolve scope channels and send ECM through source control 
channels.
+    sendEmbeddedControlMessageToSources(
+      msg.id,
+      msg.ecmType,
+      msg.scope.toSet,
+      msg.sourceOpToStartProp,
+      cmdMapping
+    )
 
     // step 5: wait for the ECM propagation.
     Future.collect(futures.toList).map { ret =>
       cp.logManager.markAsReplayDestination(msg.id)
-      PropagateEmbeddedControlMessageResponse(ret.map(x => (x._1.name, 
x._2)).toMap)
+      PropagateEmbeddedControlMessageResponse(ret.iterator.map(x => 
(x._1.name, x._2)).toMap)
     }
   }
 }
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/ReconfigurationHandler.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/ReconfigurationHandler.scala
index cf6d22e29a..6c2062c16d 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/ReconfigurationHandler.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/ReconfigurationHandler.scala
@@ -22,7 +22,6 @@ package 
org.apache.texera.amber.engine.architecture.coordinator.promisehandlers
 import com.twitter.util.Future
 import org.apache.texera.amber.core.virtualidentity.{
   ActorVirtualIdentity,
-  ChannelIdentity,
   EmbeddedControlMessageIdentity
 }
 import org.apache.texera.amber.engine.architecture.coordinator.{
@@ -35,11 +34,9 @@ import 
org.apache.texera.amber.engine.architecture.rpc.controlcommands.{
   ControlInvocation,
   WorkflowReconfigureRequest
 }
-import 
org.apache.texera.amber.engine.architecture.rpc.controlreturns.{ControlReturn, 
EmptyReturn}
-import org.apache.texera.amber.engine.common.FriesReconfigurationAlgorithm
-import org.apache.texera.amber.engine.common.virtualidentity.util.COORDINATOR
-import org.apache.texera.amber.util.VirtualIdentityUtils
+import 
org.apache.texera.amber.engine.architecture.rpc.controlreturns.EmptyReturn
 import 
org.apache.texera.amber.engine.architecture.rpc.workerservice.WorkerServiceGrpc.METHOD_UPDATE_EXECUTOR
+import org.apache.texera.amber.engine.common.FriesReconfigurationAlgorithm
 
 import scala.collection.mutable
 
@@ -77,57 +74,31 @@ trait ReconfigurationHandler {
           )
         }
       } else {
-        val channelScope = cp.workflowExecution.getRunningRegionExecutions
-          .flatMap(regionExecution =>
-            regionExecution.getAllLinkExecutions
-              .map(_._2)
-              .flatMap(linkExecution => 
linkExecution.getAllChannelExecutions.map(_._1))
-          )
-          .filter(channelId => {
-            friesComponent.scope
-              
.contains(VirtualIdentityUtils.getPhysicalOpId(channelId.fromWorkerId)) &&
-              friesComponent.scope
-                
.contains(VirtualIdentityUtils.getPhysicalOpId(channelId.toWorkerId))
-          })
-        val controlChannels = friesComponent.sources.flatMap { source =>
-          
cp.workflowExecution.getLatestOperatorExecution(source).getWorkerIds.flatMap { 
worker =>
-            Seq(
-              ChannelIdentity(COORDINATOR, worker, isControl = true),
-              ChannelIdentity(worker, COORDINATOR, isControl = true)
-            )
+        val workerCommands = friesComponent.reconfigurations.flatMap { 
updateReq =>
+          val workers =
+            
cp.workflowExecution.getLatestOperatorExecution(updateReq.targetOpId).getWorkerIds
+          workers.map { worker =>
+            val (invocation, future) =
+              createInvocation(METHOD_UPDATE_EXECUTOR.getBareMethodName, 
updateReq, worker)
+            (worker, invocation, future)
           }
         }
-        val finalScope = channelScope ++ controlChannels
-        val workerCommands: Seq[(ActorVirtualIdentity, ControlInvocation, 
Future[ControlReturn])] =
-          friesComponent.reconfigurations.flatMap { updateReq =>
-            val workers =
-              
cp.workflowExecution.getLatestOperatorExecution(updateReq.targetOpId).getWorkerIds
-            workers.map { worker =>
-              val (invocation, future) =
-                createInvocation(METHOD_UPDATE_EXECUTOR.getBareMethodName, 
updateReq, worker)
-              (worker, invocation, future)
-            }
-          }.toSeq
-        val cmdMapping: Map[String, ControlInvocation] = workerCommands.map {
+        val cmdMapping: Map[String, ControlInvocation] = 
workerCommands.iterator.map {
           case (worker, invocation, _) => worker.name -> invocation
         }.toMap
-        futures ++= workerCommands.map {
+        futures ++= workerCommands.iterator.map {
           case (worker, _, future) => notifyOnComplete(future, worker)
         }
-        friesComponent.sources.foreach { source =>
-          
cp.workflowExecution.getLatestOperatorExecution(source).getWorkerIds.foreach { 
worker =>
-            sendECM(
-              EmbeddedControlMessageIdentity(msg.reconfigurationId),
-              ALL_ALIGNMENT,
-              finalScope.toSet,
-              cmdMapping,
-              ChannelIdentity(actorId, worker, isControl = true)
-            )
-          }
-        }
+        sendEmbeddedControlMessageToSources(
+          EmbeddedControlMessageIdentity(msg.reconfigurationId),
+          ALL_ALIGNMENT,
+          friesComponent.scope,
+          friesComponent.sources,
+          cmdMapping
+        )
       }
     }
-    Future.collect(futures.toList).map { _ =>
+    Future.join(futures.toList).map { _ =>
       EmptyReturn()
     }
   }
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/RetrieveWorkflowStateHandler.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/RetrieveWorkflowStateHandler.scala
index 26c51bbd5d..ca511a22c0 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/RetrieveWorkflowStateHandler.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/RetrieveWorkflowStateHandler.scala
@@ -46,9 +46,9 @@ trait RetrieveWorkflowStateHandler {
   ): Future[RetrieveWorkflowStateResponse] = {
     val targetOps = cp.workflowScheduler.physicalPlan.operators.map(_.id).toSeq
     val msg = PropagateEmbeddedControlMessageRequest(
-      cp.workflowExecution.getRunningRegionExecutions
-        .flatMap(_.getAllOperatorExecutions.map(_._1))
-        .toSeq,
+      cp.workflowExecution.getRunningRegionExecutions.iterator
+        .flatMap(_.getAllOperatorExecutions.iterator.map(_._1))
+        .toList,
       EmbeddedControlMessageIdentity("RetrieveWorkflowState_" + 
Instant.now().toString),
       NO_ALIGNMENT,
       targetOps,
@@ -63,13 +63,8 @@ trait RetrieveWorkflowStateHandler {
       )
       .map { ret =>
         RetrieveWorkflowStateResponse(ret.returns.map {
-          case (actorId, value) =>
-            val finalret = value match {
-              case s: StringResponse => s.value
-              case other =>
-                ""
-            }
-            (actorId, finalret)
+          case (actorId, response: StringResponse) => actorId -> response.value
+          case (actorId, _)                        => actorId -> ""
         })
       }
   }
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/TakeGlobalCheckpointHandler.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/TakeGlobalCheckpointHandler.scala
index d80b55145d..57fbfc7412 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/TakeGlobalCheckpointHandler.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/TakeGlobalCheckpointHandler.scala
@@ -39,27 +39,28 @@ trait TakeGlobalCheckpointHandler {
       msg: TakeGlobalCheckpointRequest,
       ctx: AsyncRPCContext
   ): Future[TakeGlobalCheckpointResponse] = {
-    var estimationOnly = msg.estimationOnly
+    val estimationRequested = msg.estimationOnly
     val destinationURI = new URI(msg.destination)
-    @transient val storage =
+    val storage =
       SequentialRecordStorage.getStorage[CheckpointState](Some(destinationURI))
-    if (storage.containsFolder(msg.checkpointId.toString)) {
+    val checkpointExists = storage.containsFolder(msg.checkpointId.toString)
+    if (checkpointExists) {
       logger.info("skip checkpoint since its already taken")
-      estimationOnly = true
     }
+    val estimationOnly = estimationRequested || checkpointExists
     val uri = destinationURI.resolve(msg.checkpointId.toString)
     var totalSize = 0L
-    val physicalOpIdsToTakeCheckpoint = 
cp.workflowScheduler.physicalPlan.operators.map(_.id)
+    val physicalOpIdsToTakeCheckpoint = 
cp.workflowScheduler.physicalPlan.operators.map(_.id).toSeq
     coordinatorInterface
       .propagateEmbeddedControlMessage(
         PropagateEmbeddedControlMessageRequest(
-          cp.workflowExecution.getAllRegionExecutions
-            .flatMap(_.getAllOperatorExecutions.map(_._1))
-            .toSeq,
+          cp.workflowExecution.getAllRegionExecutions.iterator
+            .flatMap(_.getAllOperatorExecutions.iterator.map(_._1))
+            .toList,
           msg.checkpointId,
           NO_ALIGNMENT,
-          cp.workflowScheduler.physicalPlan.operators.map(_.id).toSeq,
-          physicalOpIdsToTakeCheckpoint.toSeq,
+          physicalOpIdsToTakeCheckpoint,
+          physicalOpIdsToTakeCheckpoint,
           PrepareCheckpointRequest(msg.checkpointId, estimationOnly),
           METHOD_PREPARE_CHECKPOINT.getBareMethodName
         ),
@@ -67,7 +68,7 @@ trait TakeGlobalCheckpointHandler {
       )
       .flatMap { ret =>
         Future
-          .collect(ret.returns.map {
+          .join(ret.returns.iterator.map {
             case (workerId, _) =>
               val destActor = ActorVirtualIdentity(workerId)
               workerInterface
@@ -81,11 +82,13 @@ trait TakeGlobalCheckpointHandler {
                 .onFailure { err =>
                   throw err // TODO: handle failures.
                 }
-          }.toSeq)
+          }.toList)
           .map { _ =>
             logger.info("Start to take checkpoint")
-            val chkpt = new CheckpointState()
-            if (!estimationOnly) {
+            val coordinatorCheckpoint = if (estimationOnly) {
+              None
+            } else {
+              val chkpt = new CheckpointState()
               // serialize CP state
               chkpt.save(SerializedState.CP_STATE_KEY, this.cp)
               logger.info(
@@ -101,8 +104,9 @@ trait TakeGlobalCheckpointHandler {
               writer.writeRecord(chkpt)
               writer.flush()
               writer.close()
+              Some(chkpt)
             }
-            totalSize += chkpt.size()
+            totalSize += coordinatorCheckpoint.fold(0L)(_.size())
             logger.info(s"global checkpoint finalized, total size = 
$totalSize")
             TakeGlobalCheckpointResponse(totalSize)
           }
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/logreplay/AsyncReplayLogWriter.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/logreplay/AsyncReplayLogWriter.scala
index 668d5345d3..914f3d109f 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/logreplay/AsyncReplayLogWriter.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/logreplay/AsyncReplayLogWriter.scala
@@ -27,7 +27,6 @@ import 
org.apache.texera.amber.engine.common.storage.SequentialRecordStorage.Seq
 
 import java.util
 import java.util.concurrent.CompletableFuture
-import scala.collection.mutable.ListBuffer
 import scala.jdk.CollectionConverters.ListHasAsScala
 
 class AsyncReplayLogWriter(
@@ -42,6 +41,7 @@ class AsyncReplayLogWriter(
     Queues.newLinkedBlockingQueue[
       Either[ReplayLogRecord, Either[MainThreadDelegateMessage, 
WorkflowFIFOMessage]]
     ]()
+  private val terminationEntry = Left(TerminateSignal)
   private var stopped = false
   private val logInterval =
     ApplicationConfig.faultToleranceLogFlushIntervalInMs
@@ -61,7 +61,7 @@ class AsyncReplayLogWriter(
 
   def terminate(): Unit = {
     stopped = true
-    writerQueue.put(Left(TerminateSignal))
+    writerQueue.put(terminationEntry)
     gracefullyStopped.get()
   }
 
@@ -78,31 +78,23 @@ class AsyncReplayLogWriter(
   }
 
   private def drainWriterQueueAndProcess(): Boolean = {
-    var stop = false
     if (writerQueue.drainTo(drained) == 0) {
       drained.add(writerQueue.take())
     }
-    var drainedScala = drained.asScala
-    if (drainedScala.last == Left(TerminateSignal)) {
-      drainedScala = drainedScala.dropRight(1)
-      stop = true
-    }
+    val lastIndex = drained.size() - 1
+    val stop = drained.get(lastIndex) == terminationEntry
+    // Keep the drained entries intact until all writes and callbacks succeed.
+    val batch = (if (stop) drained.subList(0, lastIndex) else drained).asScala
 
-    val (replayLogRecords, workflowFIFOMessages) =
-      drainedScala.foldLeft(
-        (
-          ListBuffer[ReplayLogRecord](),
-          ListBuffer[Either[MainThreadDelegateMessage, WorkflowFIFOMessage]]()
-        )
-      ) {
-        case ((accLogs, accMsgs), Left(logRecord))    => (accLogs += 
logRecord, accMsgs)
-        case ((accLogs, accMsgs), Right(fifoMessage)) => (accLogs, accMsgs += 
fifoMessage)
-      }
-    // write logs first
-    replayLogRecords.foreach(replayLogRecord => 
writer.writeRecord(replayLogRecord))
+    batch.foreach {
+      case Left(record) => writer.writeRecord(record)
+      case Right(_)     => ()
+    }
     writer.flush()
-    // send messages after logs are written
-    workflowFIFOMessages.foreach(workflowFIFOMessage => 
handler(workflowFIFOMessage))
+    batch.foreach {
+      case Left(_)        => ()
+      case Right(message) => handler(message)
+    }
 
     drained.clear()
     stop
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/logreplay/ReplayLogGenerator.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/logreplay/ReplayLogGenerator.scala
index d159263db3..834a676f9a 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/logreplay/ReplayLogGenerator.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/logreplay/ReplayLogGenerator.scala
@@ -34,18 +34,20 @@ object ReplayLogGenerator {
     val logs = logStorage.getReader(logFileName).mkRecordIterator()
     val steps = mutable.Queue[ProcessingStep]()
     val messages = mutable.Queue[WorkflowFIFOMessage]()
-    logs.foreach {
-      case s: ProcessingStep =>
-        steps.enqueue(s)
-      case MessageContent(message) =>
-        messages.enqueue(message)
-      case ReplayDestination(id) =>
-        if (id == replayTo) {
-          // we only need log record upto this point
-          return (steps, messages)
-        }
-      case other =>
-        throw new RuntimeException(s"cannot handle $other in the log")
+    while (logs.hasNext) {
+      logs.next() match {
+        case s: ProcessingStep =>
+          steps.enqueue(s)
+        case MessageContent(message) =>
+          messages.enqueue(message)
+        case ReplayDestination(id) =>
+          if (id == replayTo) {
+            // we only need log record upto this point
+            return (steps, messages)
+          }
+        case other =>
+          throw new RuntimeException(s"cannot handle $other in the log")
+      }
     }
     (steps, messages)
   }
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/CostBasedScheduleGenerator.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/CostBasedScheduleGenerator.scala
index dd43eb99aa..be376fa19d 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/CostBasedScheduleGenerator.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/CostBasedScheduleGenerator.scala
@@ -204,11 +204,10 @@ class CostBasedScheduleGenerator(
 
         // Enumerate all ports belonging to the Region
         val ports: Set[GlobalPortIdentity] = physicalOps.flatMap { op =>
-          op.inputPorts.keys
-            .map(inputPortId => GlobalPortIdentity(op.id, inputPortId, input = 
true))
-            .toSet ++ op.outputPorts.keys
-            .map(outputPortId => GlobalPortIdentity(op.id, outputPortId))
-            .toSet
+          op.inputPorts.keysIterator
+            .map(inputPortId => GlobalPortIdentity(op.id, inputPortId, input = 
true)) ++
+            op.outputPorts.keysIterator
+              .map(outputPortId => GlobalPortIdentity(op.id, outputPortId))
         }
 
         // Build the Region skeleton (no input‑port URIs yet)
@@ -233,10 +232,10 @@ class CostBasedScheduleGenerator(
     // Pass 2 – add input‑port storage configs (reader URIs)
 
     regionsWithOnlyOutputPortURIs.map { existingRegion =>
+      val regionOpIds = existingRegion.getOperators.map(_.id)
       // MatEdges that originally connected to the input ports of this region.
-      val relevantMatEdges: Set[PhysicalLink] = matEdges.filter { matEdge =>
-        existingRegion.getOperators.exists(_.id == matEdge.toOpId)
-      }
+      val relevantMatEdges: Set[PhysicalLink] =
+        matEdges.filter(matEdge => regionOpIds.contains(matEdge.toOpId))
 
       // Assign storage URIs to input ports of each materialized edge (each 
input port could have more than one URI)
       val inputPortConfigs: Map[GlobalPortIdentity, 
IntermediateInputPortConfig] =
@@ -401,6 +400,7 @@ class CostBasedScheduleGenerator(
       }
     // Queue to hold states to be explored, starting with the empty set
     val queue: mutable.Queue[Set[PhysicalLink]] = 
mutable.Queue(Set.empty[PhysicalLink])
+    val inQueue: mutable.Set[Set[PhysicalLink]] = 
mutable.Set(Set.empty[PhysicalLink])
     // Keep track of visited states to avoid revisiting
     val visited: mutable.Set[Set[PhysicalLink]] = 
mutable.Set.empty[Set[PhysicalLink]]
     // Used for the Early Stop optimization technique
@@ -415,6 +415,7 @@ class CostBasedScheduleGenerator(
     while (queue.nonEmpty) {
       // A state is represented as a set of materialized non-blocking edges.
       val currentState = queue.dequeue()
+      inQueue.remove(currentState)
       breakable {
         if (
           oEarlyStop && schedulableStates
@@ -474,7 +475,7 @@ class CostBasedScheduleGenerator(
         val unvisitedNeighborStates = candidateEdges
           .map(edge => currentState + edge)
           .filter(neighborState =>
-            !visited.contains(neighborState) && !queue.contains(neighborState)
+            !visited.contains(neighborState) && 
!inQueue.contains(neighborState)
           )
 
         val filteredNeighborStates = if (oEarlyStop) {
@@ -486,25 +487,7 @@ class CostBasedScheduleGenerator(
           unvisitedNeighborStates
         }
 
-        if (globalSearch) {
-          // include all unvisited neighbors
-          filteredNeighborStates.foreach(neighborState => 
queue.enqueue(neighborState))
-        } else {
-          // greedy search, only include an unvisited neighbor with the lowest 
cost
-          if (filteredNeighborStates.nonEmpty) {
-            val minCostNeighborState = 
filteredNeighborStates.minBy(neighborState =>
-              tryConnectRegionDAG(
-                physicalPlan.getBlockingAndDependeeLinks ++ neighborState
-              ) match {
-                case Left(regionDAG) =>
-                  allocateResourcesAndEvaluateCost(regionDAG)
-                case Right(_) =>
-                  Double.MaxValue
-              }
-            )
-            queue.enqueue(minCostNeighborState)
-          }
-        }
+        enqueueFrontier(filteredNeighborStates, queue, inQueue, globalSearch)
       }
     }
 
@@ -515,6 +498,31 @@ class CostBasedScheduleGenerator(
     )
   }
 
+  private def enqueueFrontier(
+      neighbors: Iterable[Set[PhysicalLink]],
+      queue: mutable.Queue[Set[PhysicalLink]],
+      inQueue: mutable.Set[Set[PhysicalLink]],
+      globalSearch: Boolean
+  ): Unit = {
+    if (globalSearch) {
+      neighbors.foreach { neighborState =>
+        inQueue.add(neighborState)
+        queue.enqueue(neighborState)
+      }
+    } else if (neighbors.nonEmpty) {
+      val minCostNeighborState = neighbors.minBy(neighborState =>
+        tryConnectRegionDAG(
+          physicalPlan.getBlockingAndDependeeLinks ++ neighborState
+        ) match {
+          case Left(regionDAG) => allocateResourcesAndEvaluateCost(regionDAG)
+          case Right(_)        => Double.MaxValue
+        }
+      )
+      inQueue.add(minCostNeighborState)
+      queue.enqueue(minCostNeighborState)
+    }
+  }
+
   /** Constructs a baseline fully materialized region plan (one operator per 
region) and evaluates its cost. */
   def getFullyMaterializedSearchState: SearchResult = {
     val startTime = System.nanoTime()
@@ -577,6 +585,7 @@ class CostBasedScheduleGenerator(
 
     // Queue to hold states to be explored, starting with the seed state
     val queue: mutable.Queue[Set[PhysicalLink]] = mutable.Queue(finalSeedState)
+    val inQueue: mutable.Set[Set[PhysicalLink]] = mutable.Set(finalSeedState)
     // Keep track of visited states to avoid revisiting
     val visited: mutable.Set[Set[PhysicalLink]] = 
mutable.Set.empty[Set[PhysicalLink]]
     // Initialize the bestResult with an impossible high cost for comparison
@@ -588,6 +597,7 @@ class CostBasedScheduleGenerator(
 
     while (queue.nonEmpty) {
       val currentState = queue.dequeue()
+      inQueue.remove(currentState)
       visited.add(currentState)
       tryConnectRegionDAG(
         physicalPlan.getBlockingAndDependeeLinks ++ currentState
@@ -622,28 +632,10 @@ class CostBasedScheduleGenerator(
         val unvisitedNeighborStates = currentState
           .map(edge => currentState - edge)
           .filter(neighborState =>
-            !visited.contains(neighborState) && !queue.contains(neighborState)
+            !visited.contains(neighborState) && 
!inQueue.contains(neighborState)
           )
 
-        if (globalSearch) {
-          // include all unvisited neighbors
-          unvisitedNeighborStates.foreach(neighborState => 
queue.enqueue(neighborState))
-        } else {
-          // greedy search, only include an unvisited neighbor with the lowest 
cost
-          if (unvisitedNeighborStates.nonEmpty) {
-            val minCostNeighborState = 
unvisitedNeighborStates.minBy(neighborState =>
-              tryConnectRegionDAG(
-                physicalPlan.getBlockingAndDependeeLinks ++ neighborState
-              ) match {
-                case Left(regionDAG) =>
-                  allocateResourcesAndEvaluateCost(regionDAG)
-                case Right(_) =>
-                  Double.MaxValue
-              }
-            )
-            queue.enqueue(minCostNeighborState)
-          }
-        }
+        enqueueFrontier(unvisitedNeighborStates, queue, inQueue, globalSearch)
       }
     }
 
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/Region.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/Region.scala
index 248a3ece3c..bbb4035e22 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/Region.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/Region.scala
@@ -73,14 +73,9 @@ case class Region(
     * The effective source contains operators that have 0 input links in this 
region.
     */
   def getSourceOperators: Set[PhysicalOp] = {
-    getOperators
-      .filter(physicalOp =>
-        physicalOp
-          .getInputLinks()
-          .map(link => link.fromOpId)
-          .forall(upstreamOpId => 
!getOperators.map(_.id).contains(upstreamOpId))
-      )
-
+    getOperators.filter(physicalOp =>
+      physicalOp.getInputLinks().forall(link => 
!operators.contains(link.fromOpId))
+    )
   }
 
   /**
@@ -90,16 +85,13 @@ case class Region(
   def getStarterOperators: Set[PhysicalOp] = {
     val opsReadingFromMaterialization = resourceConfig match {
       case Some(config) =>
-        config.portConfigs
-          .filter {
-            case (globalPortId, config) =>
-              globalPortId.input && config.storageURIs.nonEmpty
-          }
-          .map {
-            case (globalPortId, _) => globalPortId.opId
+        config.portConfigs.iterator
+          .collect {
+            case (globalPortId, portCfg) if globalPortId.input && 
portCfg.storageURIs.nonEmpty =>
+              globalPortId.opId
           }
           .toSet
-          .map(opId => getOperator(opId))
+          .map(getOperator)
       case None => Set.empty
     }
     opsReadingFromMaterialization ++ getSourceOperators
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/ScheduleGenerator.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/ScheduleGenerator.scala
index 68124f7687..13f1acebdc 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/ScheduleGenerator.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/ScheduleGenerator.scala
@@ -52,7 +52,7 @@ abstract class ScheduleGenerator(
   def generateScheduleFromRegionPlan(regionPlan: RegionPlan): Schedule = {
     val inDegree = mutable.Map.empty[RegionIdentity, Int]
     regionPlan.topologicalIterator().foreach { rid =>
-      inDegree(rid) = regionPlan.dag.incomingEdgesOf(rid).asScala.size
+      inDegree(rid) = regionPlan.dag.inDegreeOf(rid)
     }
 
     val readyRegionsQueue = mutable.Queue(
@@ -70,9 +70,13 @@ abstract class ScheduleGenerator(
     //      b. If a successor's in-degree reaches zero, enqueue it to the 
readyRegionsQueue.
     // 4. Increment level and repeat.
     while (readyRegionsQueue.nonEmpty) {
-      val batchIds = (1 to ApplicationConfig.maxConcurrentRegions).flatMap { _ 
=>
-        if (readyRegionsQueue.nonEmpty) Some(readyRegionsQueue.dequeue()) else 
None
-      }.toSet
+      val batch = Set.newBuilder[RegionIdentity]
+      var remaining = ApplicationConfig.maxConcurrentRegions
+      while (remaining > 0 && readyRegionsQueue.nonEmpty) {
+        batch += readyRegionsQueue.dequeue()
+        remaining -= 1
+      }
+      val batchIds = batch.result()
 
       tmpLevelSets(level) = batchIds
       batchIds.foreach { rid =>
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/config/WorkerConfig.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/config/WorkerConfig.scala
index da773d7a6b..d6c0a7ae4b 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/config/WorkerConfig.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/scheduling/config/WorkerConfig.scala
@@ -42,12 +42,13 @@ case object WorkerConfig {
       1
     }
 
-    (0 until workerCount).toList.map(idx =>
+    lazy val largeBinaryBaseUri = 
LargeBinaryManager.baseUriForExecution(physicalOp.executionId.id)
+    List.tabulate(workerCount)(idx =>
       WorkerConfig(
         VirtualIdentityUtils.createWorkerIdentity(physicalOp.workflowId, 
physicalOp.id, idx),
         pveName = physicalOp.pveName,
         cuid = cuid,
-        largeBinaryBaseUri = 
LargeBinaryManager.baseUriForExecution(physicalOp.executionId.id)
+        largeBinaryBaseUri = largeBinaryBaseUri
       )
     )
   }
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/FinalizeCheckpointHandler.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/FinalizeCheckpointHandler.scala
index 96d7b4dfaf..1ede5a54ec 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/FinalizeCheckpointHandler.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/FinalizeCheckpointHandler.scala
@@ -44,40 +44,43 @@ trait FinalizeCheckpointHandler {
       msg: FinalizeCheckpointRequest,
       ctx: AsyncRPCContext
   ): Future[FinalizeCheckpointResponse] = {
-    val checkpointSize = if 
(dp.ecmManager.checkpoints.contains(msg.checkpointId)) {
-      val waitFuture = new CompletableFuture[Unit]()
-      val chkpt = dp.ecmManager.checkpoints(msg.checkpointId)
-      val closure = (worker: WorkflowWorker) => {
-        logger.info(s"Main thread: start to serialize recorded messages.")
-        chkpt.save(
-          SerializedState.IN_FLIGHT_MSG_KEY,
-          worker.recordedInputs.getOrElse(msg.checkpointId, new ArrayBuffer())
-        )
-        worker.recordedInputs.remove(msg.checkpointId)
-        logger.info(s"Main thread: recorded messages serialized.")
-        waitFuture.complete(())
-        ()
-      }
-      // TODO: find a way to skip logging for the following output?
-      dp.outputHandler(
-        Left(MainThreadDelegateMessage(closure))
-      ) //this will create duplicate log records!
-      waitFuture.get()
-      logger.info(s"Start to write checkpoint to storage. Destination: 
${msg.writeTo}")
-      val storage = 
SequentialRecordStorage.getStorage[CheckpointState](Some(new URI(msg.writeTo)))
-      val writer = storage.getWriter(actorId.name.replace("Worker:", ""))
-      writer.writeRecord(chkpt)
-      writer.flush()
-      writer.close()
-      logger.info(s"Checkpoint finalized, total size = ${chkpt.size()} bytes")
-      chkpt.size()
-    } else {
-      logger.info(s"Checkpoint is estimation-only. report estimated size.")
-      dp.executor match {
-        case support: CheckpointSupport =>
-          support.getEstimatedCheckpointCost
-        case _ => 0L
-      } // for estimation
+    val checkpointId = msg.checkpointId
+    val checkpointSize = dp.ecmManager.checkpoints.get(checkpointId) match {
+      case Some(chkpt) =>
+        val waitFuture = new CompletableFuture[Unit]()
+        val closure = (worker: WorkflowWorker) => {
+          logger.info(s"Main thread: start to serialize recorded messages.")
+          chkpt.save(
+            SerializedState.IN_FLIGHT_MSG_KEY,
+            worker.recordedInputs.getOrElse(checkpointId, new ArrayBuffer())
+          )
+          worker.recordedInputs.remove(checkpointId)
+          logger.info(s"Main thread: recorded messages serialized.")
+          waitFuture.complete(())
+          ()
+        }
+        // TODO: find a way to skip logging for the following output?
+        dp.outputHandler(
+          Left(MainThreadDelegateMessage(closure))
+        ) //this will create duplicate log records!
+        waitFuture.get()
+        logger.info(s"Start to write checkpoint to storage. Destination: 
${msg.writeTo}")
+        val storage =
+          SequentialRecordStorage.getStorage[CheckpointState](Some(new 
URI(msg.writeTo)))
+        val writer = storage.getWriter(actorId.name.replace("Worker:", ""))
+        writer.writeRecord(chkpt)
+        writer.flush()
+        writer.close()
+        val size = chkpt.size()
+        logger.info(s"Checkpoint finalized, total size = $size bytes")
+        size
+      case None =>
+        logger.info(s"Checkpoint is estimation-only. report estimated size.")
+        dp.executor match {
+          case support: CheckpointSupport =>
+            support.getEstimatedCheckpointCost
+          case _ => 0L
+        } // for estimation
     }
     FinalizeCheckpointResponse(checkpointSize)
   }
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/PrepareCheckpointHandler.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/PrepareCheckpointHandler.scala
index 3333f54e90..122a06f615 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/PrepareCheckpointHandler.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/PrepareCheckpointHandler.scala
@@ -46,9 +46,8 @@ trait PrepareCheckpointHandler {
   ): Future[EmptyReturn] = {
     logger.info("Start to take checkpoint")
     if (!msg.estimationOnly) {
-      dp.serializationManager.registerSerialization(() => {
-        serializeWorkerState(msg.checkpointId)
-      })
+      val checkpointId = msg.checkpointId
+      dp.serializationManager.registerSerialization(() => 
serializeWorkerState(checkpointId))
     } else {
       logger.info(s"Checkpoint is estimation-only. do nothing.")
     }
@@ -65,9 +64,8 @@ trait PrepareCheckpointHandler {
     // 2. serialize operator state
     dp.executor match {
       case support: CheckpointSupport =>
-        dp.outputManager.outputIterator.setTupleOutput(
-          support.serializeState(dp.outputManager.outputIterator.outputIter, 
chkpt)
-        )
+        val outputIterator = dp.outputManager.outputIterator
+        
outputIterator.setTupleOutput(support.serializeState(outputIterator.outputIter, 
chkpt))
         logger.info("Serialized operator state")
       case _ =>
         logger.info("Operator does not support checkpoint, skip")
@@ -78,9 +76,9 @@ trait PrepareCheckpointHandler {
     val closure = (worker: WorkflowWorker) => {
       val queuedMsgs = mutable.ArrayBuffer[WorkflowFIFOMessage]()
       worker.inputQueue.forEach {
-        case WorkflowWorker.FIFOMessageElement(msg)           => 
queuedMsgs.append(msg)
-        case WorkflowWorker.TimerBasedControlElement(control) => // skip
-        case WorkflowWorker.ActorCommandElement(cmd)          => // skip
+        case WorkflowWorker.FIFOMessageElement(msg)     => 
queuedMsgs.append(msg)
+        case WorkflowWorker.TimerBasedControlElement(_) => // skip
+        case WorkflowWorker.ActorCommandElement(_)      => // skip
       }
       chkpt.save(SerializedState.DP_QUEUED_MSG_KEY, queuedMsgs)
       // get all output messages from worker.transferService
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/common/CheckpointState.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/common/CheckpointState.scala
index 0da3eaba6f..31113071aa 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/common/CheckpointState.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/common/CheckpointState.scala
@@ -34,15 +34,14 @@ class CheckpointState extends Serializable {
   }
 
   def load[T <: Any](key: String): T = {
-    if (states.contains(key)) {
-      states(key).toObject(AmberRuntime.serde).asInstanceOf[T]
-    } else {
-      throw new RuntimeException(s"no state saved for key = $key")
+    states.get(key) match {
+      case Some(state) => state.toObject(AmberRuntime.serde).asInstanceOf[T]
+      case None        => throw new RuntimeException(s"no state saved for key 
= $key")
     }
   }
 
   def size(): Long = {
-    states.filter(_._2 != null).map(_._2.size()).sum
+    states.iterator.filter(_._2 != null).map(_._2.size()).sum
   }
 
 }
diff --git 
a/amber/src/main/scala/org/apache/texera/amber/engine/common/FriesReconfigurationAlgorithm.scala
 
b/amber/src/main/scala/org/apache/texera/amber/engine/common/FriesReconfigurationAlgorithm.scala
index 544ce819a1..37556d2fd9 100644
--- 
a/amber/src/main/scala/org/apache/texera/amber/engine/common/FriesReconfigurationAlgorithm.scala
+++ 
b/amber/src/main/scala/org/apache/texera/amber/engine/common/FriesReconfigurationAlgorithm.scala
@@ -29,8 +29,7 @@ import 
org.apache.texera.amber.engine.architecture.scheduling.{Region, WorkflowE
 import org.jgrapht.alg.connectivity.ConnectivityInspector
 
 import scala.collection.mutable
-import scala.collection.mutable.ArrayBuffer
-import scala.jdk.CollectionConverters.SetHasAsScala
+import scala.jdk.CollectionConverters.{ListHasAsScala, SetHasAsScala}
 
 object FriesReconfigurationAlgorithm {
 
@@ -40,88 +39,77 @@ object FriesReconfigurationAlgorithm {
       reconfigurations: Set[UpdateExecutorRequest]
   )
 
-  private def getOneToManyOperators(region: Region): Set[PhysicalOpIdentity] = 
{
-    region.getOperators.filter(op => op.isOneToManyOp).map(op => op.id)
-  }
-
   def getReconfigurations(
       workflowExecutionManager: WorkflowExecutionManager,
       reconfiguration: WorkflowReconfigureRequest
   ): Set[FriesComponent] = {
     // independently schedule reconfigurations for each region:
     workflowExecutionManager.getExecutingRegions
-      .flatMap(region => computeMCS(region, reconfiguration, 
reconfiguration.reconfigurationId))
+      .flatMap(region => computeMCS(region, reconfiguration.reconfiguration))
   }
 
   private def computeMCS(
       region: Region,
-      reconfiguration: WorkflowReconfigureRequest,
-      epochMarkerId: String
+      reconfigurations: Seq[UpdateExecutorRequest]
   ): List[FriesComponent] = {
 
     // add all reconfiguration operators to M
-    val reconfigOps = reconfiguration.reconfiguration.map(req => 
req.targetOpId).toSet
+    val reconfigOps = reconfigurations.iterator.map(_.targetOpId).toSet
     val M = mutable.Set.empty ++ reconfigOps
 
     // for each one-to-many operator, add it to M if its downstream has a 
reconfiguration operator
-    val oneToManyOperators = getOneToManyOperators(region)
-    oneToManyOperators.foreach(oneToManyOp => {
-      val intersection = 
region.dag.getDescendants(oneToManyOp).asScala.intersect(reconfigOps)
-      if (intersection.nonEmpty) {
-        M += oneToManyOp
+    region.getOperators.foreach { op =>
+      if (op.isOneToManyOp) {
+        val descendants = region.dag.getDescendants(op.id)
+        if (reconfigOps.exists(descendants.contains)) {
+          M += op.id
+        }
       }
-    })
+    }
 
     // compute MCS based on M
-    var forwardVertices: Set[PhysicalOpIdentity] = Set()
-    var backwardVertices: Set[PhysicalOpIdentity] = Set()
+    var forwardVertices = Set.empty[PhysicalOpIdentity]
+    var backwardVertices = Set.empty[PhysicalOpIdentity]
 
     val topologicalOps = region.topologicalIterator().toList
-    val reverseTopologicalOps = topologicalOps.reverse
 
-    topologicalOps.foreach(opId => {
+    topologicalOps.foreach { opId =>
       val op = region.getOperator(opId)
-      val parents = op.inputPorts.flatMap(_._2._2).map(_.fromOpId)
-      val fromParent: Boolean = parents.exists(p => 
forwardVertices.contains(p))
+      val fromParent = op.inputPorts.valuesIterator
+        .flatMap(_._2)
+        .exists(link => forwardVertices.contains(link.fromOpId))
       if (M.contains(opId) || fromParent) {
         forwardVertices += opId
       }
-    })
+    }
 
-    reverseTopologicalOps.foreach(opId => {
+    topologicalOps.reverseIterator.foreach { opId =>
       val op = region.getOperator(opId)
-      val children = op.outputPorts.flatMap(_._2._2).map(_.toOpId)
-      val fromChildren: Boolean = children.exists(p => 
backwardVertices.contains(p))
-      if (M.contains(opId) || fromChildren) {
+      val fromChild = op.outputPorts.valuesIterator
+        .flatMap(_._2)
+        .exists(link => backwardVertices.contains(link.toOpId))
+      if (M.contains(opId) || fromChild) {
         backwardVertices += opId
       }
-    })
+    }
 
     val resultMCSOpIds = forwardVertices.intersect(backwardVertices)
     val newLinks =
       region.getLinks.filter(link =>
         resultMCSOpIds.contains(link.fromOpId) && 
resultMCSOpIds.contains(link.toOpId)
       )
-    val mcsPlan = PhysicalPlan(resultMCSOpIds.map(opId => 
region.getOperator(opId)), newLinks)
-
-    // find the MCS components,
-    // for each component, send an epoch marker to each of its source operators
-    val epochMarkers = new ArrayBuffer[FriesComponent]()
+    val mcsPlan = PhysicalPlan(resultMCSOpIds.map(region.getOperator), 
newLinks)
 
     val connectedSets = new ConnectivityInspector(mcsPlan.dag).connectedSets()
-    connectedSets.forEach(component => {
-      val componentSet = component.asScala.toSet
-      val componentPlan = mcsPlan.getSubPlan(componentSet)
-      val reconfigCommands =
-        reconfiguration.reconfiguration
-          .filter(req => component.contains(req.targetOpId))
-          .toSet
-
-      // find the source operators of the component
-      val sources = componentSet.intersect(mcsPlan.getSourceOperatorIds)
-      epochMarkers += FriesComponent(sources, 
componentPlan.operators.map(_.id), reconfigCommands)
-    })
-    epochMarkers.toList
+    val mcsSources = mcsPlan.getSourceOperatorIds
+    connectedSets.asScala.toList.map { component =>
+      val operators = component.asScala.toSet
+      FriesComponent(
+        operators.intersect(mcsSources),
+        operators,
+        reconfigurations.iterator.filter(req => 
operators.contains(req.targetOpId)).toSet
+      )
+    }
   }
 
 }
diff --git 
a/amber/src/main/scala/org/apache/texera/web/service/ExecutionConsoleService.scala
 
b/amber/src/main/scala/org/apache/texera/web/service/ExecutionConsoleService.scala
index fd16c654f1..8255c8b24f 100644
--- 
a/amber/src/main/scala/org/apache/texera/web/service/ExecutionConsoleService.scala
+++ 
b/amber/src/main/scala/org/apache/texera/web/service/ExecutionConsoleService.scala
@@ -172,17 +172,19 @@ class ExecutionConsoleService(
       newState.operatorConsole
         .foreach {
           case (opId, info) =>
-            val oldConsole = oldState.operatorConsole.getOrElse(opId, new 
OperatorConsole())
+            val oldConsole =
+              oldState.operatorConsole.getOrElse(opId, 
OperatorConsole.defaultInstance)
             val diff = info.consoleMessages.diff(oldConsole.consoleMessages)
             output.append(ConsoleUpdateEvent(opId, diff))
 
-            info.evaluateExprResults.keys
-              .filterNot(oldConsole.evaluateExprResults.contains)
-              .foreach { key =>
-                output.append(
-                  PythonExpressionEvaluateResponse(key, 
info.evaluateExprResults(key).values)
-                )
-              }
+            info.evaluateExprResults.foreach {
+              case (key, evalResult) =>
+                if (!oldConsole.evaluateExprResults.contains(key)) {
+                  output.append(
+                    PythonExpressionEvaluateResponse(key, evalResult.values)
+                  )
+                }
+            }
         }
       output
     })
@@ -207,7 +209,7 @@ class ExecutionConsoleService(
   addSubscription(
     client.registerCallback[ExecutionStateUpdate] {
       case ExecutionStateUpdate(state: WorkflowAggregatedState.Recognized)
-          if Set(COMPLETED, FAILED, KILLED).contains(state) =>
+          if state == COMPLETED || state == FAILED || state == KILLED =>
         logger.info("Workflow execution terminated. Commit console messages.")
         consoleMessageOpIdToWriterMap.values.foreach { writer =>
           try {
diff --git 
a/amber/src/main/scala/org/apache/texera/web/service/ExecutionStatsService.scala
 
b/amber/src/main/scala/org/apache/texera/web/service/ExecutionStatsService.scala
index 2c173c25a8..7e470a38b4 100644
--- 
a/amber/src/main/scala/org/apache/texera/web/service/ExecutionStatsService.scala
+++ 
b/amber/src/main/scala/org/apache/texera/web/service/ExecutionStatsService.scala
@@ -43,11 +43,11 @@ import 
org.apache.texera.amber.engine.architecture.rpc.controlreturns.WorkflowAg
   KILLED
 }
 import org.apache.texera.amber.engine.common.Utils
+import 
org.apache.texera.amber.engine.architecture.worker.statistics.PortTupleMetricsMapping
 import org.apache.texera.amber.engine.common.Utils.maptoStatusCode
 import org.apache.texera.amber.engine.common.client.AmberClient
 import org.apache.texera.amber.engine.common.executionruntimestate.{
   OperatorMetrics,
-  OperatorStatistics,
   OperatorWorkerMapping
 }
 import org.apache.texera.amber.error.ErrorUtils.{
@@ -104,23 +104,20 @@ class ExecutionStatsService(
       // Update operator stats if any operator updates its stat
       if (newState.operatorInfo.toSet != oldState.operatorInfo.toSet) {
         Iterable(
-          OperatorStatisticsUpdateEvent(newState.operatorInfo.collect {
-            case x =>
-              val metrics = x._2
-              val inMap = metrics.operatorStatistics.inputMetrics
-                .map(pm => pm.portId.id.toString -> pm.tupleMetrics.count)
-                .toMap
-              val outMap = metrics.operatorStatistics.outputMetrics
-                .map(pm => pm.portId.id.toString -> pm.tupleMetrics.count)
-                .toMap
+          OperatorStatisticsUpdateEvent(newState.operatorInfo.map {
+            case (opId, metrics) =>
+              val (inCount, inSize, inMap) =
+                summarizePortMetrics(metrics.operatorStatistics.inputMetrics)
+              val (outCount, outSize, outMap) =
+                summarizePortMetrics(metrics.operatorStatistics.outputMetrics)
 
               val res = OperatorAggregatedMetrics(
                 Utils.aggregatedStateToString(metrics.operatorState),
-                
metrics.operatorStatistics.inputMetrics.map(_.tupleMetrics.count).sum,
-                
metrics.operatorStatistics.inputMetrics.map(_.tupleMetrics.size).sum,
+                inCount,
+                inSize,
                 inMap,
-                
metrics.operatorStatistics.outputMetrics.map(_.tupleMetrics.count).sum,
-                
metrics.operatorStatistics.outputMetrics.map(_.tupleMetrics.size).sum,
+                outCount,
+                outSize,
                 outMap,
                 metrics.operatorStatistics.numWorkers,
                 metrics.operatorStatistics.dataProcessingTime,
@@ -128,7 +125,7 @@ class ExecutionStatsService(
                 metrics.operatorStatistics.idleTime,
                 reusedFromCache = metrics.reusedFromCache
               )
-              (x._1, res)
+              (opId, res)
           })
         )
       } else {
@@ -209,7 +206,7 @@ class ExecutionStatsService(
   addSubscription(
     client.registerCallback[ExecutionStateUpdate] {
       case ExecutionStateUpdate(state: WorkflowAggregatedState.Recognized)
-          if Set(COMPLETED, FAILED, KILLED).contains(state) =>
+          if state == COMPLETED || state == FAILED || state == KILLED =>
         logger.info("Workflow execution terminated. Commit runtime 
statistics.")
         try {
           runtimeStatsWriter.close()
@@ -224,38 +221,59 @@ class ExecutionStatsService(
   private def computeStatsDiff(
       newMetrics: Map[String, OperatorMetrics]
   ): Map[String, OperatorMetrics] = {
-    // Default metrics for new operators
-    val defaultMetrics = OperatorMetrics(
-      WorkflowAggregatedState.UNINITIALIZED,
-      OperatorStatistics(Seq.empty, Seq.empty, 0, 0, 0, 0)
-    )
-
-    // Determine new and old keys
-    val newKeys = newMetrics.keySet.diff(lastPersistedMetrics.keySet)
-    val oldKeys = lastPersistedMetrics.keySet.diff(newMetrics.keySet)
+    val previousMetrics = lastPersistedMetrics
+    val missingKeys = previousMetrics.keySet.diff(newMetrics.keySet)
+    newMetrics ++ missingKeys.map(key => key -> previousMetrics(key))
+  }
 
-    // Update last metrics with default metrics for new keys
-    val updatedLastMetrics = lastPersistedMetrics ++ newKeys.map(_ -> 
defaultMetrics)
+  private def summarizePortMetrics(
+      portMetrics: Seq[PortTupleMetricsMapping]
+  ): (Long, Long, Map[String, Long]) = {
+    val perPortCounts = Map.newBuilder[String, Long]
+    val (totalCount, totalSize) = aggregatePortMetrics(
+      portMetrics,
+      (portId, count) => perPortCounts += (portId -> count)
+    )
+    (totalCount, totalSize, perPortCounts.result())
+  }
 
-    // Combine new metrics with old metrics for keys that are no longer present
-    newMetrics ++ oldKeys.map(key => key -> updatedLastMetrics(key))
+  private def aggregatePortMetrics(
+      portMetrics: Seq[PortTupleMetricsMapping],
+      onPort: (String, Long) => Unit = (_, _) => ()
+  ): (Long, Long) = {
+    var totalCount = 0L
+    var totalSize = 0L
+    portMetrics.foreach { pm =>
+      val count = pm.tupleMetrics.count
+      totalCount += count
+      totalSize += pm.tupleMetrics.size
+      onPort(pm.portId.id.toString, count)
+    }
+    (totalCount, totalSize)
   }
 
   private def storeRuntimeStatistics(
       operatorStatistics: scala.collection.immutable.Map[String, 
OperatorMetrics]
   ): Unit = {
+    if (operatorStatistics.isEmpty) {
+      return
+    }
     try {
+      val schema = ResultSchema.runtimeStatisticsSchema
+      val timestamp = new java.sql.Timestamp(System.currentTimeMillis())
       operatorStatistics.foreach {
         case (operatorId, stat) =>
+          val (inCount, inSize) = 
aggregatePortMetrics(stat.operatorStatistics.inputMetrics)
+          val (outCount, outSize) = 
aggregatePortMetrics(stat.operatorStatistics.outputMetrics)
           val runtimeStats = new Tuple(
-            ResultSchema.runtimeStatisticsSchema,
+            schema,
             Array(
               operatorId,
-              new java.sql.Timestamp(System.currentTimeMillis()),
-              
stat.operatorStatistics.inputMetrics.map(_.tupleMetrics.count).sum,
-              
stat.operatorStatistics.inputMetrics.map(_.tupleMetrics.size).sum,
-              
stat.operatorStatistics.outputMetrics.map(_.tupleMetrics.count).sum,
-              
stat.operatorStatistics.outputMetrics.map(_.tupleMetrics.size).sum,
+              timestamp,
+              inCount,
+              inSize,
+              outCount,
+              outSize,
               stat.operatorStatistics.dataProcessingTime,
               stat.operatorStatistics.controlProcessingTime,
               stat.operatorStatistics.idleTime,
diff --git 
a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/EmbeddedControlMessageHandlerSpec.scala
 
b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/EmbeddedControlMessageHandlerSpec.scala
index 05e83fa1d2..94037bcad9 100644
--- 
a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/EmbeddedControlMessageHandlerSpec.scala
+++ 
b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/EmbeddedControlMessageHandlerSpec.scala
@@ -338,4 +338,32 @@ class EmbeddedControlMessageHandlerSpec extends 
AnyFlatSpec {
     )
     assert(fixture.logManager.marked.toSeq == Seq(ecmId))
   }
+
+  it should "inject one ECM per source worker when a source operator has 
multiple workers" in {
+    val fixture = newFixture()
+    seedRunningRegion(fixture.init)
+    val secondSourceWorker = mkWorkerId(sourceOp, 1)
+    val regionExec = 
fixture.init.cp.workflowExecution.getRunningRegionExecutions.head
+    
regionExec.getOperatorExecution(sourceOp.id).initWorkerExecution(secondSourceWorker)
+
+    fixture.init.propagateEmbeddedControlMessage(request(), 
fixture.init.mkContext(COORDINATOR))
+
+    val sentMessages = embeddedMessages(fixture.sent)
+    assert(
+      sentMessages.map(_._1).toSet == Set(
+        ChannelIdentity(COORDINATOR, sourceWorker, isControl = true),
+        ChannelIdentity(COORDINATOR, secondSourceWorker, isControl = true)
+      )
+    )
+    val expectedControlChannels = Set(sourceWorker, 
secondSourceWorker).flatMap { w =>
+      Seq(
+        ChannelIdentity(COORDINATOR, w, isControl = true),
+        ChannelIdentity(w, COORDINATOR, isControl = true)
+      )
+    }
+    sentMessages.foreach {
+      case (_, ecm) =>
+        assert(expectedControlChannels.subsetOf(ecm.scope.toSet))
+    }
+  }
 }
diff --git 
a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/RetrieveWorkflowStateHandlerSpec.scala
 
b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/RetrieveWorkflowStateHandlerSpec.scala
index cb5a8d487d..e64373c5ab 100644
--- 
a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/RetrieveWorkflowStateHandlerSpec.scala
+++ 
b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/coordinator/promisehandlers/RetrieveWorkflowStateHandlerSpec.scala
@@ -19,7 +19,21 @@
 
 package org.apache.texera.amber.engine.architecture.coordinator.promisehandlers
 
-import org.apache.texera.amber.core.workflow.{PhysicalPlan, WorkflowContext}
+import com.twitter.util.{Await, Duration}
+import org.apache.texera.amber.core.executor.OpExecInitInfo
+import org.apache.texera.amber.core.virtualidentity.{
+  ExecutionIdentity,
+  OperatorIdentity,
+  PhysicalOpIdentity,
+  WorkflowIdentity
+}
+import org.apache.texera.amber.core.workflow.{
+  GlobalPortIdentity,
+  PhysicalOp,
+  PhysicalPlan,
+  PortIdentity,
+  WorkflowContext
+}
 import org.apache.texera.amber.engine.architecture.coordinator.{
   CoordinatorAsyncRPCHandlerInitializer,
   CoordinatorConfig,
@@ -32,12 +46,21 @@ import 
org.apache.texera.amber.engine.architecture.rpc.controlcommands.{
   EmptyRequest,
   PropagateEmbeddedControlMessageRequest
 }
+import org.apache.texera.amber.engine.architecture.rpc.controlreturns.{
+  EmptyReturn,
+  PropagateEmbeddedControlMessageResponse,
+  RetrieveWorkflowStateResponse,
+  ReturnInvocation,
+  StringResponse
+}
 import 
org.apache.texera.amber.engine.architecture.rpc.workerservice.WorkerServiceGrpc.METHOD_RETRIEVE_STATE
+import org.apache.texera.amber.engine.architecture.scheduling.{Region, 
RegionIdentity}
 import 
org.apache.texera.amber.engine.architecture.worker.WorkflowWorker.MainThreadDelegateMessage
 import org.apache.texera.amber.engine.common.ambermessage.WorkflowFIFOMessage
 import org.apache.texera.amber.engine.common.virtualidentity.util.COORDINATOR
 import org.apache.texera.amber.engine.e2e.TestUtils.buildWorkflow
 import org.apache.texera.amber.operator.TestOperators
+import org.apache.texera.amber.util.VirtualIdentityUtils
 import org.scalatest.flatspec.AnyFlatSpec
 
 import scala.collection.mutable.ArrayBuffer
@@ -136,4 +159,74 @@ class RetrieveWorkflowStateHandlerSpec extends AnyFlatSpec 
{
     assert(req.targetOps.toSet == expectedOps)
     assert(req.scope.toSet == expectedOps)
   }
+
+  it should "map StringResponse replies to their strings and fallback other 
returns to empty strings" in {
+    val (init, sent) = newFixture()
+    init.cp.workflowScheduler.physicalPlan = PhysicalPlan(Set.empty, Set.empty)
+
+    val response = init.retrieveWorkflowState(EmptyRequest(), rpcContext)
+    assert(sent.size == 1)
+    val invocation = sent.head.payload.asInstanceOf[ControlInvocation]
+    init.cp.asyncRPCClient.fulfillPromise(
+      ReturnInvocation(
+        invocation.commandId,
+        PropagateEmbeddedControlMessageResponse(
+          Map("worker-a" -> StringResponse("state-a"), "worker-b" -> 
EmptyReturn())
+        )
+      )
+    )
+
+    assert(
+      Await.result(response, Duration.fromSeconds(5)) == 
RetrieveWorkflowStateResponse(
+        Map("worker-a" -> "state-a", "worker-b" -> "")
+      )
+    )
+  }
+
+  it should "include only running region operators in sourceOpToStartProp" in {
+    def mkOp(id: String): PhysicalOp =
+      PhysicalOp(
+        PhysicalOpIdentity(OperatorIdentity(id), "main"),
+        WorkflowIdentity(0),
+        ExecutionIdentity(0),
+        OpExecInitInfo.Empty
+      )
+
+    val runningOp = mkOp("running")
+    val completedOp = mkOp("completed")
+    val runningRegion = Region(
+      RegionIdentity(1),
+      physicalOps = Set(runningOp),
+      physicalLinks = Set.empty,
+      ports = Set(GlobalPortIdentity(runningOp.id, PortIdentity(), input = 
false))
+    )
+    val completedRegion = Region(
+      RegionIdentity(2),
+      physicalOps = Set(completedOp),
+      physicalLinks = Set.empty,
+      ports = Set(GlobalPortIdentity(completedOp.id, PortIdentity(), input = 
false))
+    )
+    val (init, sent) = newFixture()
+    val runningExec = 
init.cp.workflowExecution.initRegionExecution(runningRegion)
+    runningExec
+      .initOperatorExecution(runningOp.id)
+      .initWorkerExecution(
+        VirtualIdentityUtils.createWorkerIdentity(WorkflowIdentity(0), 
runningOp.id, 0)
+      )
+    val completedExec = 
init.cp.workflowExecution.initRegionExecution(completedRegion)
+    completedExec
+      .initOperatorExecution(completedOp.id)
+      .initWorkerExecution(
+        VirtualIdentityUtils.createWorkerIdentity(WorkflowIdentity(0), 
completedOp.id, 0)
+      )
+      .getOutputPortExecution(PortIdentity())
+      .setCompleted()
+    init.cp.workflowScheduler.physicalPlan = PhysicalPlan(Set(runningOp, 
completedOp), Set.empty)
+
+    init.retrieveWorkflowState(EmptyRequest(), rpcContext)
+
+    val req = dispatchedRequest(sent)
+    assert(req.sourceOpToStartProp.toSet == Set(runningOp.id))
+    assert(req.targetOps.toSet == Set(runningOp.id, completedOp.id))
+  }
 }
diff --git 
a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionSpec.scala
 
b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionSpec.scala
index 0aacaaeae2..42236132be 100644
--- 
a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionSpec.scala
+++ 
b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/RegionSpec.scala
@@ -28,12 +28,21 @@ import org.apache.texera.amber.core.virtualidentity.{
 }
 import org.apache.texera.amber.core.workflow.{
   GlobalPortIdentity,
+  InputPort,
+  OutputPort,
   PhysicalLink,
   PhysicalOp,
   PortIdentity
 }
+import org.apache.texera.amber.engine.architecture.scheduling.config.{
+  IntermediateInputPortConfig,
+  OutputPortConfig,
+  ResourceConfig
+}
 import org.scalatest.flatspec.AnyFlatSpec
 
+import java.net.URI
+
 class RegionSpec extends AnyFlatSpec {
 
   private def physicalOpId(opId: String): PhysicalOpIdentity =
@@ -47,6 +56,11 @@ class RegionSpec extends AnyFlatSpec {
       OpExecInitInfo.Empty
     )
 
+  private def wiredOp(opId: String): PhysicalOp =
+    op(opId)
+      .withInputPorts(List(InputPort(PortIdentity(0))))
+      .withOutputPorts(List(OutputPort(PortIdentity(0))))
+
   private def link(fromOp: String, toOp: String): PhysicalLink =
     PhysicalLink(physicalOpId(fromOp), PortIdentity(0), physicalOpId(toOp), 
PortIdentity(0))
 
@@ -114,6 +128,17 @@ class RegionSpec extends AnyFlatSpec {
     assert(region.getSourceOperators == Set(a, b))
   }
 
+  it should "exclude operators fed by internal links and keep operators fed 
only from outside" in {
+    val internalLink = link("a", "b")
+    val externalLink = link("external", "c")
+    val a = wiredOp("a").addOutputLink(internalLink)
+    val b = wiredOp("b").addInputLink(internalLink)
+    val c = wiredOp("c").addInputLink(externalLink)
+    val region = Region(RegionIdentity(1), Set(a, b, c), Set(internalLink))
+
+    assert(region.getSourceOperators == Set(a, c))
+  }
+
   "Region.getStarterOperators" should "match getSourceOperators when no 
resource config is provided" in {
     val a = op("a")
     val b = op("b")
@@ -121,4 +146,31 @@ class RegionSpec extends AnyFlatSpec {
 
     assert(region.getStarterOperators == region.getSourceOperators)
   }
+
+  it should "promote only operators reading from materialized input ports in 
resourceConfig" in {
+    val ab = link("a", "b")
+    val ac = link("a", "c")
+    val a = wiredOp("a").addOutputLink(ab).addOutputLink(ac)
+    val b = wiredOp("b").addInputLink(ab)
+    val c = wiredOp("c").addInputLink(ac)
+    val baseUri = new URI("ram:///materialized/")
+    val resourceConfig = ResourceConfig(
+      portConfigs = Map(
+        GlobalPortIdentity(b.id, PortIdentity(0), input = true) ->
+          IntermediateInputPortConfig(List(baseUri)),
+        GlobalPortIdentity(c.id, PortIdentity(0), input = true) ->
+          IntermediateInputPortConfig(List.empty),
+        GlobalPortIdentity(c.id, PortIdentity(0), input = false) ->
+          OutputPortConfig(baseUri)
+      )
+    )
+    val region = Region(
+      RegionIdentity(1),
+      Set(a, b, c),
+      Set(ab, ac),
+      resourceConfig = Some(resourceConfig)
+    )
+
+    assert(region.getStarterOperators == Set(a, b))
+  }
 }
diff --git 
a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/ScheduleSpec.scala
 
b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/ScheduleSpec.scala
index 81ca54c1dd..95dda9b675 100644
--- 
a/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/ScheduleSpec.scala
+++ 
b/amber/src/test/scala/org/apache/texera/amber/engine/architecture/scheduling/ScheduleSpec.scala
@@ -26,7 +26,8 @@ import org.apache.texera.amber.core.virtualidentity.{
   PhysicalOpIdentity,
   WorkflowIdentity
 }
-import org.apache.texera.amber.core.workflow.PhysicalOp
+import org.apache.texera.amber.core.workflow.{PhysicalOp, PhysicalPlan, 
WorkflowContext}
+import org.apache.texera.common.config.ApplicationConfig
 import org.scalatest.flatspec.AnyFlatSpec
 
 class ScheduleSpec extends AnyFlatSpec {
@@ -86,4 +87,48 @@ class ScheduleSpec extends AnyFlatSpec {
     }
   }
 
+  "ScheduleGenerator.generateScheduleFromRegionPlan" should "return an empty 
schedule for an empty region plan" in {
+    val generator = new ScheduleGenerator(
+      new WorkflowContext(),
+      PhysicalPlan(Set.empty, Set.empty)
+    ) {
+      override def generate(): (Schedule, PhysicalPlan) = 
(Schedule(Map.empty), physicalPlan)
+    }
+
+    val schedule = 
generator.generateScheduleFromRegionPlan(RegionPlan(Set.empty, Set.empty))
+    assert(schedule.getRegions.isEmpty)
+    assert(!schedule.hasNext)
+  }
+
+  it should "schedule a DAG of regions in topological batches capped by 
maxConcurrentRegions" in {
+    val r0 = region(0, "a")
+    val r1 = region(1, "b")
+    val r2 = region(2, "c")
+    val r3 = region(3, "d")
+    val plan = RegionPlan(
+      Set(r0, r1, r2, r3),
+      Set(
+        RegionLink(r0.id, r1.id),
+        RegionLink(r0.id, r2.id),
+        RegionLink(r1.id, r3.id),
+        RegionLink(r2.id, r3.id)
+      )
+    )
+    val generator = new ScheduleGenerator(
+      new WorkflowContext(),
+      PhysicalPlan(Set.empty, Set.empty)
+    ) {
+      override def generate(): (Schedule, PhysicalPlan) = 
(Schedule(Map.empty), physicalPlan)
+    }
+
+    val levels = generator.generateScheduleFromRegionPlan(plan).toList
+    val order = levels.flatten
+    assert(levels.forall(_.size <= ApplicationConfig.maxConcurrentRegions))
+    assert(order.toSet == Set(r0, r1, r2, r3))
+    assert(order.indexOf(r0) < order.indexOf(r1))
+    assert(order.indexOf(r0) < order.indexOf(r2))
+    assert(order.indexOf(r1) < order.indexOf(r3))
+    assert(order.indexOf(r2) < order.indexOf(r3))
+  }
+
 }
diff --git 
a/amber/src/test/scala/org/apache/texera/amber/engine/common/FriesReconfigurationAlgorithmSpec.scala
 
b/amber/src/test/scala/org/apache/texera/amber/engine/common/FriesReconfigurationAlgorithmSpec.scala
index a15cc1d316..a99b8dc005 100644
--- 
a/amber/src/test/scala/org/apache/texera/amber/engine/common/FriesReconfigurationAlgorithmSpec.scala
+++ 
b/amber/src/test/scala/org/apache/texera/amber/engine/common/FriesReconfigurationAlgorithmSpec.scala
@@ -404,4 +404,49 @@ class FriesReconfigurationAlgorithmSpec extends 
AnyFlatSpec {
     assert(component.sources == Set(physicalOpId("m0"), physicalOpId("m1")))
     assert(component.reconfigurations == request.reconfiguration.toSet)
   }
+
+  it should "return no components for an empty reconfiguration request" in {
+    val region = buildRegion(1, Set(op("a"), op("b")), Set(link("a", "b")))
+    val request = reconfigureRequest()
+
+    val components =
+      
FriesReconfigurationAlgorithm.getReconfigurations(managerWithRegions(region), 
request)
+
+    assert(components.isEmpty)
+  }
+
+  it should "keep multiple reconfigured operators in the same connected 
component" in {
+    val region = buildRegion(
+      1,
+      Set(op("a"), op("b"), op("c")),
+      Set(link("a", "b"), link("b", "c"))
+    )
+    val request = reconfigureRequest("a", "c")
+
+    val components =
+      
FriesReconfigurationAlgorithm.getReconfigurations(managerWithRegions(region), 
request)
+
+    val component = singleComponent(components)
+    assert(component.scope == Set(physicalOpId("a"), physicalOpId("b"), 
physicalOpId("c")))
+    assert(component.sources == Set(physicalOpId("a")))
+    assert(component.reconfigurations == request.reconfiguration.toSet)
+  }
+
+  it should "ignore unknown target operators when splitting multiple 
disconnected components" in {
+    val region = buildRegion(
+      1,
+      Set(op("a1"), op("b1"), op("a2"), op("b2")),
+      Set(link("a1", "b1"), link("a2", "b2"))
+    )
+    val request = reconfigureRequest("b1", "b2", "missing")
+
+    val components =
+      
FriesReconfigurationAlgorithm.getReconfigurations(managerWithRegions(region), 
request)
+
+    assert(components.size == 2)
+    val componentOfB1 = 
components.find(_.scope.contains(physicalOpId("b1"))).get
+    val componentOfB2 = 
components.find(_.scope.contains(physicalOpId("b2"))).get
+    assert(componentOfB1.reconfigurations.map(_.targetOpId) == 
Set(physicalOpId("b1")))
+    assert(componentOfB2.reconfigurations.map(_.targetOpId) == 
Set(physicalOpId("b2")))
+  }
 }
diff --git 
a/amber/src/test/scala/org/apache/texera/web/service/ExecutionConsoleServiceSpec.scala
 
b/amber/src/test/scala/org/apache/texera/web/service/ExecutionConsoleServiceSpec.scala
index ce88a46e6e..c9cb96c1e0 100644
--- 
a/amber/src/test/scala/org/apache/texera/web/service/ExecutionConsoleServiceSpec.scala
+++ 
b/amber/src/test/scala/org/apache/texera/web/service/ExecutionConsoleServiceSpec.scala
@@ -31,14 +31,23 @@ import 
org.apache.texera.amber.engine.architecture.rpc.controlcommands.{
   ConsoleMessageType,
   DebugCommandRequest => AmberDebugCommandRequest
 }
-import 
org.apache.texera.amber.engine.architecture.rpc.controlreturns.EmptyReturn
+import org.apache.texera.amber.engine.architecture.rpc.controlreturns.{
+  EmptyReturn,
+  EvaluatedValue,
+  TypedValue
+}
 import 
org.apache.texera.amber.engine.architecture.rpc.coordinatorservice.CoordinatorServiceFs2Grpc
 import org.apache.texera.amber.engine.common.client.AmberClient
-import 
org.apache.texera.amber.engine.common.executionruntimestate.ExecutionConsoleStore
+import org.apache.texera.amber.engine.common.executionruntimestate.{
+  EvaluatedValueList,
+  ExecutionConsoleStore,
+  OperatorConsole
+}
 import org.apache.texera.web.WebsocketInput
 import org.apache.texera.web.model.websocket.event.TexeraWebSocketEvent
 import org.apache.texera.web.model.websocket.event.python.ConsoleUpdateEvent
 import org.apache.texera.web.model.websocket.request.python.DebugCommandRequest
+import 
org.apache.texera.web.model.websocket.response.python.PythonExpressionEvaluateResponse
 import org.apache.texera.web.storage.ExecutionStateStore
 import org.scalamock.scalatest.MockFactory
 import org.scalatest.BeforeAndAfterAll
@@ -380,6 +389,47 @@ class ExecutionConsoleServiceSpec
     }
   }
 
+  it should "emit PythonExpressionEvaluateResponse only for newly added 
evaluation keys" in {
+    withFixture { f =>
+      val val1 =
+        EvaluatedValue(Some(TypedValue("x", "r1", "1", "int", expandable = 
false)), Seq.empty)
+      val val2 =
+        EvaluatedValue(Some(TypedValue("y", "r2", "2", "int", expandable = 
false)), Seq.empty)
+      val val3 =
+        EvaluatedValue(Some(TypedValue("z", "r3", "3", "int", expandable = 
false)), Seq.empty)
+
+      val batches = ListBuffer.empty[Iterable[TexeraWebSocketEvent]]
+      val sub = f.stateStore.consoleStore.getWebsocketEventObservable
+        .subscribe((batch: Iterable[TexeraWebSocketEvent]) => batches += batch)
+
+      try {
+        f.stateStore.consoleStore.updateState { store =>
+          store.addOperatorConsole(
+            "udf1" -> OperatorConsole(evaluateExprResults =
+              Map("x" -> EvaluatedValueList(Seq(val1)), "y" -> 
EvaluatedValueList(Seq(val2)))
+            )
+          )
+        }
+        f.stateStore.consoleStore.updateState { store =>
+          val current = store.operatorConsole("udf1")
+          store.addOperatorConsole(
+            "udf1" -> current.addEvaluateExprResults("z" -> 
EvaluatedValueList(Seq(val3)))
+          )
+        }
+      } finally sub.dispose()
+
+      val firstEval = batches.head.collect {
+        case e: PythonExpressionEvaluateResponse => e.expression -> e.values
+      }.toMap
+      firstEval shouldBe Map("x" -> Seq(val1), "y" -> Seq(val2))
+
+      val secondEval = batches.last.collect {
+        case e: PythonExpressionEvaluateResponse => e.expression -> e.values
+      }.toMap
+      secondEval shouldBe Map("z" -> Seq(val3))
+    }
+  }
+
   "the console message callback" should "file a message under the logical 
operator id" in {
     // The worker id carries the physical layer and worker index; the frontend 
console is keyed by
     // the logical operator, so anything else silently strands the output.
diff --git 
a/amber/src/test/scala/org/apache/texera/web/service/ExecutionStatsServiceSpec.scala
 
b/amber/src/test/scala/org/apache/texera/web/service/ExecutionStatsServiceSpec.scala
index acc34e0e7c..a02208b0e7 100644
--- 
a/amber/src/test/scala/org/apache/texera/web/service/ExecutionStatsServiceSpec.scala
+++ 
b/amber/src/test/scala/org/apache/texera/web/service/ExecutionStatsServiceSpec.scala
@@ -373,6 +373,34 @@ class ExecutionStatsServiceSpec
     }
   }
 
+  it should "sum multi-port output metrics and zero-out empty ports 
consistently" in {
+    withService { f =>
+      val batches = recordBatches(f.stateStore.statsStore) {
+        f.client.fire(
+          ExecutionStatsUpdate(
+            Map(
+              "multiOut" -> metrics(
+                RUNNING,
+                inputs = Seq.empty,
+                outputs = Seq((0, 2L, 20L), (1, 5L, 55L)),
+                numWorkers = 3
+              )
+            )
+          )
+        )
+      }
+
+      val published = statisticsEvents(batches.flatten)
+      val multiOut = published("multiOut")
+      multiOut.aggregatedInputRowCount shouldBe 0L
+      multiOut.aggregatedInputSize shouldBe 0L
+      multiOut.inputPortMetrics shouldBe Map.empty
+      multiOut.aggregatedOutputRowCount shouldBe 7L
+      multiOut.aggregatedOutputSize shouldBe 75L
+      multiOut.outputPortMetrics shouldBe Map("0" -> 2L, "1" -> 5L)
+    }
+  }
+
   "the worker assignment callback" should
     "publish one event per operator carrying that operator's workers" in {
     withService { f =>
@@ -582,4 +610,28 @@ class ExecutionStatsServiceSpec
       }
     }
   }
+
+  it should "sum multi-port input and output counts and sizes when persisting 
statistics" in {
+    withService { f =>
+      val multiPort = metrics(
+        RUNNING,
+        inputs = Seq((0, 2L, 20L), (1, 3L, 35L)),
+        outputs = Seq((0, 4L, 40L), (1, 5L, 55L)),
+        numWorkers = 2
+      )
+
+      f.client.fire(RuntimeStatisticsPersist(Map("opMulti" -> multiPort)))
+      awaitPersist(f.service)
+      f.client.fire(ExecutionStateUpdate(COMPLETED))
+
+      val rows = persistedRows()
+      rows should have size 1
+      val row = rows.head
+      row.getField[String]("operatorId") shouldBe "opMulti"
+      row.getField[Long]("inputTupleCnt") shouldBe 5L
+      row.getField[Long]("inputTupleSize") shouldBe 55L
+      row.getField[Long]("outputTupleCnt") shouldBe 9L
+      row.getField[Long]("outputTupleSize") shouldBe 95L
+    }
+  }
 }

Reply via email to