Xiao-zhen-Liu commented on code in PR #9364:
URL: https://github.com/apache/texera/pull/9364#discussion_r4520714318


##########
amber/src/main/scala/org/apache/texera/amber/engine/architecture/pythonworker/PythonProxyClient.scala:
##########
@@ -155,13 +154,35 @@ class PythonProxyClient(portNumberPromise: Promise[Int], 
val actorId: ActorVirtu
     schemaRoot.clear()
     writer.completed()
 
-    // for calculating sender credits - get back number of batches in Python 
worker queue
-    val ackMsgBuf: ArrowBuf = flightListener.poll(5, 
TimeUnit.SECONDS).getApplicationMetadata
+    finishPut(writer, flightListener)
+
+    flightListener.close()
+  }
+
+  /**
+    * Finishes a put: reads the Python queue size that Python returns for it, 
for sender
+    * credits, then the put's own status. Waits as long as it takes: a busy 
Python process (one
+    * holding the GIL in a long native call, for example) may answer late, and 
a dead one fails
+    * the call instead, which the worker reports along with the exit it 
observes on its own.
+    * A put that ends without its ack, or fails after it, ends the client with 
that error.
+    */
+  private def finishPut(
+      writer: FlightClient.ClientStreamListener,
+      flightListener: SyncPutListener
+  ): Unit = {
+    val ack = flightListener.read()
+    if (ack == null) {
+      throw new WorkflowRuntimeException(
+        s"Python worker ${actorId.name} completed a put without acknowledging 
it",
+        Some(actorId)
+      )
+    }
+    val ackMsgBuf: ArrowBuf = ack.getApplicationMetadata

Review Comment:
   Nit: If a put result arrives with no application metadata buffer, reading 
the queue size throws a raw null-pointer error, and any exception thrown here 
also skips closing the listener in the callers. Check for a missing metadata 
buffer and close the listener in a `finally` block here.



##########
amber/src/main/scala/org/apache/texera/amber/engine/architecture/pythonworker/PythonWorkflowWorker.scala:
##########
@@ -169,6 +187,31 @@ class PythonWorkflowWorker(
     )
   }
 
