Copilot commented on code in PR #4220:
URL: https://github.com/apache/texera/pull/4220#discussion_r2866967065


##########
amber/src/main/scala/org/apache/texera/amber/engine/architecture/controller/promisehandlers/ReconfigurationHandler.scala:
##########
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.texera.amber.engine.architecture.controller.promisehandlers
+
+import com.twitter.util.Future
+import org.apache.texera.amber.core.virtualidentity.{
+  ChannelIdentity,
+  EmbeddedControlMessageIdentity
+}
+import 
org.apache.texera.amber.engine.architecture.controller.ControllerAsyncRPCHandlerInitializer
+import 
org.apache.texera.amber.engine.architecture.rpc.controlcommands.EmbeddedControlMessageType.ALL_ALIGNMENT
+import org.apache.texera.amber.engine.architecture.rpc.controlcommands.{
+  AsyncRPCContext,
+  WorkflowReconfigureRequest
+}
+import 
org.apache.texera.amber.engine.architecture.rpc.controlreturns.EmptyReturn
+import org.apache.texera.amber.engine.common.FriesReconfigurationAlgorithm
+import org.apache.texera.amber.engine.common.virtualidentity.util.CONTROLLER
+import org.apache.texera.amber.util.VirtualIdentityUtils
+import 
org.apache.texera.amber.engine.architecture.rpc.workerservice.WorkerServiceGrpc.METHOD_UPDATE_EXECUTOR
+
+import scala.collection.mutable
+
+trait ReconfigurationHandler {
+  this: ControllerAsyncRPCHandlerInitializer =>
+
+  override def reconfigureWorkflow(
+      msg: WorkflowReconfigureRequest,
+      ctx: AsyncRPCContext
+  ): Future[EmptyReturn] = {
+    if (
+      msg.reconfiguration.exists(req =>
+        
cp.workflowScheduler.physicalPlan.getOperator(req.targetOpId).isSourceOperator
+      )
+    ) {
+      throw new IllegalStateException(
+        "Reconfiguration cannot be applied to source operators"
+      )
+    }
+    val futures = mutable.ArrayBuffer[Future[_]]()
+    val friesComponents =
+      
FriesReconfigurationAlgorithm.getReconfigurations(cp.workflowExecutionCoordinator,
 msg)
+    friesComponents.foreach { friesComponent =>
+      if (friesComponent.scope.size == 1) {
+        val updateExecutorRequest = friesComponent.reconfigurations.head
+        val workerIds = cp.workflowExecution
+          .getLatestOperatorExecution(updateExecutorRequest.targetOpId)
+          .getWorkerIds
+        workerIds.foreach { worker =>
+          futures.append(workerInterface.updateExecutor(updateExecutorRequest, 
mkContext(worker)))
+        }
+      } 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(CONTROLLER, worker, isControl = true),
+              ChannelIdentity(worker, CONTROLLER, isControl = true)
+            )
+          }
+        }
+        val finalScope = channelScope ++ controlChannels
+        val cmdMapping =
+          friesComponent.reconfigurations.flatMap { updateReq =>
+            val workers =
+              
cp.workflowExecution.getLatestOperatorExecution(updateReq.targetOpId).getWorkerIds
+            workers.map(worker =>
+              worker.name -> createInvocation(
+                METHOD_UPDATE_EXECUTOR.getBareMethodName,
+                updateReq,
+                worker
+              )
+            )
+          }.toMap
+        futures += cmdMapping.map(_._2._2)

Review Comment:
   `futures += cmdMapping.map(_._2._2)` attempts to add an 
`Iterable[Future[_]]` as a single element to `ArrayBuffer[Future[_]]`, which 
will not type-check (and won’t collect the invocation futures as intended). Use 
`++=` (or append each future) to add the individual futures from the mapping.
   ```suggestion
           futures ++= cmdMapping.map(_._2._2)
   ```



