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 cb1d61946b fix(amber): commit the last runtime stats snapshot on close
(#9628)
cb1d61946b is described below
commit cb1d61946ba1ad1102c68a57c89fdd1a3613a546
Author: Kunwoo (Chris) <[email protected]>
AuthorDate: Tue Nov 24 16:41:11 2026 +0000
fix(amber): commit the last runtime stats snapshot on close (#9628)
### What changes were proposed in this PR?
Problem. `ExecutionStatsService` queues each `RuntimeStatisticsPersist`
on its own persist thread, but closes the runtime statistics writer
directly on the callback thread when the execution reaches a terminal
state. The engine reports the final statistics right before the terminal
state, so `close()` can flush and commit before that last snapshot is
written. The snapshot then sits in the writer's buffer and is never
committed. The persist executor is also never shut down, so every
execution leaves an idle thread behind. A user kill or a fatal error
never sends a terminal state at all, so those runs never commit their
buffered statistics either, and the service is only torn down at the
next run or about 30 s after the last tab disconnects.
Fix. A new `commitAndStop` runs `close()` on the persist thread, behind
anything still queued, waits for it (up to 60 s, so the commit stays
synchronous as before), and then shuts the executor down. It runs once,
on whichever comes first: the terminal state, a fatal error, or
teardown. A failed run is committed as soon as it fails. A killed run is
committed on teardown, in the background, so starting the next run does
not wait for it. Statistics that arrive after that are dropped instead
of being rejected into the client's error handler.
```
Before: final persist -> queued | terminal state -> close() now ->
commit -> final snapshot never committed
After: final persist -> queued | terminal state -> close() queued ->
final snapshot committed -> executor shut down
```
Not included. `ExecutionConsoleService` has the same pattern: console
messages are written on a single-thread executor, but the writers are
closed on the callback thread. That is tracked in #9641 and will get the
same fix in a separate PR.
### Any related issues, documentation, discussions?
Closes #9627. Found while reviewing #9594.
### How was this PR tested?
Three tests were added to `ExecutionStatsServiceSpec`:
| Test | Checks |
| --- | --- |
| commit a statistics snapshot that is still queued when the execution
terminates | holds the persist thread so the final snapshot is still
queued at the terminal state, then reads it back |
| stop the persist thread on commit and ignore what arrives after it |
the executor is shut down, and later statistics and terminal states
neither throw nor add rows |
| commit and stop the persist thread when the engine reports no terminal
state | a fatal error and `unsubscribeAll` each commit buffered
statistics and shut the executor down |
Without the fix, the first test reads back no rows (`List()` where
`List("opA")` was expected) and the second fails too; the third tests
fatal-error and teardown commits that didn't exist before. The existing
persistence tests waited for the persist thread before sending the
terminal state, which is why they passed.
```
sbt "WorkflowExecutionService/testOnly
org.apache.texera.web.service.ExecutionStatsServiceSpec
org.apache.texera.web.service.WorkflowExecutionServiceSpec"
sbt "WorkflowExecutionService/scalafixAll --check"
"WorkflowExecutionService/scalafmtCheckAll"
```
The first command runs 28 tests, and all pass; the second is clean.
Across all of `org.apache.texera.web.service.*`, the only failures are
two `WorkflowServiceSpec` tests that fail the same way on `main` (a
warehouse setting on my machine) and four `ResultExportServiceSpec`
tests that need port 9092, which my local stack holds.
### Was this PR authored or co-authored using generative AI tooling?
Generated-by: Claude Code, Claude Opus 5.5
---
.../texera/web/service/ExecutionStatsService.scala | 76 ++++++++++++++++++----
.../web/service/ExecutionStatsServiceSpec.scala | 73 ++++++++++++++++++---
.../web/service/WorkflowExecutionServiceSpec.scala | 5 --
3 files changed, 127 insertions(+), 27 deletions(-)
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 7e470a38b4..e1e7997fcf 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
@@ -52,7 +52,8 @@ import
org.apache.texera.amber.engine.common.executionruntimestate.{
}
import org.apache.texera.amber.error.ErrorUtils.{
getOperatorFromActorIdOpt,
- getStackTraceWithAllCauses
+ getStackTraceWithAllCauses,
+ safely
}
import org.apache.texera.web.SubscriptionManager
import org.apache.texera.web.model.websocket.event.{
@@ -66,7 +67,8 @@ import org.apache.texera.web.storage.ExecutionStateStore
import org.apache.texera.web.storage.ExecutionStateStore.updateWorkflowState
import java.time.Instant
-import java.util.concurrent.Executors
+import java.util.concurrent.atomic.AtomicBoolean
+import java.util.concurrent.{Executors, RejectedExecutionException, TimeUnit,
TimeoutException}
class ExecutionStatsService(
client: AmberClient,
@@ -97,6 +99,9 @@ class ExecutionStatsService(
private var lastPersistedMetrics: Map[String, OperatorMetrics] =
Map.empty[String, OperatorMetrics]
+ private val committed = new AtomicBoolean(false)
+ private val CommitTimeoutSeconds = 60L
+
registerCallbacks()
addSubscription(
@@ -195,10 +200,15 @@ class ExecutionStatsService(
addSubscription(
client
.registerCallback[RuntimeStatisticsPersist]((evt:
RuntimeStatisticsPersist) => {
- metricsPersistThread.execute(() => {
- storeRuntimeStatistics(computeStatsDiff(evt.operatorMetrics))
- lastPersistedMetrics = evt.operatorMetrics
- })
+ try {
+ metricsPersistThread.execute(() => {
+ storeRuntimeStatistics(computeStatsDiff(evt.operatorMetrics))
+ lastPersistedMetrics = evt.operatorMetrics
+ })
+ } catch {
+ // commitAndStop has shut the thread down; its queued close
commits what came before.
+ case _: RejectedExecutionException =>
+ }
})
)
}
@@ -207,16 +217,54 @@ class ExecutionStatsService(
client.registerCallback[ExecutionStateUpdate] {
case ExecutionStateUpdate(state: WorkflowAggregatedState.Recognized)
if state == COMPLETED || state == FAILED || state == KILLED =>
- logger.info("Workflow execution terminated. Commit runtime
statistics.")
+ commitAndStop()
+ case _ =>
+ }
+ )
+
+ /**
+ * Commits a run that never reported a terminal state, such as a user kill,
when
+ * WorkflowService tears the service down: at the next run or on session
cleanup. The commit
+ * finishes in the background so the next run does not wait for it.
+ */
+ override def unsubscribeAll(): Unit = {
+ super.unsubscribeAll()
+ commitAndStop(awaitCommit = false)
+ }
+
+ /**
+ * Commits the runtime statistics and stops the persist thread, once. The
engine reports the
+ * final statistics right before the terminal state, and that report may
still be queued on
+ * the persist thread. Closing the writer there, behind it, commits it;
closing on the calling
+ * thread would flush before it and strand it in the buffer.
+ */
+ private def commitAndStop(awaitCommit: Boolean = true): Unit = {
+ if (committed.compareAndSet(false, true)) {
+ logger.info("Committing runtime statistics.")
+ val close: Runnable = () =>
+ try runtimeStatsWriter.close()
+ catch safely {
+ case e => logger.error("Failed to close runtime statistics writer",
e)
+ }
+ val commit = metricsPersistThread.submit(close)
+ // Queued tasks, the close among them, still run after shutdown.
+ metricsPersistThread.shutdown()
+ if (awaitCommit) {
try {
- runtimeStatsWriter.close()
+ // Bounded so a stuck write cannot hang the caller.
+ commit.get(CommitTimeoutSeconds, TimeUnit.SECONDS)
} catch {
- case e: Exception =>
- logger.error("Failed to close runtime statistics writer", e)
+ case e: InterruptedException =>
+ Thread.currentThread().interrupt()
+ logger.error("Interrupted while committing runtime statistics", e)
+ case _: TimeoutException =>
+ logger.warn(
+ s"Runtime statistics commit exceeded ${CommitTimeoutSeconds}s;
continuing in background"
+ )
}
- case _ =>
+ }
}
- )
+ }
private def computeStatsDiff(
newMetrics: Map[String, OperatorMetrics]
@@ -338,6 +386,10 @@ class ExecutionStatsService(
)
)
}
+ // A failed run ends here without the engine reporting a terminal
state, and the
+ // service is not torn down until the next run or session cleanup;
commit now so the
+ // statistics can be read.
+ commitAndStop()
})
)
}
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 39502a278a..4b2a577923 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
@@ -78,7 +78,7 @@ import org.scalatest.matchers.should.Matchers
import java.net.URI
import java.sql.Timestamp
-import java.util.concurrent.ExecutorService
+import java.util.concurrent.{ExecutorService, TimeUnit}
/**
* The service class was entirely uncovered. It owns two independent outputs:
the websocket
@@ -94,9 +94,10 @@ import java.util.concurrent.ExecutorService
* (DefaultCostEstimatorSpec owns wid 1 / eid 1). They must also differ from
each other, so a
* URI built from the wrong identity is a visibly different URI.
*
- * Not covered on purpose: the catch arm around `runtimeStatsWriter.close()`
(iceberg's close is
- * a repeatable buffer flush and does not throw), and the catch arm in
`storeRuntimeStatistics`
- * (it runs on the private persist executor, which swallows anything a test
could observe).
+ * Not covered on purpose: the catch arms in `commitAndStop` (iceberg's close
is a repeatable
+ * buffer flush and does not throw, and the wait is neither interrupted nor
near its timeout),
+ * and the catch arm in `storeRuntimeStatistics` (it runs on the private
persist executor, which
+ * swallows anything a test could observe).
*/
class ExecutionStatsServiceSpec
extends TestKit(ActorSystem("ExecutionStatsServiceSpec"))
@@ -222,12 +223,15 @@ class ExecutionStatsServiceSpec
/**
* The persist callback hands its work to a private single-threaded
executor. A no-op task
* queued behind it can only run once that work is done, which is the
barrier a test needs
- * before it closes the writer and reads the table back.
+ * before it checks that nothing was committed yet.
*/
- private def awaitPersist(service: ExecutionStatsService): Unit = {
+ private def awaitPersist(service: ExecutionStatsService): Unit =
+ persistExecutor(service).submit((() => ()): Runnable).get()
+
+ private def persistExecutor(service: ExecutionStatsService): ExecutorService
= {
val field =
classOf[ExecutionStatsService].getDeclaredField("metricsPersistThread")
field.setAccessible(true)
- field.get(service).asInstanceOf[ExecutorService].submit((() => ()):
Runnable).get()
+ field.get(service).asInstanceOf[ExecutorService]
}
/** Reads the committed statistics rows. Opening (never re-creating) the
document is what makes
@@ -508,11 +512,9 @@ class ExecutionStatsServiceSpec
Map("opA" -> metrics(RUNNING, inputs = Seq((0, 1L, 10L))), "opB" ->
opBFinal)
)
)
- awaitPersist(f.service)
// opB is gone from the second report, as happens once an operator
completes and stops
// being polled.
f.client.fire(RuntimeStatisticsPersist(Map("opA" -> metrics(COMPLETED))))
- awaitPersist(f.service)
f.client.fire(ExecutionStateUpdate(COMPLETED))
val rows = persistedRows()
@@ -570,7 +572,6 @@ class ExecutionStatsServiceSpec
)
f.client.fire(RuntimeStatisticsPersist(Map("opMulti" -> multiPort)))
- awaitPersist(f.service)
f.client.fire(ExecutionStateUpdate(COMPLETED))
val rows = persistedRows()
@@ -583,4 +584,56 @@ class ExecutionStatsServiceSpec
row.getField[Long]("outputTupleSize") shouldBe 95L
}
}
+
+ it should "commit a statistics snapshot that is still queued when the
execution terminates" in {
+ withService { f =>
+ // The engine reports the final snapshot right before the terminal
state, and the persist
+ // callback only queues it. Keep the persist thread busy so that
snapshot is still queued
+ // when the terminal state arrives.
+ persistExecutor(f.service).execute(() => Thread.sleep(200))
+ f.client.fire(RuntimeStatisticsPersist(Map("opA" -> metrics(COMPLETED))))
+
+ f.client.fire(ExecutionStateUpdate(COMPLETED))
+
+ persistedRows().map(_.getField[String]("operatorId")) shouldBe Seq("opA")
+ }
+ }
+
+ it should "stop the persist thread on commit and ignore what arrives after
it" in {
+ withService { f =>
+ f.client.fire(RuntimeStatisticsPersist(Map("opA" -> metrics(RUNNING))))
+ f.client.fire(ExecutionStateUpdate(COMPLETED))
+ persistExecutor(f.service).isShutdown shouldBe true
+
+ // fire passes exceptions through, so a rejected persist task would fail
the test here.
+ f.client.fire(RuntimeStatisticsPersist(Map("opA" -> metrics(COMPLETED))))
+ f.client.fire(ExecutionStateUpdate(KILLED))
+ persistedRows() should have size 1
+ }
+ }
+
+ it should "commit and stop the persist thread when the engine reports no
terminal state" in {
+ // A fatal error commits right away, since the service lives on until the
next run or session
+ // cleanup; a user kill commits when the service is torn down, in the
background.
+ Seq[(String, Fixture => Unit)](
+ "fatal error" -> (_.client.fire(FatalError(new RuntimeException("boom"),
None))),
+ "teardown" -> (_.service.unsubscribeAll())
+ ).foreach {
+ case (trigger, end) =>
+ withClue(s"$trigger: ") {
+ withService { f =>
+ f.client.fire(RuntimeStatisticsPersist(Map("opA" ->
metrics(RUNNING))))
+ awaitPersist(f.service)
+ persistedRows() shouldBe empty
+
+ end(f)
+
+ val executor = persistExecutor(f.service)
+ executor.isShutdown shouldBe true
+ executor.awaitTermination(30, TimeUnit.SECONDS) shouldBe true
+ persistedRows().map(_.getField[String]("operatorId")) shouldBe
Seq("opA")
+ }
+ }
+ }
+ }
}
diff --git
a/amber/src/test/scala/org/apache/texera/web/service/WorkflowExecutionServiceSpec.scala
b/amber/src/test/scala/org/apache/texera/web/service/WorkflowExecutionServiceSpec.scala
index d84a1cd88c..7abaee2b0c 100644
---
a/amber/src/test/scala/org/apache/texera/web/service/WorkflowExecutionServiceSpec.scala
+++
b/amber/src/test/scala/org/apache/texera/web/service/WorkflowExecutionServiceSpec.scala
@@ -89,11 +89,6 @@ import scala.collection.mutable.ListBuffer
* The runtime half of `executeWorkflow` (everything from
`createAmberRuntime` on) is
* out of reach here for the reason above and is exercised by the integration
suites.
*
- * Known, pre-existing: `ExecutionStatsService` never shuts down its private
- * `metricsPersistThread` (it does not override `unsubscribeAll`), so the
teardown
- * test below leaks one single-thread executor into the shared JVM, as every
- * construction of that service already does.
- *
* Three further gaps are deliberately described and NOT pinned, because a
test that
* froze the current behaviour would cement it:
*