+  override def receive: Receive = handlePythonFailure orElse super.receive
+
+  // Throwing hands the failure to the coordinator's supervisor, which fails 
the execution.
+  private def handlePythonFailure: Receive = {
+    case PythonWorkflowWorker.PythonProcessExited(code) =>
+      throw new WorkflowRuntimeException(
+        
PythonWorkflowWorker.describeUnexpectedExit(workerConfig.workerId.name, code),
+        null,

Review Comment:
   Nit: The two-argument constructor already defaults the cause to `null` (as 
used in the proxy client), so the extra `null` argument here and at line 270 
can be omitted.



##########
amber/src/main/scala/org/apache/texera/amber/engine/architecture/pythonworker/PythonWorkflowWorker.scala:
##########
@@ -169,6 +187,31 @@ class PythonWorkflowWorker(
     )
   }
 
+  override def receive: Receive = handlePythonFailure orElse super.receive
+
+  // Throwing hands the failure to the coordinator's supervisor, which fails 
the execution.
+  private def handlePythonFailure: Receive = {
+    case PythonWorkflowWorker.PythonProcessExited(code) =>
+      throw new WorkflowRuntimeException(
+        
PythonWorkflowWorker.describeUnexpectedExit(workerConfig.workerId.name, code),
+        null,
+        Some(workerConfig.workerId)
+      )
+    case PythonWorkflowWorker.PythonClientFailed(cause) =>
+      val process = pythonServerProcess
+      // When the process is gone, its exit is the reason the client stopped; 
report that.
+      val message =
+        if (process != null && !process.isAlive()) {

Review Comment:
   When the operating system kills the Python process with `SIGKILL` during an 
active Flight call, the kernel closes the socket up to a few milliseconds 
before the JVM updates the process liveness state. If the client failure 
message reaches the actor in that window, the actor sees the process as still 
alive and reports a generic Flight client failure instead of exit code 137 and 
the out-of-memory hint. Wait briefly for the process to exit before choosing 
the error message.



##########
amber/src/main/scala/org/apache/texera/amber/engine/architecture/pythonworker/PythonWorkflowWorker.scala:
##########
@@ -187,10 +230,12 @@ class PythonWorkflowWorker(
   }
 
   override def postStop(): Unit = {
+    stopping = true
     super.postStop()
     try {
-      // try to send shutdown command so that it can gracefully shutdown
-      pythonProxyClient.close()
+      // try to send shutdown command so that it can gracefully shutdown. 
Without a port the
+      // client's constructor would wait forever, and there is no Python side 
to shut down.
+      if (portNumberPromise.isDefined) pythonProxyClient.close()

Review Comment:
   This guards closing the client when the actor stops early, but destroying 
the process seven lines below is still unguarded: when the actor stops before 
the Python process is created (as in the client-only unit tests), shutdown 
throws and logs a null-pointer error. Guard destroying the process against 
`null` too.



##########
amber/src/main/scala/org/apache/texera/amber/engine/architecture/pythonworker/PythonWorkflowWorker.scala:
##########
@@ -262,14 +337,35 @@ class PythonWorkflowWorker(
       workerConfig.largeBinaryBaseUri
     )
 
-    pythonServerProcess = Process(
+    // Python writes straight to this JVM's stdout and stderr, with no copying 
threads in between:
+    // its exit is then known when the process ends, even if a child it 
started (a UDF's
+    // subprocess, for example) still holds those streams open.
+    pythonServerProcess = new ProcessBuilder(
       Seq(
         pythonBin,
         "-u",
         udfEntryScriptPath,
         PythonWorkflowWorker.encodeStartupConfig(startupConfig)
-      )
-    ).run(BasicIO.standard(false))
+      ).asJava
+    ).redirectOutput(ProcessBuilder.Redirect.INHERIT)
+      .redirectError(ProcessBuilder.Redirect.INHERIT)
+      .start()
+    pythonServerProcess.getOutputStream.close() // the worker reads no input
+    watchPythonProcess()
+  }
+
+  /** Reports an exit of the Python process that this actor did not cause. */
+  private def watchPythonProcess(): Unit = {
+    val process = pythonServerProcess
+    val watcher = new Thread(
+      () => {
+        val code = process.waitFor()

Review Comment:
   Nit: Catch thread interruption on this daemon thread so interrupting it 
during shutdown exits cleanly without hitting the uncaught exception handler.



##########
amber/src/main/scala/org/apache/texera/amber/engine/architecture/pythonworker/PythonWorkflowWorker.scala:
##########
@@ -207,9 +252,30 @@ class PythonWorkflowWorker(
   override def initState(): Unit = {
     startProxyServer()
     startPythonProcess()
+    awaitPythonPort()
     startProxyClient()
   }
 
+  /**
+    * Waits for the Python process to report its Flight port, failing if the 
process exits
+    * first: the proxy client's constructor waits for that port with no limit, 
on this actor's
+    * thread, so it must not be built for a process that will never connect.
+    */
+  private def awaitPythonPort(): Unit = {

Review Comment:
   Waiting for the port and throwing here runs during actor creation before the 
worker registers with the coordinator. When the Python process exits early, the 
user sees raw internal actor paths (`pekko://Amber/user/$a/$a/$c: exception 
during creation...`) in the console with no operator link, as shown in the 
`after-earlyexit` screenshot. Moving the port wait from the client constructor 
into its connection step on the client thread lets actor creation finish and 
reports early exits through the watcher with the operator linked.



##########
amber/src/test/scala/org/apache/texera/amber/engine/architecture/pythonworker/PythonProxyClientSpec.scala:
##########
@@ -368,6 +408,96 @@ class PythonProxyClientSpec extends AnyFlatSpec {
     }
   }
 
+  it should "keep sending after the Python side acknowledges a put late" in {
+    withClient() { fixture =>
+      // Longer than the 5 s the client used to allow for a put's ack.
+      fixture.producer.ackDelayMs = 6000L
+      fixture.producer.delayedPuts = 1
+      fixture.producer.reportedQueueSize = 11L
+      fixture.start()
+      val schema = Schema().add(new Attribute("v", AttributeType.INTEGER))
+      def frame(v: Int): Array[Tuple] =
+        Array(Tuple.builder(schema).addSequentially(Array(Int.box(v))).build())
+      val dataChannel = ChannelIdentity(clientWorkerId, controllerId, 
isControl = false)
+
+      fixture.client.enqueueData(DataElement(DataFrame(frame(1)), dataChannel))
+      fixture.client.enqueueData(DataElement(DataFrame(frame(2)), dataChannel))
+      fixture.client.enqueueActorCommand(CreditUpdate())
+
+      // Everything queued behind the slow put still reaches the Python side, 
in order.
+      awaitTrue(20000)(
+        fixture.loopFailure.isDefined ||
+          (fixture.producer.putsReceived.size == 2 &&
+            fixture.producer.actionsReceived.asScala.exists(_._1 == "actor"))
+      )
+      assert(fixture.loopFailure.isEmpty, s"the client loop died: 
${fixture.loopFailure}")
+      assert(
+        fixture.producer.putsReceived.asScala.map(_.tuples).toVector ==
+          Vector(frame(1).toVector, frame(2).toVector)
+      )
+      // The late ack's queue size is still taken for flow control.
+      awaitTrue()(fixture.client.getQueuedCredit == 11L)
+    }
+  }
+
+  it should "stop with the Python side's error when a put is rejected" in {
+    withClient() { fixture =>
+      fixture.producer.rejectPuts = true
+      fixture.start()
+      val schema = Schema().add(new Attribute("v", AttributeType.INTEGER))
+      val tuple = 
Tuple.builder(schema).addSequentially(Array(Int.box(1))).build()
+      val dataChannel = ChannelIdentity(clientWorkerId, controllerId, 
isControl = false)
+
+      fixture.client.enqueueData(DataElement(DataFrame(Array(tuple)), 
dataChannel))
+
+      // The loop must end with an error rather than wait forever for an ack 
that never comes,
+      // and the error must say why, so the worker can report it.
+      awaitTrue()(fixture.loopFailure.isDefined)
+      val messages = Iterator

Review Comment:
   Nit: Use the helper defined at line 105 here as in the next two tests 
instead of repeating the cause-chain traversal.



##########
amber/src/test/integration/org/apache/texera/amber/engine/e2e/PythonWorkerFailureIntegrationSpec.scala:
##########
@@ -0,0 +1,192 @@
+/*
+ * 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.Duration
+import org.apache.commons.lang3.SystemUtils
+import org.apache.pekko.actor.{ActorSystem, Props}
+import org.apache.pekko.testkit.{ImplicitSender, TestKit}
+import org.apache.texera.amber.clustering.SingleNodeListener
+import org.apache.texera.amber.core.workflow.PortIdentity
+import org.apache.texera.amber.engine.common.AmberRuntime
+import org.apache.texera.amber.engine.e2e.TestUtils.{
+  buildWorkflow,
+  cleanupWorkflowExecutionData,
+  initiateTexeraDBForTestCases,
+  runWorkflowAndReadResults,
+  setUpWorkflowExecutionData
+}
+import org.apache.texera.amber.operator.TestOperators
+import org.apache.texera.amber.tags.IntegrationTest
+import org.apache.texera.common.compiler.model.LogicalLink
+import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach}
+import org.scalatest.flatspec.AnyFlatSpecLike
+
+import java.nio.charset.StandardCharsets
+import java.nio.file.{Files, Path}
+import java.util.Base64
+import java.util.concurrent.atomic.AtomicLong
+import scala.jdk.CollectionConverters._
+import scala.util.{Failure, Success, Try}
+
+/**
+  * End-to-end: when the operating system kills a running Python worker's 
process (the
+  * out-of-memory killer, for example), the execution must fail promptly and 
say which worker
+  * died and how, instead of staying RUNNING forever with nothing reported.
+  *
+  * The workflow is CSV (20,000 rows) -> Python UDF (1 ms per row) -> Keyword 
Search, which runs
+  * for tens of seconds, so the kill lands mid-run. Only this run's UDF 
process is killed: it is
+  * picked out by the operator id in its startup configuration.
+  *
+  * Tagged @IntegrationTest because it spawns a real Python worker; routed to 
the
+  * `amber-integration` CI job.
+  */
+@IntegrationTest
+class PythonWorkerFailureIntegrationSpec

Review Comment:
   This test boots the database, writes 20,000 CSV rows, and sleeps 5 seconds 
to test `SIGKILL` (exit 137), which the unit spec already covers with a real 
child process under a supervisor in under a second. Please drop this 
integration test so CI does not pay for the extra wait.



##########
amber/src/test/scala/org/apache/texera/amber/engine/architecture/pythonworker/PythonWorkflowWorkerSpec.scala:
##########
@@ -163,6 +184,150 @@ class PythonWorkflowWorkerSpec
     field.getBoolean(client)
   }
 
+  // 
---------------------------------------------------------------------------
+  // Failure-reporting fixtures
+  // 
---------------------------------------------------------------------------
+
+  /** Sent to the failure probe once the worker child exists. */
+  private case class Spawned(worker: ActorRef)
+
+  /**
+    * Creates one worker as its child and supervises it the way the 
coordinator does: each failure
+    * goes to `failures` and the child is stopped. What the child sends its 
parent (its
+    * RegisterActorRef, for one) is ignored.
+    */
+  private class FailureCapturingParent(worker: => PythonWorkflowWorker, 
failures: ActorRef)
+      extends Actor {
+    override val supervisorStrategy: SupervisorStrategy = OneForOneStrategy() {
+      case e: Throwable =>
+        failures ! e
+        SupervisorStrategy.Stop
+    }
+    override def preStart(): Unit = failures ! 
Spawned(context.actorOf(Props(worker)))
+    override def receive: Receive = { case _ => }
+  }
+
+  /** A real worker that hands itself to the test, so the test can release its 
port. */
+  private class ObservedWorker(config: WorkerConfig, held: 
AtomicReference[PythonWorkflowWorker])
+      extends PythonWorkflowWorker(config) {
+    held.set(this)
+  }
+
+  /** Starts the proxy server and the (stand-in) interpreter, but no Flight 
client. */
+  private class ProcessOnlyWorker(config: WorkerConfig, held: 
AtomicReference[PythonWorkflowWorker])
+      extends ObservedWorker(config, held) {
+    override def initState(): Unit = {
+      invokePrivate(this, "startProxyServer")
+      invokePrivate(this, "startPythonProcess")
+    }
+  }
+
+  /**
+    * Starts only the Flight client, against a port nothing listens on, so the 
client fails to
+    * connect. `process` stands in for the interpreter the worker would have 
spawned.
+    */
+  private class ClientOnlyWorker(
+      config: WorkerConfig,
+      held: AtomicReference[PythonWorkflowWorker],
+      process: Option[Process]
+  ) extends ObservedWorker(config, held) {
+    override def initState(): Unit = {
+      process.foreach(setServerProcess(this, _))
+      openPort(this, freePort)
+      invokePrivate(this, "startProxyClient")
+    }
+  }
+
+  /** A process that has already exited with `code`. */
+  private class ExitedProcess(code: Int) extends StandInProcess {
+    override def isAlive(): Boolean = false
+    override def exitValue(): Int = code
+    override def destroy(): Unit = ()
+  }
+
+  private case class Supervised(
+      worker: ActorRef,
+      instance: AtomicReference[PythonWorkflowWorker],
+      failures: TestProbe
+  )
+
+  private def supervise(
+      create: AtomicReference[PythonWorkflowWorker] => PythonWorkflowWorker
+  ): Supervised = {
+    val failures = TestProbe()
+    val held = new AtomicReference[PythonWorkflowWorker]()
+    system.actorOf(Props(new FailureCapturingParent(create(held), 
failures.ref)))
+    val worker = failures.expectMsgType[Spawned](10.seconds).worker
+    // The child is constructed asynchronously, after the parent has already 
reported it.
+    awaitCond(held.get != null, 10.seconds)
+    Supervised(worker, held, failures)
+  }
+
+  private def invokePrivate(actor: PythonWorkflowWorker, name: String): Unit = 
{

Review Comment:
   Nit: Making the three startup methods package-private (or `protected`) on 
the worker class lets the test subclasses call them directly instead of 
invoking them through reflection.



##########
amber/src/test/scala/org/apache/texera/amber/engine/architecture/pythonworker/PythonWorkflowWorkerSpec.scala:
##########
@@ -339,4 +504,129 @@ class PythonWorkflowWorkerSpec
 
     a[NotImplementedError] should be thrownBy 
worker.underlyingActor.loadFromCheckpoint(null)
   }
+
+  // 
---------------------------------------------------------------------------
+  // Failure reporting: a Python process that exits, a Flight client that 
stops, and an
+  // interpreter that exits before connecting must each fail the worker, so 
the coordinator
+  // can fail the run instead of letting it hang.
+  // 
---------------------------------------------------------------------------
+
+  for ((code, how) <- Seq(3 -> "with an error code", 0 -> "cleanly")) {
+    it should s"report a Python process that exits $how mid-run, naming the 
worker and the code" in {
+      val name = s"py-exit-$code"
+      standInInterpreter(name, s"sleep 1\nexit $code")

Review Comment:
   Nit: The process-only test worker does not wait for a client connection, so 
the four 1-second sleeps in the stand-in shell scripts (here and at lines 533 
and 587) and the 3-second wait after actor termination at line 629 can be 
dropped or shortened to save about 7 seconds of unit test time.



##########
amber/src/test/scala/org/apache/texera/amber/engine/architecture/pythonworker/PythonProxyClientSpec.scala:
##########
@@ -368,6 +408,96 @@ class PythonProxyClientSpec extends AnyFlatSpec {
     }
   }
 
+  it should "keep sending after the Python side acknowledges a put late" in {
+    withClient() { fixture =>
+      // Longer than the 5 s the client used to allow for a put's ack.
+      fixture.producer.ackDelayMs = 6000L

Review Comment:
   Nit: Since the client waits without a timeout, sleeping 6 seconds only adds 
wall-clock time to the unit test suite. A short delay such as 200 ms still 
exercises a delayed acknowledgement without slowing down every test run.



-- 
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