##########
amber/src/main/scala/org/apache/texera/amber/engine/architecture/worker/promisehandlers/UpdateExecutorHandler.scala:
##########
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.texera.amber.engine.architecture.worker.promisehandlers
+
+import com.twitter.util.Future
+import org.apache.texera.amber.engine.architecture.rpc.controlcommands.{
+  AsyncRPCContext,
+  UpdateExecutorRequest
+}
+import 
org.apache.texera.amber.engine.architecture.rpc.controlreturns.EmptyReturn
+import 
org.apache.texera.amber.engine.architecture.worker.DataProcessorRPCHandlerInitializer
+import org.apache.texera.amber.util.VirtualIdentityUtils
+
+trait UpdateExecutorHandler {
+  this: DataProcessorRPCHandlerInitializer =>
+
+  override def updateExecutor(
+      request: UpdateExecutorRequest,
+      ctx: AsyncRPCContext
+  ): Future[EmptyReturn] = {
+    val workerIdx = VirtualIdentityUtils.getWorkerIndex(actorId)

Review Comment:
   `updateExecutor` replaces `dp.executor` via `setupExecutor` without closing 
the previous executor instance. Since `OperatorExecutor` has a `close()` hook, 
consider closing the old executor before overwriting it to avoid leaking 
resources (files, connections, timers) during reconfiguration.
   ```suggestion
       val workerIdx = VirtualIdentityUtils.getWorkerIndex(actorId)
       // Close the existing executor (if any) before replacing it to avoid 
resource leaks.
       val oldExecutor = dp.executor
       if (oldExecutor != null) {
         oldExecutor.close()
       }
   ```



##########
amber/src/test/scala/org/apache/texera/amber/engine/e2e/ModifyLogicSpec.scala:
##########
@@ -0,0 +1,313 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.texera.amber.engine.e2e
+
+import com.twitter.util.{Await, Duration, Promise}
+import com.typesafe.scalalogging.Logger
+import org.apache.pekko.actor.{ActorSystem, Props}
+import org.apache.pekko.testkit.{ImplicitSender, TestKit}
+import org.apache.pekko.util.Timeout
+import org.apache.texera.amber.clustering.SingleNodeListener
+import org.apache.texera.amber.core.executor.{OpExecInitInfo, OpExecWithCode}
+import org.apache.texera.amber.core.storage.DocumentFactory
+import org.apache.texera.amber.core.storage.model.VirtualDocument
+import org.apache.texera.amber.core.tuple.Tuple
+import org.apache.texera.amber.core.virtualidentity.OperatorIdentity
+import org.apache.texera.amber.core.workflow.{PortIdentity, WorkflowContext}
+import org.apache.texera.amber.engine.architecture.controller.{
+  ControllerConfig,
+  ExecutionStateUpdate
+}
+import org.apache.texera.amber.engine.architecture.rpc.controlcommands.{
+  EmptyRequest,
+  UpdateExecutorRequest,
+  WorkflowReconfigureRequest
+}
+import 
org.apache.texera.amber.engine.architecture.rpc.controlreturns.WorkflowAggregatedState.COMPLETED
+import org.apache.texera.amber.engine.common.AmberRuntime
+import org.apache.texera.amber.engine.common.client.AmberClient
+import org.apache.texera.amber.engine.e2e.TestUtils.{
+  cleanupWorkflowExecutionData,
+  initiateTexeraDBForTestCases,
+  setUpWorkflowExecutionData
+}
+import org.apache.texera.amber.operator.{LogicalOp, TestOperators}
+import 
org.apache.texera.web.resource.dashboard.user.workflow.WorkflowExecutionsResource.getResultUriByLogicalPortId
+import org.apache.texera.workflow.LogicalLink
+import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach, Outcome, Retries}
+import org.scalatest.flatspec.AnyFlatSpecLike
+
+import scala.concurrent.duration._
+
+class ModifyLogicSpec
+    extends TestKit(ActorSystem("ModifyLogicSpec", AmberRuntime.akkaConfig))
+    with ImplicitSender
+    with AnyFlatSpecLike
+    with BeforeAndAfterAll
+    with BeforeAndAfterEach
+    with Retries {
+
+  /**
+    * This block retries each test once if it fails.
+    * In the CI environment, there is a chance that executeWorkflow does not 
receive "COMPLETED" status.
+    * Until we find the root cause of this issue, we use a retry mechanism 
here to stablize CI runs.
+    */
+  override def withFixture(test: NoArgTest): Outcome =
+    withRetry { super.withFixture(test) }
+
+  implicit val timeout: Timeout = Timeout(5.seconds)
+
+  val logger = Logger("ModifyLogicSpecLogger")
+  val ctx = new WorkflowContext()
+
+  override protected def beforeEach(): Unit = {
+    setUpWorkflowExecutionData()
+  }
+
+  override protected def afterEach(): Unit = {
+    cleanupWorkflowExecutionData()
+  }
+
+  override def beforeAll(): Unit = {
+    system.actorOf(Props[SingleNodeListener](), "cluster-info")
+    // These test cases access postgres in CI, but occasionally the jdbc 
driver cannot be found during CI run.
+    // Explicitly load the JDBC driver to avoid flaky CI failures.
+    Class.forName("org.postgresql.Driver")
+    initiateTexeraDBForTestCases()
+  }
+
+  override def afterAll(): Unit = {
+    TestKit.shutdownActorSystem(system)
+  }
+
+  def shouldReconfigure(
+      operators: List[LogicalOp],
+      links: List[LogicalLink],
+      targetOps: Seq[LogicalOp],
+      newOpExecInitInfo: OpExecInitInfo
+  ): Map[OperatorIdentity, List[Tuple]] = {
+    val workflow =
+      TestUtils.buildWorkflow(operators, links, ctx)
+    val client =
+      new AmberClient(
+        system,
+        workflow.context,
+        workflow.physicalPlan,
+        ControllerConfig.default,
+        error => {}
+      )
+    val completion = Promise[Unit]()
+    var result: Map[OperatorIdentity, List[Tuple]] = null
+    client
+      .registerCallback[ExecutionStateUpdate](evt => {
+        if (evt.state == COMPLETED) {
+          result = workflow.logicalPlan.getTerminalOperatorIds
+            .filter(terminalOpId => {
+              val uri = getResultUriByLogicalPortId(
+                workflow.context.executionId,
+                terminalOpId,
+                PortIdentity()
+              )
+              uri.nonEmpty
+            })
+            .map(terminalOpId => {
+              //TODO: remove the delay after fixing the issue of reporting 
"completed" status too early.
+              Thread.sleep(1000)
+              val uri = getResultUriByLogicalPortId(
+                workflow.context.executionId,
+                terminalOpId,
+                PortIdentity()
+              ).get
+              terminalOpId -> DocumentFactory
+                .openDocument(uri)
+                ._1
+                .asInstanceOf[VirtualDocument[Tuple]]
+                .get()
+                .toList
+            })
+            .toMap
+          completion.setDone()
+        }
+      })
+    Await.result(client.controllerInterface.startWorkflow(EmptyRequest(), ()))
+    Await.result(client.controllerInterface.pauseWorkflow(EmptyRequest(), ()))
+    Thread.sleep(4000)
+    val physicalOps = targetOps.flatMap(op =>
+      workflow.physicalPlan.getPhysicalOpsOfLogicalOp(op.operatorIdentifier)
+    )
+    Await.result(
+      client.controllerInterface.reconfigureWorkflow(
+        WorkflowReconfigureRequest(
+          reconfiguration = physicalOps.map(op => UpdateExecutorRequest(op.id, 
newOpExecInitInfo)),
+          reconfigurationId = "test-reconfigure-1"
+        ),
+        ()
+      )
+    )
+    Await.result(client.controllerInterface.resumeWorkflow(EmptyRequest(), ()))
+    Thread.sleep(400)
+    Await.result(completion, Duration.fromMinutes(1))
+    result
+  }
+
+  "Engine" should "be able to modify a python UDF worker in workflow" in {
+    val sourceOpDesc = TestOperators.smallCsvScanOpDesc()
+    val udfOpDesc = TestOperators.pythonOpDesc()
+    val code = """
+                 |from pytexera import *
+                 |
+                 |class ProcessTupleOperator(UDFOperatorV2):
+                 |    @overrides
+                 |    def process_tuple(self, tuple_: Tuple, port: int) -> 
Iterator[Optional[TupleLike]]:
+                 |        tuple_['Region'] = tuple_['Region'] + '_reconfigured'
+                 |        yield tuple_
+                 |""".stripMargin
+
+    val result = shouldReconfigure(
+      List(sourceOpDesc, udfOpDesc),
+      List(
+        LogicalLink(
+          sourceOpDesc.operatorIdentifier,
+          PortIdentity(),
+          udfOpDesc.operatorIdentifier,
+          PortIdentity()
+        )
+      ),
+      Seq(udfOpDesc),
+      OpExecWithCode(code, "python")
+    )
+    assert(result(udfOpDesc.operatorIdentifier).exists { t =>
+      t.getField("Region").asInstanceOf[String].contains("_reconfigured")
+    })
+  }
+
+  "Engine" should "be able to modify a java operator in workflow" in {
+    val sourceOpDesc = TestOperators.mediumCsvScanOpDesc()
+    val keywordMatchNoneOpDesc = TestOperators.keywordSearchOpDesc("Region", 
"ShouldMatchNone")
+    val keywordMatchManyOpDesc = TestOperators.keywordSearchOpDesc("Region", 
"Asia")
+    val result = shouldReconfigure(
+      List(sourceOpDesc, keywordMatchNoneOpDesc),
+      List(
+        LogicalLink(
+          sourceOpDesc.operatorIdentifier,
+          PortIdentity(),
+          keywordMatchNoneOpDesc.operatorIdentifier,
+          PortIdentity()
+        )
+      ),
+      Seq(keywordMatchNoneOpDesc),
+      keywordMatchManyOpDesc.getPhysicalOp(ctx.workflowId, 
ctx.executionId).opExecInitInfo
+    )
+    assert(result(keywordMatchNoneOpDesc.operatorIdentifier).nonEmpty)
+  }
+
+  "Engine" should "not be able to modify a source operator in workflow" in {
+    val sourceOpDesc = TestOperators.mediumCsvScanOpDesc()
+    val sourceOpDesc2 = TestOperators.mediumCsvScanOpDesc()
+    val keywordMatchNoneOpDesc = TestOperators.keywordSearchOpDesc("Region", 
"ShouldMatchNone")
+    val ex = intercept[Throwable] {
+      shouldReconfigure(
+        List(sourceOpDesc, keywordMatchNoneOpDesc),
+        List(
+          LogicalLink(
+            sourceOpDesc.operatorIdentifier,
+            PortIdentity(),
+            keywordMatchNoneOpDesc.operatorIdentifier,
+            PortIdentity()
+          )
+        ),
+        Seq(sourceOpDesc),
+        sourceOpDesc2.getPhysicalOp(ctx.workflowId, 
ctx.executionId).opExecInitInfo
+      )
+    }
+    assert(
+      ex.getMessage == "java.lang.IllegalStateException: Reconfiguration 
cannot be applied to source operators"
+    )

Review Comment:
   This test asserts the full exception message string including the exception 
class prefix. That makes the test brittle (wrapping/serialization can change 
the message format). Prefer asserting on the exception type and/or that the 
message contains the expected substring (e.g., "Reconfiguration cannot be 
applied to source operators").



##########
amber/src/test/scala/org/apache/texera/amber/engine/e2e/ModifyLogicSpec.scala:
##########
@@ -0,0 +1,313 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.texera.amber.engine.e2e
+
+import com.twitter.util.{Await, Duration, Promise}
+import com.typesafe.scalalogging.Logger
+import org.apache.pekko.actor.{ActorSystem, Props}
+import org.apache.pekko.testkit.{ImplicitSender, TestKit}
+import org.apache.pekko.util.Timeout
+import org.apache.texera.amber.clustering.SingleNodeListener
+import org.apache.texera.amber.core.executor.{OpExecInitInfo, OpExecWithCode}
+import org.apache.texera.amber.core.storage.DocumentFactory
+import org.apache.texera.amber.core.storage.model.VirtualDocument
+import org.apache.texera.amber.core.tuple.Tuple
+import org.apache.texera.amber.core.virtualidentity.OperatorIdentity
+import org.apache.texera.amber.core.workflow.{PortIdentity, WorkflowContext}
+import org.apache.texera.amber.engine.architecture.controller.{
+  ControllerConfig,
+  ExecutionStateUpdate
+}
+import org.apache.texera.amber.engine.architecture.rpc.controlcommands.{
+  EmptyRequest,
+  UpdateExecutorRequest,
+  WorkflowReconfigureRequest
+}
+import 
org.apache.texera.amber.engine.architecture.rpc.controlreturns.WorkflowAggregatedState.COMPLETED
+import org.apache.texera.amber.engine.common.AmberRuntime
+import org.apache.texera.amber.engine.common.client.AmberClient
+import org.apache.texera.amber.engine.e2e.TestUtils.{
+  cleanupWorkflowExecutionData,
+  initiateTexeraDBForTestCases,
+  setUpWorkflowExecutionData
+}
+import org.apache.texera.amber.operator.{LogicalOp, TestOperators}
+import 
org.apache.texera.web.resource.dashboard.user.workflow.WorkflowExecutionsResource.getResultUriByLogicalPortId
+import org.apache.texera.workflow.LogicalLink
+import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach, Outcome, Retries}
+import org.scalatest.flatspec.AnyFlatSpecLike
+
+import scala.concurrent.duration._
+
+class ModifyLogicSpec
+    extends TestKit(ActorSystem("ModifyLogicSpec", AmberRuntime.akkaConfig))
+    with ImplicitSender
+    with AnyFlatSpecLike
+    with BeforeAndAfterAll
+    with BeforeAndAfterEach
+    with Retries {
+
+  /**
+    * This block retries each test once if it fails.
+    * In the CI environment, there is a chance that executeWorkflow does not 
receive "COMPLETED" status.
+    * Until we find the root cause of this issue, we use a retry mechanism 
here to stablize CI runs.

Review Comment:
   Typo in comment: "stablize" should be "stabilize".
   ```suggestion
       * Until we find the root cause of this issue, we use a retry mechanism 
here to stabilize CI runs.
   ```



##########
amber/src/main/protobuf/org/apache/texera/amber/engine/architecture/rpc/controlcommands.proto:
##########
@@ -40,12 +39,12 @@ message ControlRequest {
     TakeGlobalCheckpointRequest takeGlobalCheckpointRequest = 2;
     DebugCommandRequest debugCommandRequest = 3;
     EvaluatePythonExpressionRequest evaluatePythonExpressionRequest = 4;
-    ModifyLogicRequest modifyLogicRequest = 5;
-    RetryWorkflowRequest retryWorkflowRequest = 6;
-    ConsoleMessageTriggeredRequest consoleMessageTriggeredRequest = 8;
-    PortCompletedRequest portCompletedRequest = 9;
-    WorkerStateUpdatedRequest workerStateUpdatedRequest = 10;
-    LinkWorkersRequest linkWorkersRequest = 11;
+    RetryWorkflowRequest retryWorkflowRequest = 5;
+    ConsoleMessageTriggeredRequest consoleMessageTriggeredRequest = 6;
+    PortCompletedRequest portCompletedRequest = 7;
+    WorkerStateUpdatedRequest workerStateUpdatedRequest = 8;
+    LinkWorkersRequest linkWorkersRequest = 9;
+    WorkflowReconfigureRequest workflowReconfigureRequest = 10;

Review Comment:
   The numeric tags in the `ControlRequest` oneof were renumbered (e.g., 
`RetryWorkflowRequest` moved to 5, etc.). In protobuf, field numbers are part 
of the wire format and should not be renumbered/reused; removed tags should be 
marked `reserved` to avoid breaking compatibility and accidental reuse.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to