hvanhovell commented on code in PR #55683: URL: https://github.com/apache/spark/pull/55683#discussion_r3343626253
########## udf/worker/core/src/main/scala/org/apache/spark/udf/worker/core/grpc/GrpcWorkerSession.scala: ########## @@ -0,0 +1,773 @@ +/* + * 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.spark.udf.worker.core.grpc + +import java.util.concurrent.{CountDownLatch, LinkedBlockingQueue, TimeoutException, TimeUnit} +import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference} + +import scala.util.control.NonFatal + +import com.google.protobuf.ByteString +import io.grpc.{ConnectivityState, ManagedChannel} +import io.grpc.stub.StreamObserver + +import org.apache.spark.annotation.Experimental +import org.apache.spark.udf.worker.{Cancel, DataRequest, ExecutionError, Finish, Init, + UdfControlRequest, UdfControlResponse, UdfRequest, UdfResponse, UdfWorkerGrpc} +import org.apache.spark.udf.worker.core.{WorkerHandle, WorkerLogger, WorkerSession} +import org.apache.spark.udf.worker.core.grpc.GrpcWorkerSession._ + +/** + * :: Experimental :: + * gRPC implementation of [[WorkerSession]] for the `UdfWorker.Execute` + * bidirectional RPC. + * + * Drives one bidirectional `Execute` stream against the worker per the + * ordering invariants documented in `udf_protocol.proto`: + * {{{ + * Engine -> Worker: Init -> (DataRequest)* -> Finish (Cancel)? + * | Cancel + * Worker -> Engine: InitResponse -> (DataResponse)* -> (ErrorResponse)? -> (FinishResponse | CancelResponse) + * }}} + * + * Knows nothing about how the worker was provisioned (locally spawned, + * indirectly looked up, ...) -- the dispatcher constructs this with a + * [[WorkerHandle]] and channel; the base [[WorkerSession]] handles + * dispatcher-side cleanup on close. + * + * Threading: + * - [[doInit]] is synchronous: sends `Init` and blocks on `InitResponse`. + * - [[doProcess]] returns an iterator. Input batches are forwarded inline + * (the iterator's `next()` thread also sends `DataRequest`). Output + * batches arrive via the response observer (gRPC callback thread) and + * are consumed by the same iterator. A terminator (`FinishResponse`, + * `CancelResponse`, `ErrorResponse`, gRPC stream error) is published + * once. + * - [[cancel]] is thread-safe and idempotent. + * - [[doClose]] half-closes the request stream after the terminator arrives. + * + * TODO [SPARK-55278]: this class does not yet implement payload chunking; + * the entire [[Init.udf]] payload is sent inline. Chunking will be added + * when a UDF payload large enough to exceed gRPC's default message size + * limit is introduced. + * + * @param workerHandle dispatcher-side handle for releasing the worker on + * [[close]] (see [[WorkerSession]]). + * @param channel built and owned by the caller (typically a + * [[GrpcWorkerChannel]]). Not closed here -- the + * dispatcher tears it down via [[WorkerHandle]]. + * @param logger diagnostics. Defaults to [[WorkerLogger.NoOp]]. + * @param initResponseTimeoutMs upper bound on the wait for `InitResponse` + * after [[doInit]] sends `Init`. + * @param terminalTimeoutMs upper bound on the wait for a stream + * terminator (`FinishResponse`, + * `CancelResponse`, or `ErrorResponse`). + * Each output-queue poll resets this wait; + * see [[doProcess]] / `ProcessIterator`. + */ +@Experimental +class GrpcWorkerSession( + workerHandle: WorkerHandle, + channel: ManagedChannel, + logger: WorkerLogger = WorkerLogger.NoOp, + initResponseTimeoutMs: Long = DEFAULT_INIT_RESPONSE_TIMEOUT_MS, + terminalTimeoutMs: Long = DEFAULT_TERMINAL_TIMEOUT_MS) + extends WorkerSession(workerHandle, logger) { + + require(channel != null, "channel is required") + + private val asyncStub = UdfWorkerGrpc.newStub(channel) + + // Output batches received from the worker, drained by the iterator returned + // from process(). Intentionally unbounded -- the alternative (a bounded + // queue that the gRPC callback thread blocks on when full) would stall the + // Netty event loop and back-pressure the entire channel, including control + // messages, which makes cancel / terminator delivery latency-sensitive. + // + // Today this is safe because gRPC's HTTP/2 flow control bounds in-flight + // bytes on the wire and the engine consumer typically drains promptly; the + // queue holds at most a small number of decoded batches. + // + // Future work -- protocol-level back-pressure: a slow downstream consumer + // (e.g. a Spark operator that stalls) can in principle let the queue grow, + // because flow control only gates the wire path, not the in-heap queue. + // The intended fix is at the protocol layer, not the queue: extend the + // proto so the engine can ask the worker to hold UDF execution while the + // downstream is behind (e.g. periodic data-request acks with a sequence + // number, or a dedicated pause/resume control message). That keeps the + // gRPC receive path non-blocking while still bounding driver memory. + // We deliberately do NOT bound this queue: blocking the gRPC receiving + // thread is worse than the current unbounded-but-fast behaviour. A proto + // change is out of scope here. + private val outputQueue = new LinkedBlockingQueue[QueueItem]() + + // Latch fired when `InitResponse` (success or error) or a transport error + // arrives. init() blocks on this; until it fires we have no proof the + // worker actually accepted the session. + private val initLatch = new CountDownLatch(1) Review Comment: A `Phaser` might be more appropriate. You can combine this with other latch. -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
