From 43830acc4c46789b649611d6bbc566353211d226 Mon Sep 17 00:00:00 2001 From: "He-Pin(kerr)" Date: Sun, 29 Nov 2026 14:13:38 +0800 Subject: [PATCH] fix: preserve demand handoff in eagerFutureSink Motivation: An outstanding eager upstream pull can race with materialization of the selected sink. Modification: Reuse the outstanding pull and wait for inner demand before forwarding a buffered element. Keep the final element until it has been delivered before normal completion. Cover both arrival orders and the normal completion boundary with directional tests. Result: Eager prefetch is preserved without a duplicate pull, loss of the first element, or a public API change. Tests: The preceding revision's functional CI passed. Scoped ScalaFmt 3.11.5 passed for this revision; its sole delta is a whitespace-only test constructor wrap with identical parsed Scala AST. References: Refs playframework/playframework#13793. --- .../stream/operators/Sink/eagerFutureSink.md | 3 +- .../stream/scaladsl/EagerFutureSinkSpec.scala | 120 +++++++++++++++++- .../org/apache/pekko/stream/impl/Sinks.scala | 16 ++- 3 files changed, 133 insertions(+), 6 deletions(-) diff --git a/docs/src/main/paradox/stream/operators/Sink/eagerFutureSink.md b/docs/src/main/paradox/stream/operators/Sink/eagerFutureSink.md index 8c0dbe03c6..4d3b7d3caf 100644 --- a/docs/src/main/paradox/stream/operators/Sink/eagerFutureSink.md +++ b/docs/src/main/paradox/stream/operators/Sink/eagerFutureSink.md @@ -33,7 +33,8 @@ successfully. If the `Future` is completed with a failure the stream is failed. Unlike @ref:[futureSink](futureSink.md) and @ref:[lazyFutureSink](lazyFutureSink.md), this operator materializes the inner sink as soon as the future completes, even if no elements have arrived yet. This means empty streams complete normally rather than failing -with `NeverMaterializedException`. At most one element that arrives before the future completes is buffered. +with `NeverMaterializedException`. At most one element is prefetched before the inner sink requests it. +If upstream completes with an element buffered, that element is delivered on demand before completion. The materialized future value is completed with the materialized value of the inner sink once it has been materialized, or failed if the future itself fails or if materialization of the inner sink fails. Upstream diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/EagerFutureSinkSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/EagerFutureSinkSpec.scala index d01176d306..c6e0ce08d2 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/EagerFutureSinkSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/EagerFutureSinkSpec.scala @@ -20,9 +20,22 @@ package org.apache.pekko.stream.scaladsl import scala.concurrent.{ Future, Promise } import org.apache.pekko +import pekko.Done +import pekko.stream.AbruptStageTerminationException +import pekko.stream.Attributes +import pekko.stream.Inlet +import pekko.stream.Materializer +import pekko.stream.Outlet +import pekko.stream.SinkShape +import pekko.stream.SourceShape +import pekko.stream.stage.AsyncCallback +import pekko.stream.stage.GraphStageLogic +import pekko.stream.stage.GraphStageWithMaterializedValue +import pekko.stream.stage.InHandler +import pekko.stream.stage.OutHandler import pekko.stream.testkit.StreamSpec import pekko.stream.testkit.Utils._ -import pekko.stream.{ AbruptStageTerminationException, Materializer } +import pekko.stream.testkit.scaladsl.StreamTestKit.assertAllStagesStopped class EagerFutureSinkSpec extends StreamSpec(""" pekko.stream.materializer.initial-input-buffer-size = 1 @@ -31,6 +44,82 @@ class EagerFutureSinkSpec extends StreamSpec(""" val ex = TE("") + private final class SourceControl( + val firstPull: Future[Done], + signal: AsyncCallback[(Option[Int], Boolean)]) { + def send(value: Int, last: Boolean = false): Future[Done] = + signal.invokeWithFeedback((Some(value), last)) + + def finish(): Future[Done] = signal.invokeWithFeedback((None, true)) + } + + private final class ControlledSource extends GraphStageWithMaterializedValue[SourceShape[Int], SourceControl] { + private val out = Outlet[Int]("eagerSinkTestSource.out") + override val shape: SourceShape[Int] = SourceShape(out) + + override def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, SourceControl) = { + val firstPull = Promise[Done]() + class Logic extends GraphStageLogic(shape) with OutHandler { + val signal: AsyncCallback[(Option[Int], Boolean)] = getAsyncCallback { + case (element, last) => + element.foreach(push(out, _)) + if (last) completeStage() + } + override def onPull(): Unit = { + firstPull.trySuccess(Done) + () + } + setHandler(out, this) + } + val logic = new Logic + (logic, new SourceControl(firstPull.future, logic.signal)) + } + } + + private final class SinkControl(val demand: AsyncCallback[Unit], val received: Future[Int], + val completed: Future[Done]) + + private final class ControlledSink extends GraphStageWithMaterializedValue[SinkShape[Int], SinkControl] { + private val in = Inlet[Int]("eagerSinkTestSink.in") + override val shape: SinkShape[Int] = SinkShape(in) + + override def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, SinkControl) = { + val received = Promise[Int]() + val completed = Promise[Done]() + class Logic extends GraphStageLogic(shape) with InHandler { + val demand: AsyncCallback[Unit] = getAsyncCallback(_ => pull(in)) + override def onPush(): Unit = { + received.success(grab(in)) + () + } + override def onUpstreamFinish(): Unit = { + completed.success(Done) + completeStage() + } + override def onUpstreamFailure(ex: Throwable): Unit = { + received.tryFailure(ex) + completed.tryFailure(ex) + failStage(ex) + } + setHandler(in, this) + } + val logic = new Logic + (logic, new SinkControl(logic.demand, received.future, completed.future)) + } + } + + private def startHandoff(): (SourceControl, SinkControl) = { + val sinkPromise = Promise[Sink[Int, SinkControl]]() + // No async boundary: both controlled stages and the eager sink's substream use the same + // interpreter actor. It processes the current graph events before the next test callback. + val (upstream, inner) = Source.fromGraph(new ControlledSource) + .toMat(Sink.eagerFutureSink(sinkPromise.future))(Keep.both) + .run() + upstream.firstPull.futureValue shouldBe Done + sinkPromise.success(Sink.fromGraph(new ControlledSink)) + (upstream, inner.futureValue) + } + "Sink.eagerFutureSink" must { "work with an already-completed future" in { @@ -53,6 +142,35 @@ class EagerFutureSinkSpec extends StreamSpec(""" result.futureValue shouldBe Seq(1, 2, 3) } + "reuse the outstanding prefetch when the inner sink requests first" in assertAllStagesStopped { + val (upstream, inner) = startHandoff() + + inner.demand.invokeWithFeedback(()).futureValue shouldBe Done + upstream.send(1).futureValue shouldBe Done + inner.received.futureValue shouldBe 1 + upstream.finish().futureValue shouldBe Done + inner.completed.futureValue shouldBe Done + } + + "buffer the prefetched element when it arrives before the inner sink requests" in assertAllStagesStopped { + val (upstream, inner) = startHandoff() + + upstream.send(2).futureValue shouldBe Done + inner.demand.invokeWithFeedback(()).futureValue shouldBe Done + inner.received.futureValue shouldBe 2 + upstream.finish().futureValue shouldBe Done + inner.completed.futureValue shouldBe Done + } + + "deliver a buffered last element before completing the inner sink" in assertAllStagesStopped { + val (upstream, inner) = startHandoff() + + upstream.send(3, last = true).futureValue shouldBe Done + inner.demand.invokeWithFeedback(()).futureValue shouldBe Done + inner.received.futureValue shouldBe 3 + inner.completed.futureValue shouldBe Done + } + "handle an empty stream with an already-completed future" in { val result = Source .empty[Int] diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/Sinks.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/Sinks.scala index 7573ed7aa3..1e19cee658 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/Sinks.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/Sinks.scala @@ -709,10 +709,18 @@ import org.reactivestreams.Subscriber setHandler( in, new InHandler { - override def onPush(): Unit = subOutlet.push(grab(in)) + override def onPush(): Unit = { + val elem = grab(in) + // The initial pull may be fulfilled before the newly materialized sink requests an element. + if (subOutlet.isAvailable) subOutlet.push(elem) + else bufferedElement = OptionVal.Some(elem) + } override def onUpstreamFinish(): Unit = { - subOutlet.complete() - completeStage() + upstreamClosed = true + if (bufferedElement.isEmpty) { + subOutlet.complete() + completeStage() + } } override def onUpstreamFailure(ex: Throwable): Unit = { subOutlet.fail(ex) @@ -734,7 +742,7 @@ import org.reactivestreams.Subscriber if (upstreamClosed) { subOutlet.complete() completeStage() - } else if (!isClosed(in)) { + } else if (!isClosed(in) && !hasBeenPulled(in)) { pull(in) } }