diff --git a/amber/src/main/scala/org/apache/texera/web/resource/SyncExecutionResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/SyncExecutionResource.scala index 400d7bbc877..622cc1610b2 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/SyncExecutionResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/SyncExecutionResource.scala @@ -67,6 +67,8 @@ import javax.ws.rs.core.MediaType import scala.collection.mutable import scala.jdk.CollectionConverters._ import com.fasterxml.jackson.databind.ObjectMapper +import org.apache.texera.observability.{SpanAttrs, TexeraTracer} +import io.opentelemetry.api.trace.StatusCode case class SyncExecutionRequest( executionName: String, @@ -153,7 +155,14 @@ class SyncExecutionResource extends LazyLogging { s"maxOperatorResultCellCharLimit=${request.maxOperatorResultCellCharLimit} (capped to $maxOperatorResultCellCharLimit)" ) - try { + val span = TexeraTracer.tracer + .spanBuilder("SyncExecutionResource.executeWorkflowSync") + .setAttribute(SpanAttrs.WorkflowId, Long.box(workflowId)) + .setAttribute(SpanAttrs.ComputingUnitId, Long.box(computingUnitId.toLong)) + .setAttribute(SpanAttrs.OperatorCount, Long.box(request.logicalPlan.operators.size.toLong)) + .startSpan() + val scope = span.makeCurrent() + def runExecution(): SyncExecutionResult = { val workflowService = WorkflowService.getOrCreate( WorkflowIdentity(workflowId), computingUnitId @@ -353,11 +362,29 @@ class SyncExecutionResource extends LazyLogging { compilationErrors = None, errors = if (fatalErrors.nonEmpty) Some(fatalErrors) else None ) + } + try { + // A failed run (an early return or a caught exception) must mark the span ERROR, or + // Jaeger's error filter skips it; set it once from the single result. + val result = + try runExecution() + catch { + case e: Exception => + logger.error(s"Sync execution error: ${e.getMessage}", e) + span.recordException(e) + handleExecutionError(e) + } + if (!result.success) span.setStatus(StatusCode.ERROR) + result } catch { - case e: Exception => - logger.error(s"Sync execution error: ${e.getMessage}", e) - handleExecutionError(e) + case t: Throwable => + span.recordException(t) + span.setStatus(StatusCode.ERROR) + throw t + } finally { + scope.close() + span.end() } } diff --git a/amber/src/test/scala/org/apache/texera/web/resource/SyncExecutionResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/SyncExecutionResourceSpec.scala index 7c505881e5b..3a6b5e5bd5d 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/SyncExecutionResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/SyncExecutionResourceSpec.scala @@ -88,14 +88,22 @@ import java.net.URI import java.sql.Timestamp import java.util.concurrent.{FutureTask, TimeUnit} import scala.jdk.CollectionConverters._ +import io.opentelemetry.api.GlobalOpenTelemetry +import io.opentelemetry.api.trace.StatusCode +import io.opentelemetry.sdk.OpenTelemetrySdk +import io.opentelemetry.sdk.common.CompletableResultCode +import io.opentelemetry.sdk.trace.SdkTracerProvider +import io.opentelemetry.sdk.trace.`export`.{SimpleSpanProcessor, SpanExporter} +import io.opentelemetry.sdk.trace.data.SpanData +import org.apache.texera.observability.SpanAttrs /** * Unit tests for the synchronous "run this workflow and hand me the results" endpoint used by * agent-service. * * Two of the resource's methods are public (`executeWorkflowSync`, `healthCheck`); the other - * sixteen are `private def`. `executeWorkflowSync` is driven for real here — one end-to-end case - * that gets as far as a running engine can be taken without one — but the result-shaping helpers + * sixteen are `private def`. `executeWorkflowSync` is driven for real here — two end-to-end cases + * that get as far as a running engine can be taken without one — but the result-shaping helpers * it calls cannot be reached that way: every one of them only produces an observable difference * once the engine has populated the stats/console stores or written Iceberg results. They are * therefore driven through `PrivateMethodTester` over fixtures that stand in for that state, and @@ -152,6 +160,18 @@ class SyncExecutionResourceSpec private val resource = new SyncExecutionResource() + // Captures the spans the resource emits so a case can assert their status and attributes. + private val exportedSpans = + java.util.Collections.synchronizedList(new java.util.ArrayList[SpanData]()) + private object CollectingSpanExporter extends SpanExporter { + override def `export`(spans: java.util.Collection[SpanData]): CompletableResultCode = { + exportedSpans.addAll(spans) + CompletableResultCode.ofSuccess() + } + override def flush(): CompletableResultCode = CompletableResultCode.ofSuccess() + override def shutdown(): CompletableResultCode = CompletableResultCode.ofSuccess() + } + private val stateToString = PrivateMethod[String](Symbol("stateToString")) private val isTerminalState = PrivateMethod[Boolean](Symbol("isTerminalState")) private val isCausedByTimeout = PrivateMethod[Boolean](Symbol("isCausedByTimeout")) @@ -184,6 +204,20 @@ class SyncExecutionResourceSpec private var resultEid: Int = 0 override protected def beforeAll(): Unit = { + // Install an in-memory span exporter before anything emits a span; TexeraTracer reads the + // tracer from GlobalOpenTelemetry, so the resource's spans land in exportedSpans. + GlobalOpenTelemetry.resetForTest() + GlobalOpenTelemetry.set( + OpenTelemetrySdk + .builder() + .setTracerProvider( + SdkTracerProvider + .builder() + .addSpanProcessor(SimpleSpanProcessor.create(CollectingSpanExporter)) + .build() + ) + .build() + ) initializeDBAndReplaceDSLContext() val cfg = getDSLContext.configuration() @@ -226,7 +260,10 @@ class SyncExecutionResourceSpec resultEid = insertExecution("result-fixture") } - override protected def afterAll(): Unit = closeConnectionPool() + override protected def afterAll(): Unit = { + try closeConnectionPool() + finally GlobalOpenTelemetry.resetForTest() + } private def insertExecution(name: String): Int = { import org.apache.texera.dao.jooq.generated.Tables.{WORKFLOW_EXECUTIONS, WORKFLOW_VERSION} @@ -1217,4 +1254,74 @@ class SyncExecutionResourceSpec result.operators("scan-op").state shouldBe "Unknown" result.operators("scan-op").error shouldBe None } + + it should "mark the execution span ERROR with correlation labels on a failed run" in { + exportedSpans.clear() + val scan = new CSVScanSourceOpDesc() + scan.setOperatorId("scan-op") + val user = new User + user.setUid(testUid) + user.setEmail("sync-exec@example.com") + + val result = resource.executeWorkflowSync( + testWid.toLong, + testCuid, + SyncExecutionRequest( + executionName = "sync-spec-span", + logicalPlan = LogicalPlanPojo(List(scan), List.empty, List.empty, List.empty), + workflowSettings = None, + targetOperatorIds = List("scan-op"), + timeoutSeconds = 5, + maxOperatorResultCharLimit = 100000, + maxOperatorResultCellCharLimit = 20000 + ), + new SessionUser(user) + ) + result.success shouldBe false + + val span = exportedSpans.asScala + .find(_.getName == "SyncExecutionResource.executeWorkflowSync") + .getOrElse(fail("expected the executeWorkflowSync span to be exported")) + span.getStatus.getStatusCode shouldBe StatusCode.ERROR + span.getAttributes.get(SpanAttrs.WorkflowId) shouldBe testWid.toLong + span.getAttributes.get(SpanAttrs.ComputingUnitId) shouldBe testCuid.toLong + span.getAttributes.get(SpanAttrs.OperatorCount) shouldBe 1L + + val initSpan = exportedSpans.asScala + .find(_.getName == "WorkflowService.initExecutionService") + .getOrElse(fail("expected the initExecutionService span to be exported")) + initSpan.getParentSpanId shouldBe span.getSpanContext.getSpanId + } + + it should "record the exception and mark the span ERROR when the run throws" in { + exportedSpans.clear() + val scan = new CSVScanSourceOpDesc() + scan.setOperatorId("scan-op") + val user = new User + user.setUid(testUid) + user.setEmail("sync-exec@example.com") + + val result = resource.executeWorkflowSync( + testWid.toLong, + testCuid, + SyncExecutionRequest( + executionName = "sync-spec-span-throw", + logicalPlan = LogicalPlanPojo(List(scan), List.empty, List.empty, List.empty), + workflowSettings = None, + targetOperatorIds = List("scan-op"), + timeoutSeconds = 5, + maxOperatorResultCharLimit = 100000, + maxOperatorResultCellCharLimit = 20000, + warehouseId = Some(1) + ), + new SessionUser(user) + ) + result.success shouldBe false + + val span = exportedSpans.asScala + .find(_.getName == "SyncExecutionResource.executeWorkflowSync") + .getOrElse(fail("expected the executeWorkflowSync span to be exported")) + span.getStatus.getStatusCode shouldBe StatusCode.ERROR + span.getEvents.asScala.exists(_.getName == "exception") shouldBe true + } } diff --git a/common/observability/src/main/scala/org/apache/texera/observability/SpanAttrs.scala b/common/observability/src/main/scala/org/apache/texera/observability/SpanAttrs.scala index 56e0d192571..197b461c439 100644 --- a/common/observability/src/main/scala/org/apache/texera/observability/SpanAttrs.scala +++ b/common/observability/src/main/scala/org/apache/texera/observability/SpanAttrs.scala @@ -35,4 +35,7 @@ object SpanAttrs { val WorkflowId: AttributeKey[java.lang.Long] = AttributeKey.longKey("texera.workflow.id") val ExecutionId: AttributeKey[java.lang.Long] = AttributeKey.longKey("texera.execution.id") + val ComputingUnitId: AttributeKey[java.lang.Long] = + AttributeKey.longKey("texera.computing_unit.id") + val OperatorCount: AttributeKey[java.lang.Long] = AttributeKey.longKey("texera.operator.count") } diff --git a/common/observability/src/test/scala/org/apache/texera/observability/SpanAttrsSpec.scala b/common/observability/src/test/scala/org/apache/texera/observability/SpanAttrsSpec.scala index 8143832c4c6..65ab2eb641d 100644 --- a/common/observability/src/test/scala/org/apache/texera/observability/SpanAttrsSpec.scala +++ b/common/observability/src/test/scala/org/apache/texera/observability/SpanAttrsSpec.scala @@ -47,6 +47,8 @@ class SpanAttrsSpec extends AnyFlatSpec with Matchers { it should "expose stable key names so callsites share one label vocabulary" in { SpanAttrs.WorkflowId.getKey shouldBe "texera.workflow.id" SpanAttrs.ExecutionId.getKey shouldBe "texera.execution.id" + SpanAttrs.ComputingUnitId.getKey shouldBe "texera.computing_unit.id" + SpanAttrs.OperatorCount.getKey shouldBe "texera.operator.count" } // ----- attribute-count cap is the OTel SDK default (128) -------------