From ca1b49997e0b6da484243c4b7d6db9d97e91f04a Mon Sep 17 00:00:00 2001 From: Google Team Member Date: Thu, 3 Dec 2026 14:07:52 -0800 Subject: [PATCH] fix(plugins): prevent BigQuery model error self-loops and keep post-tool live latency PiperOrigin-RevId: 1035720457 --- .../BigQueryAgentAnalyticsPlugin.java | 118 +++--- .../plugins/agentanalytics/TraceManager.java | 122 ++++-- .../BigQueryAgentAnalyticsPluginE2ETest.java | 297 +++++++++++++ .../BigQueryAgentAnalyticsPluginTest.java | 395 +++++++++++++++++- .../agentanalytics/TraceManagerTest.java | 342 +++++++++++++-- 5 files changed, 1123 insertions(+), 151 deletions(-) diff --git a/core/src/main/java/com/google/adk/plugins/agentanalytics/BigQueryAgentAnalyticsPlugin.java b/core/src/main/java/com/google/adk/plugins/agentanalytics/BigQueryAgentAnalyticsPlugin.java index a09476314..ef2847826 100644 --- a/core/src/main/java/com/google/adk/plugins/agentanalytics/BigQueryAgentAnalyticsPlugin.java +++ b/core/src/main/java/com/google/adk/plugins/agentanalytics/BigQueryAgentAnalyticsPlugin.java @@ -32,6 +32,7 @@ import com.google.adk.models.LlmResponse; import com.google.adk.plugins.BasePlugin; import com.google.adk.plugins.agentanalytics.JsonFormatter.TruncationResult; +import com.google.adk.plugins.agentanalytics.TraceManager.LiveTurnBoundaryKind; import com.google.adk.plugins.agentanalytics.TraceManager.LlmResponseSpanSnapshot; import com.google.adk.plugins.agentanalytics.TraceManager.RecordData; import com.google.adk.plugins.agentanalytics.TraceManager.SpanIds; @@ -68,10 +69,10 @@ import com.google.genai.types.FunctionCall; import com.google.genai.types.FunctionResponse; import com.google.genai.types.Part; +import com.google.genai.types.Transcription; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Maybe; import java.io.IOException; -import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; @@ -707,18 +708,18 @@ public Maybe onEventCallback(InvocationContext invocationContext, Event e if (!config.enabled() || state.isProcessed(invocationContext.invocationId())) { return Maybe.empty(); } - // Function-response and input-transcription events never close an open llm_request span. boolean isLive = isLiveInvocation(invocationContext); TraceManager traceManager = state.getTraceManager(invocationContext.invocationId()); String eventBranch = event.branch().orElse(null); + // Function-response and input-transcription events never close an open llm_request span. if (event.functionResponses().isEmpty() && event.inputTranscription().isEmpty()) { if (isLive) { if (!event.partial().orElse(false) && isLiveTurnBoundary(event)) { traceManager.popLiveLlmRequestSpan( - invocationContext, eventBranch, isBareLiveInterrupted(event)); + invocationContext, eventBranch, liveTurnBoundaryKind(event)); } else if (!Objects.equals(event.author(), "user") && event.functionCalls().isEmpty() - && (event.content().isPresent() || event.outputTranscription().isPresent())) { + && (event.content().isPresent() || hasNonEmptyOutputTranscription(event))) { traceManager.markLiveOutputObserved(invocationContext, eventBranch); } } else if (!event.partial().orElse(false)) { @@ -924,21 +925,43 @@ && continuesLiveConnectionAfterFunctionResponse(event)) { private static boolean isLiveTurnBoundary(Event event) { return event.turnComplete().orElse(false) || event.interrupted().orElse(false) - || event - .errorCode() - .filter(BigQueryAgentAnalyticsPlugin::isTerminalLiveErrorCode) - .isPresent(); + || hasTerminalLiveError(event); + } + + private static LiveTurnBoundaryKind liveTurnBoundaryKind(Event event) { + boolean interrupted = event.interrupted().orElse(false); + boolean turnComplete = event.turnComplete().orElse(false); + // A bare boundary carries exactly one of the two flags and nothing else that ends the turn. + boolean isBare = + interrupted != turnComplete + && event.content().isEmpty() + && !hasNonEmptyOutputTranscription(event) + && !hasTerminalLiveError(event); + if (!isBare) { + return LiveTurnBoundaryKind.TERMINAL; + } + return interrupted + ? LiveTurnBoundaryKind.BARE_INTERRUPTED + : LiveTurnBoundaryKind.BARE_TURN_COMPLETE; + } + + /** + * Returns whether {@code event} carries spoken model output. A live server may end a + * transcription with an empty finished chunk, which carries no output for the turn it arrives in. + */ + private static boolean hasNonEmptyOutputTranscription(Event event) { + return event + .outputTranscription() + .flatMap(Transcription::text) + .filter(text -> !text.isEmpty()) + .isPresent(); } - private static boolean isBareLiveInterrupted(Event event) { - return event.interrupted().orElse(false) - && !event.turnComplete().orElse(false) - && event.content().isEmpty() - && event.outputTranscription().isEmpty() - && event - .errorCode() - .filter(BigQueryAgentAnalyticsPlugin::isTerminalLiveErrorCode) - .isEmpty(); + private static boolean hasTerminalLiveError(Event event) { + return event + .errorCode() + .filter(BigQueryAgentAnalyticsPlugin::isTerminalLiveErrorCode) + .isPresent(); } private static boolean continuesLiveConnectionAfterFunctionResponse(Event event) { @@ -1098,8 +1121,8 @@ public Maybe afterModelCallback( || state.isProcessed(callbackContext.invocationContext().invocationId())) { return Maybe.empty(); } - TraceManager traceManager = - state.getTraceManager(callbackContext.invocationContext().invocationId()); + InvocationContext invocationContext = callbackContext.invocationContext(); + TraceManager traceManager = state.getTraceManager(invocationContext.invocationId()); Map usageDict = new HashMap<>(); llmResponse @@ -1114,25 +1137,15 @@ public Maybe afterModelCallback( .ifPresent(c -> usageDict.put("cached_content_token_count", c)); }); - InvocationContext invocationContext = callbackContext.invocationContext(); LlmResponseSpanSnapshot spanSnapshot = traceManager.captureLlmResponseSpan( invocationContext, isLiveInvocation(invocationContext), llmResponse.partial().orElse(false)); - Duration duration = spanSnapshot.duration(); - Duration ttft = - spanSnapshot.startTime().isPresent() && spanSnapshot.firstTokenTime().isPresent() - ? Duration.between(spanSnapshot.startTime().get(), spanSnapshot.firstTokenTime().get()) - : null; EventData.Builder eventDataBuilder = EventData.builder(); - if (!duration.isZero()) { - eventDataBuilder.setLatency(duration); - } - if (ttft != null) { - eventDataBuilder.setTimeToFirstToken(ttft); - } + spanSnapshot.duration().ifPresent(eventDataBuilder::setLatency); + spanSnapshot.timeToFirstToken().ifPresent(eventDataBuilder::setTimeToFirstToken); llmResponse.modelVersion().ifPresent(eventDataBuilder::setModelVersion); if (!usageDict.isEmpty()) { @@ -1159,29 +1172,18 @@ public Maybe onModelErrorCallback( || state.isProcessed(callbackContext.invocationContext().invocationId())) { return Maybe.empty(); } - TraceManager traceManager = - state.getTraceManager(callbackContext.invocationContext().invocationId()); InvocationContext invocationContext = callbackContext.invocationContext(); + TraceManager traceManager = state.getTraceManager(invocationContext.invocationId()); Optional popped = traceManager.popSpan(invocationContext, "llm_request"); - String spanId = popped.map(RecordData::spanId).orElse(null); - String parentSpanId = - popped - .flatMap(RecordData::parentSpanId) - .or(() -> traceManager.getCurrentSpanAndParent(invocationContext).spanId()) - .orElse(null); EventData.Builder eventDataBuilder = EventData.builder().setStatus("ERROR").setErrorMessage(formatErrorMessage(error)); if (popped.isPresent() && !popped.get().hasSyntheticStartTime()) { eventDataBuilder.setLatency(popped.get().duration()); } - // Always record the internal execution-tree span so parent_span_id references a logged row. - if (spanId != null) { - eventDataBuilder.setSpanIdOverride(spanId); - } - if (parentSpanId != null) { - eventDataBuilder.setParentSpanIdOverride(parentSpanId); - } + // With no span popped, the row resolves to the enclosing span and that span's parent. + popped.ifPresent(p -> eventDataBuilder.setSpanIdOverride(p.spanId())); + popped.flatMap(RecordData::parentSpanId).ifPresent(eventDataBuilder::setParentSpanIdOverride); return logEvent("LLM_ERROR", invocationContext, null, Optional.of(eventDataBuilder.build())) .andThen(Maybe.empty()); } @@ -1214,13 +1216,11 @@ public Maybe> afterToolCallback( if (!config.enabled() || state.isProcessed(toolContext.invocationContext().invocationId())) { return Maybe.empty(); } - state - .getTraceManager(toolContext.invocationContext().invocationId()) - .ensureInvocationSpan(toolContext.invocationContext()); + InvocationContext invocationContext = toolContext.invocationContext(); + TraceManager traceManager = state.getTraceManager(invocationContext.invocationId()); + traceManager.ensureInvocationSpan(invocationContext); Optional popped = - state - .getTraceManager(toolContext.invocationContext().invocationId()) - .popSpan(toolContext.invocationContext(), "tool", toolOperationId(toolContext)); + traceManager.popSpan(invocationContext, "tool", toolOperationId(toolContext)); TruncationResult truncationResult = smartTruncate(result, config.maxContentLength()); ImmutableMap contentMap = ImmutableMap.of( @@ -1243,7 +1243,7 @@ public Maybe> afterToolCallback( return logEvent( "TOOL_COMPLETED", - toolContext.invocationContext(), + invocationContext, contentMap, truncationResult.isTruncated(), Optional.of(eventDataBuilder.build())) @@ -1256,13 +1256,11 @@ public Maybe> onToolErrorCallback( if (!config.enabled() || state.isProcessed(toolContext.invocationContext().invocationId())) { return Maybe.empty(); } - state - .getTraceManager(toolContext.invocationContext().invocationId()) - .ensureInvocationSpan(toolContext.invocationContext()); + InvocationContext invocationContext = toolContext.invocationContext(); + TraceManager traceManager = state.getTraceManager(invocationContext.invocationId()); + traceManager.ensureInvocationSpan(invocationContext); Optional popped = - state - .getTraceManager(toolContext.invocationContext().invocationId()) - .popSpan(toolContext.invocationContext(), "tool", toolOperationId(toolContext)); + traceManager.popSpan(invocationContext, "tool", toolOperationId(toolContext)); TruncationResult truncationResult = smartTruncate(toolArgs, config.maxContentLength()); ImmutableMap contentMap = @@ -1285,7 +1283,7 @@ public Maybe> onToolErrorCallback( return logEvent( "TOOL_ERROR", - toolContext.invocationContext(), + invocationContext, contentMap, truncationResult.isTruncated(), Optional.of(eventDataBuilder.build())) diff --git a/core/src/main/java/com/google/adk/plugins/agentanalytics/TraceManager.java b/core/src/main/java/com/google/adk/plugins/agentanalytics/TraceManager.java index 0f6501c73..e260335ce 100644 --- a/core/src/main/java/com/google/adk/plugins/agentanalytics/TraceManager.java +++ b/core/src/main/java/com/google/adk/plugins/agentanalytics/TraceManager.java @@ -103,6 +103,12 @@ abstract static class SpanRecord { /** True when first model output opened this span, so its start time measures no latency. */ abstract boolean hasSyntheticStartTime(); + /** + * True while a bare {@code turn_complete} may still end the tool-call turn whose tool response + * opened or found this span. That one is ignored before ordered output. + */ + abstract AtomicBoolean awaitingToolCallTurnComplete(); + static SpanRecord create( String spanId, String kind, @@ -110,7 +116,7 @@ static SpanRecord create( @Nullable String callbackEventId, @Nullable String parentSpanId, Instant startTime, - boolean hasSyntheticStartTime) { + SpanOrigin origin) { return new AutoValue_TraceManager_SpanRecord( spanId, kind, @@ -120,7 +126,8 @@ static SpanRecord create( startTime, new AtomicReference<>(), new AtomicBoolean(), - hasSyntheticStartTime); + origin == SpanOrigin.SYNTHETIC, + new AtomicBoolean(origin == SpanOrigin.REOPENED_AFTER_TOOL)); } } @@ -162,27 +169,45 @@ abstract static class LlmResponseSpanSnapshot { abstract Optional parentSpanId(); - abstract Optional startTime(); + /** Time since the model request started, absent when no request start was recorded. */ + abstract Optional duration(); - abstract Optional firstTokenTime(); - - abstract Duration duration(); + /** Time from the model request start to its first response, absent like the duration. */ + abstract Optional timeToFirstToken(); static LlmResponseSpanSnapshot create( @Nullable String spanId, @Nullable String parentSpanId, - @Nullable Instant startTime, - @Nullable Instant firstTokenTime, - Duration duration) { + @Nullable Duration duration, + @Nullable Duration timeToFirstToken) { return new AutoValue_TraceManager_LlmResponseSpanSnapshot( Optional.ofNullable(spanId), Optional.ofNullable(parentSpanId), - Optional.ofNullable(startTime), - Optional.ofNullable(firstTokenTime), - duration); + Optional.ofNullable(duration), + Optional.ofNullable(timeToFirstToken)); } } + /** How a live event ends a model turn, which decides whether it closes an open span. */ + enum LiveTurnBoundaryKind { + /** Interrupted alone, which a live server also sends to acknowledge new input. */ + BARE_INTERRUPTED, + /** Turn complete alone, which may trail a tool-call turn after its tool response. */ + BARE_TURN_COMPLETE, + /** A boundary with output, a terminal error, or both interrupted and turn complete. */ + TERMINAL + } + + /** What opened a span, which decides how its latency and trailing turn boundaries are read. */ + enum SpanOrigin { + /** A callback at the start of the work that the span measures. */ + NORMAL, + /** First model output with no open model request, so the start time measures no latency. */ + SYNTHETIC, + /** A live tool response, after which the server may still end the tool-call turn. */ + REOPENED_AFTER_TOOL + } + public synchronized String getRootAgentName() { return rootAgentName; } @@ -252,7 +277,7 @@ public synchronized String attachCurrentSpan(InvocationContext context) { /* callbackEventId= */ null, /* parentSpanId= */ null, instantOrSystemNow(context), - /* hasSyntheticStartTime= */ false)); + SpanOrigin.NORMAL)); return spanId; } @@ -359,7 +384,7 @@ synchronized SpanRecord pushSpanRecord( spanName, operationId, /* callbackEventId= */ null, - /* hasSyntheticStartTime= */ false, + SpanOrigin.NORMAL, instantOrSystemNow(context)); } @@ -400,7 +425,7 @@ synchronized SpanRecord ensureLiveLlmRequestSpan( InvocationContext context, @Nullable String eventBranch) { return ensureLiveLlmRequestSpanOnBranch( resolveBranch(context, eventBranch), - /* hasSyntheticStartTime= */ false, + SpanOrigin.REOPENED_AFTER_TOOL, instantOrSystemNow(context)); } @@ -413,43 +438,39 @@ synchronized LlmResponseSpanSnapshot captureLlmResponseSpan( InvocationContext context, boolean isLive, boolean isPartial) { String branch = branchKey(context); Instant now = instantOrSystemNow(context); + // Without a span of its own, a non-live response must not borrow an ancestor's llm_request. SpanRecord current = isLive - ? ensureLiveLlmRequestSpanOnBranch(branch, /* hasSyntheticStartTime= */ true, now) - : newestRecord(branch, (key, record) -> true).orElse(null); + ? ensureLiveLlmRequestSpanOnBranch(branch, SpanOrigin.SYNTHETIC, now) + : newestRecord( + branch, + (key, record) -> key.equals(branch) || !record.kind().equals("llm_request")) + .orElse(null); String spanId = null; String parentSpanId = null; - Instant startTime = null; - Instant firstTokenTime = null; + Duration duration = null; + Duration timeToFirstToken = null; if (current != null) { spanId = current.spanId(); parentSpanId = current.parentSpanId(); if (current.kind().equals("llm_request")) { current.firstTokenTime().compareAndSet(null, now); if (!current.hasSyntheticStartTime()) { - startTime = current.startTime(); - firstTokenTime = current.firstTokenTime().get(); + duration = Duration.between(current.startTime(), now); + timeToFirstToken = Duration.between(current.startTime(), current.firstTokenTime().get()); } } } - Duration duration = Duration.ZERO; - if (isPartial) { - if (startTime != null) { - duration = Duration.between(startTime, now); - } - } else { + if (!isPartial) { + // The branch's open llm_request span, if any, is the record captured above. Deque stack = stacksByBranch.get(branch); if (stack != null && !stack.isEmpty() && stack.peekLast().kind().equals("llm_request")) { - RecordData popped = toRecordData(stack.removeLast(), now); - spanId = popped.spanId(); - parentSpanId = popped.parentSpanId().orElse(null); - duration = popped.hasSyntheticStartTime() ? Duration.ZERO : popped.duration(); + stack.removeLast(); } } - return LlmResponseSpanSnapshot.create( - spanId, parentSpanId, startTime, firstTokenTime, duration); + return LlmResponseSpanSnapshot.create(spanId, parentSpanId, duration, timeToFirstToken); } /** @@ -483,19 +504,31 @@ synchronized void markLiveOutputObserved( } } - /** Pops the target branch's top {@code llm_request} span on a terminal live event. */ + /** + * Pops the target branch's top {@code llm_request} span on a live turn boundary. A bare boundary + * keeps a span without ordered output open when it may belong to an earlier turn; first-token + * time is not consulted, since model callbacks run ahead of the ordered events. + */ @CanIgnoreReturnValue synchronized Optional popLiveLlmRequestSpan( - InvocationContext context, @Nullable String eventBranch, boolean isBareInterrupted) { + InvocationContext context, @Nullable String eventBranch, LiveTurnBoundaryKind boundaryKind) { String branch = resolveBranch(context, eventBranch); Deque stack = stacksByBranch.get(branch); if (stack == null || stack.isEmpty() || !stack.peekLast().kind().equals("llm_request")) { return Optional.empty(); } - if (isBareInterrupted && !stack.peekLast().orderedOutputObserved().get()) { + SpanRecord top = stack.peekLast(); + boolean hasOrderedOutput = top.orderedOutputObserved().get(); + if (boundaryKind == LiveTurnBoundaryKind.BARE_INTERRUPTED && !hasOrderedOutput) { // A live server may acknowledge new input with a bare interrupted before ordered output. return Optional.empty(); } + if (boundaryKind == LiveTurnBoundaryKind.BARE_TURN_COMPLETE + && !hasOrderedOutput + && top.awaitingToolCallTurnComplete().compareAndSet(true, false)) { + // A live server may still end the tool-call turn after its tool response, but only once. + return Optional.empty(); + } return Optional.of(toRecordData(stack.removeLast(), instantOrSystemNow(context))); } @@ -552,17 +585,22 @@ synchronized SpanIds getCurrentAgentOrInvocationSpanAndParent( @GuardedBy("this") private SpanRecord ensureLiveLlmRequestSpanOnBranch( - String branch, boolean hasSyntheticStartTime, Instant now) { + String branch, SpanOrigin origin, Instant now) { Deque stack = stackFor(branch); if (!stack.isEmpty() && stack.peekLast().kind().equals("llm_request")) { - return stack.peekLast(); + SpanRecord top = stack.peekLast(); + if (origin == SpanOrigin.REOPENED_AFTER_TOOL) { + // First output may open the span before the tool response event is processed. + top.awaitingToolCallTurnComplete().set(true); + } + return top; } return pushSpanRecordOnBranch( branch, /* spanName= */ "llm_request", /* operationId= */ null, /* callbackEventId= */ null, - hasSyntheticStartTime, + origin, now); } @@ -584,7 +622,7 @@ private SpanRecord pushSpanClosingTopKind( spanName, operationId, callbackEventId, - /* hasSyntheticStartTime= */ false, + SpanOrigin.NORMAL, instantOrSystemNow(context)); } @@ -599,7 +637,7 @@ private SpanRecord pushSpanRecordOnBranch( String spanName, @Nullable String operationId, @Nullable String callbackEventId, - boolean hasSyntheticStartTime, + SpanOrigin origin, Instant startTime) { boolean isLlmRequest = spanName.equals("llm_request"); boolean isAgent = spanName.startsWith("agent:"); @@ -618,7 +656,7 @@ private SpanRecord pushSpanRecordOnBranch( callbackEventId, newestRecord(branch, isSkipped.negate()).map(SpanRecord::spanId).orElse(null), startTime, - hasSyntheticStartTime); + origin); stackFor(branch).addLast(record); return record; } diff --git a/core/src/test/java/com/google/adk/plugins/agentanalytics/BigQueryAgentAnalyticsPluginE2ETest.java b/core/src/test/java/com/google/adk/plugins/agentanalytics/BigQueryAgentAnalyticsPluginE2ETest.java index 9edafa13f..374aefdb1 100644 --- a/core/src/test/java/com/google/adk/plugins/agentanalytics/BigQueryAgentAnalyticsPluginE2ETest.java +++ b/core/src/test/java/com/google/adk/plugins/agentanalytics/BigQueryAgentAnalyticsPluginE2ETest.java @@ -384,6 +384,13 @@ public Maybe onEventCallback(InvocationContext invocationContext, Event e assertEquals(llmRequests.get(0).get("span_id"), llmResponses.get(0).get("span_id")); assertEquals(llmRequests.get(1).get("span_id"), llmResponses.get(1).get("span_id")); assertEquals(agentStartings.get(1).get("span_id"), llmResponses.get(1).get("parent_span_id")); + // The coordinator's reply is logged with the worker's spans open, yet keeps its own span. + ImmutableList> agentResponses = rowsOfType("AGENT_RESPONSE"); + assertEquals(2, agentResponses.size()); + assertTrue(((String) agentResponses.get(0).get("content")).contains("handing off")); + assertEquals(agentStartings.get(0).get("span_id"), agentResponses.get(0).get("span_id")); + assertTrue(((String) agentResponses.get(1).get("content")).contains("worker answer")); + assertEquals(agentStartings.get(1).get("span_id"), agentResponses.get(1).get("span_id")); assertEquals(2, rowsOfType("AGENT_COMPLETED").size()); assertNotNull( "INVOCATION_COMPLETED should record latency", @@ -619,6 +626,83 @@ && rowsOfType(live.rows, "TOOL_COMPLETED").size() == 1 } } + @Test + public void + runLive_toolCall_ignoresEmptyTranscriptionAndPreOutputTurnCompleteBeforePostToolReply() + throws Exception { + try (LiveTestHarness live = newLiveTestHarness()) { + FakeLiveModel model = new FakeLiveModel(); + LlmAgent agent = + LlmAgent.builder() + .name("weather_agent") + .model(model) + .executor(Runnable::run) + .tools(new FixedTool("lookup_weather", ImmutableMap.of("temp_f", 72))) + .build(); + Runner liveRunner = + Runner.builder().agent(agent).appName("test_app").plugins(live.plugin).build(); + Session session = liveRunner.sessionService().createSession("test_app", "user").blockingGet(); + LiveRequestQueue liveRequestQueue = new LiveRequestQueue(); + + TestSubscriber testSubscriber = + liveRunner.runLive(session, liveRequestQueue, RunConfig.builder().build()).test(); + FakeLiveTransport transport = model.awaitConnection(0); + + liveRequestQueue.content(Content.fromParts(Part.fromText("What is the weather?"))); + await( + "initial typed request", + () -> + transport.clientContents.size() == 1 + && rowsOfType(live.rows, "LLM_REQUEST").size() == 1); + String invocationId = (String) onlyRow(live.rows, "INVOCATION_STARTING").get("invocation_id"); + String invocationSpanId = (String) onlyRow(live.rows, "INVOCATION_STARTING").get("span_id"); + String agentSpanId = (String) onlyRow(live.rows, "AGENT_STARTING").get("span_id"); + + transport.push(toolCall("fc-weather", "lookup_weather")); + await( + "tool execution and forwarded function response", + () -> + transport.toolResponses.size() == 1 + && rowsOfType(live.rows, "TOOL_COMPLETED").size() == 1 + && testSubscriber.values().stream() + .anyMatch(event -> !event.functionResponses().isEmpty())); + String postToolLlmSpanId = live.currentRootSpanId(invocationId).orElseThrow(); + assertNotEquals(agentSpanId, postToolLlmSpanId); + + // The server ends the tool-call turn after the tool response, before the reply starts. + transport.push(spokenFinished("")); + transport.push(turnComplete()); + await( + "empty transcription and tool-call turn complete", + () -> + testSubscriber.values().stream().anyMatch(e -> hasOutputTranscription(e, "")) + && testSubscriber.values().stream() + .anyMatch(e -> e.turnComplete().orElse(false))); + assertEquals(postToolLlmSpanId, live.currentRootSpanId(invocationId).orElse(null)); + + transport.push(spoken("It is 72 degrees.")); + await("post-tool speech", () -> rowsOfType(live.rows, "LLM_RESPONSE").size() == 1); + transport.push(turnComplete()); + await( + "post-tool turn complete", + () -> + testSubscriber.values().stream().filter(e -> e.turnComplete().orElse(false)).count() + == 2); + assertEquals(agentSpanId, live.currentRootSpanId(invocationId).orElse(null)); + + liveRequestQueue.close(); + assertTrue(testSubscriber.await(5, SECONDS)); + testSubscriber.assertComplete(); + + // The reply is measured on the reopened span rather than a synthetic one without latency. + Map llmResponse = onlyRow(live.rows, "LLM_RESPONSE"); + assertEquals(postToolLlmSpanId, llmResponse.get("span_id")); + assertEquals(agentSpanId, llmResponse.get("parent_span_id")); + assertNotNull(llmResponse.get("latency_ms")); + live.assertCleanFinalization(invocationSpanId, agentSpanId); + } + } + @Test public void runLive_delayedFunctionCallPersistence_preservesPostToolLlmRequestSpan() throws Exception { @@ -715,6 +799,206 @@ public void runLive_delayedFunctionCallPersistence_preservesPostToolLlmRequestSp } } + @Test + public void runLive_delayedToolCallTurnCompletePersistence_preservesPostToolLlmRequestSpan() + throws Exception { + CompletableFuture turnCompleteAppendEntered = new CompletableFuture<>(); + CompletableFuture releaseTurnCompleteAppend = new CompletableFuture<>(); + LiveRequestQueue liveRequestQueue = new LiveRequestQueue(); + try (LiveTestHarness live = newLiveTestHarness()) { + FakeLiveModel model = new FakeLiveModel(); + LlmAgent agent = + LlmAgent.builder() + .name("weather_agent") + .model(model) + .executor(Runnable::run) + .tools(new FixedTool("lookup_weather", ImmutableMap.of("temp_f", 72))) + .build(); + InMemorySessionService delegate = new InMemorySessionService(); + Runner liveRunner = + Runner.builder() + .agent(agent) + .appName("test_app") + .sessionService( + new DelayedAppendSessionService( + delegate, + event -> event.turnComplete().orElse(false), + turnCompleteAppendEntered, + releaseTurnCompleteAppend)) + .plugins(live.plugin) + .build(); + Session session = delegate.createSession("test_app", "user").blockingGet(); + + TestSubscriber testSubscriber = + liveRunner.runLive(session, liveRequestQueue, RunConfig.builder().build()).test(); + FakeLiveTransport transport = model.awaitConnection(0); + + liveRequestQueue.content(Content.fromParts(Part.fromText("What is the weather?"))); + await( + "initial typed request", + () -> + transport.clientContents.size() == 1 + && rowsOfType(live.rows, "LLM_REQUEST").size() == 1); + String invocationId = (String) onlyRow(live.rows, "INVOCATION_STARTING").get("invocation_id"); + String invocationSpanId = (String) onlyRow(live.rows, "INVOCATION_STARTING").get("span_id"); + String agentSpanId = (String) onlyRow(live.rows, "AGENT_STARTING").get("span_id"); + + transport.push(toolCall("fc-weather", "lookup_weather")); + await( + "tool execution and forwarded function response", + () -> + transport.toolResponses.size() == 1 + && rowsOfType(live.rows, "TOOL_COMPLETED").size() == 1 + && testSubscriber.values().stream() + .anyMatch(event -> !event.functionResponses().isEmpty())); + String postToolLlmSpanId = live.currentRootSpanId(invocationId).orElseThrow(); + assertNotEquals(agentSpanId, postToolLlmSpanId); + + // Hold the tool-call turn's turn_complete while the reply's first chunk is screened. + transport.push(spokenFinished("")); + transport.push(turnComplete()); + turnCompleteAppendEntered.get(5, SECONDS); + transport.push(spoken("It is ")); + await("post-tool chunk 1", () -> rowsOfType(live.rows, "LLM_RESPONSE").size() == 1); + + // A response already logged on the span must not let the stale turn_complete close it. + releaseTurnCompleteAppend.complete(null); + await( + "delayed turn complete and post-tool chunk 1 events", + () -> + testSubscriber.values().stream().anyMatch(e -> e.turnComplete().orElse(false)) + && testSubscriber.values().stream() + .anyMatch(e -> hasOutputTranscription(e, "It is "))); + assertEquals(postToolLlmSpanId, live.currentRootSpanId(invocationId).orElse(null)); + + transport.push(spoken("72 degrees.")); + await("post-tool chunk 2", () -> rowsOfType(live.rows, "LLM_RESPONSE").size() == 2); + transport.push(turnComplete()); + await( + "post-tool turn complete", + () -> + testSubscriber.values().stream().filter(e -> e.turnComplete().orElse(false)).count() + == 2); + assertEquals(agentSpanId, live.currentRootSpanId(invocationId).orElse(null)); + + liveRequestQueue.close(); + assertTrue(testSubscriber.await(5, SECONDS)); + testSubscriber.assertComplete(); + + ImmutableList> llmResponses = rowsOfType(live.rows, "LLM_RESPONSE"); + assertEquals(2, llmResponses.size()); + for (Map llmResponse : llmResponses) { + assertEquals(postToolLlmSpanId, llmResponse.get("span_id")); + assertEquals(agentSpanId, llmResponse.get("parent_span_id")); + assertNotNull(llmResponse.get("latency_ms")); + } + live.assertCleanFinalization(invocationSpanId, agentSpanId); + } finally { + releaseTurnCompleteAppend.complete(null); + liveRequestQueue.close(); + } + } + + @Test + public void + runLive_delayedFunctionResponsePersistence_preservesSharedSpanAcrossStaleTurnComplete() + throws Exception { + CompletableFuture functionResponseAppendEntered = new CompletableFuture<>(); + CompletableFuture releaseFunctionResponseAppend = new CompletableFuture<>(); + LiveRequestQueue liveRequestQueue = new LiveRequestQueue(); + try (LiveTestHarness live = newLiveTestHarness()) { + FakeLiveModel model = new FakeLiveModel(); + LlmAgent agent = + LlmAgent.builder() + .name("weather_agent") + .model(model) + .executor(Runnable::run) + .tools(new FixedTool("lookup_weather", ImmutableMap.of("temp_f", 72))) + .build(); + InMemorySessionService delegate = new InMemorySessionService(); + Runner liveRunner = + Runner.builder() + .agent(agent) + .appName("test_app") + .sessionService( + new DelayedAppendSessionService( + delegate, + event -> !event.functionResponses().isEmpty(), + functionResponseAppendEntered, + releaseFunctionResponseAppend)) + .plugins(live.plugin) + .build(); + Session session = delegate.createSession("test_app", "user").blockingGet(); + + TestSubscriber testSubscriber = + liveRunner.runLive(session, liveRequestQueue, RunConfig.builder().build()).test(); + FakeLiveTransport transport = model.awaitConnection(0); + + liveRequestQueue.content(Content.fromParts(Part.fromText("What is the weather?"))); + await( + "initial typed request", + () -> + transport.clientContents.size() == 1 + && rowsOfType(live.rows, "LLM_REQUEST").size() == 1); + String invocationId = (String) onlyRow(live.rows, "INVOCATION_STARTING").get("invocation_id"); + String invocationSpanId = (String) onlyRow(live.rows, "INVOCATION_STARTING").get("span_id"); + String agentSpanId = (String) onlyRow(live.rows, "AGENT_STARTING").get("span_id"); + + // Hold the tool response's persistence while the tool-call turn ends and the reply starts. + transport.push(toolCall("fc-weather", "lookup_weather")); + functionResponseAppendEntered.get(5, SECONDS); + await( + "forwarded function response", + () -> + transport.toolResponses.size() == 1 + && rowsOfType(live.rows, "TOOL_COMPLETED").size() == 1); + transport.push(spokenFinished("")); + transport.push(turnComplete()); + transport.push(spoken("It is ")); + await("post-tool chunk 1", () -> rowsOfType(live.rows, "LLM_RESPONSE").size() == 1); + String postToolLlmSpanId = live.currentRootSpanId(invocationId).orElseThrow(); + assertNotEquals(agentSpanId, postToolLlmSpanId); + + // The tool response finds the reply's span open, so the stale turn_complete keeps it open. + releaseFunctionResponseAppend.complete(null); + await( + "delayed function response, turn complete and post-tool chunk 1 events", + () -> + testSubscriber.values().stream().anyMatch(e -> !e.functionResponses().isEmpty()) + && testSubscriber.values().stream().anyMatch(e -> e.turnComplete().orElse(false)) + && testSubscriber.values().stream() + .anyMatch(e -> hasOutputTranscription(e, "It is "))); + assertEquals(postToolLlmSpanId, live.currentRootSpanId(invocationId).orElse(null)); + + transport.push(spoken("72 degrees.")); + await("post-tool chunk 2", () -> rowsOfType(live.rows, "LLM_RESPONSE").size() == 2); + transport.push(turnComplete()); + await( + "post-tool turn complete", + () -> + testSubscriber.values().stream().filter(e -> e.turnComplete().orElse(false)).count() + == 2); + assertEquals(agentSpanId, live.currentRootSpanId(invocationId).orElse(null)); + + liveRequestQueue.close(); + assertTrue(testSubscriber.await(5, SECONDS)); + testSubscriber.assertComplete(); + + // First output opened the shared span, so it has no request start to measure from. + ImmutableList> llmResponses = rowsOfType(live.rows, "LLM_RESPONSE"); + assertEquals(2, llmResponses.size()); + for (Map llmResponse : llmResponses) { + assertEquals(postToolLlmSpanId, llmResponse.get("span_id")); + assertEquals(agentSpanId, llmResponse.get("parent_span_id")); + assertNull(llmResponse.get("latency_ms")); + } + live.assertCleanFinalization(invocationSpanId, agentSpanId); + } finally { + releaseFunctionResponseAppend.complete(null); + liveRequestQueue.close(); + } + } + @Test public void runLive_goAwayMidTurn_keepsLlmRequestSpanOpen() throws Exception { try (LiveTestHarness live = newLiveTestHarness()) { @@ -938,6 +1222,10 @@ private static boolean hasAudioInlineData(Event event) { part.inlineData().flatMap(Blob::mimeType).map("audio/pcm"::equals).orElse(false)); } + private static boolean hasOutputTranscription(Event event, String text) { + return event.outputTranscription().flatMap(Transcription::text).map(text::equals).orElse(false); + } + private static LiveServerMessage audioChunk(byte[] pcmBytes) { return LiveServerMessage.builder() .serverContent( @@ -970,6 +1258,15 @@ private static LiveServerMessage spoken(String text) { .build(); } + private static LiveServerMessage spokenFinished(String text) { + return LiveServerMessage.builder() + .serverContent( + LiveServerContent.builder() + .outputTranscription(Transcription.builder().text(text).finished(true).build()) + .build()) + .build(); + } + private static LiveServerMessage turnComplete() { return LiveServerMessage.builder() .serverContent(LiveServerContent.builder().turnComplete(true).build()) diff --git a/core/src/test/java/com/google/adk/plugins/agentanalytics/BigQueryAgentAnalyticsPluginTest.java b/core/src/test/java/com/google/adk/plugins/agentanalytics/BigQueryAgentAnalyticsPluginTest.java index ba414f3ab..7f782cbf4 100644 --- a/core/src/test/java/com/google/adk/plugins/agentanalytics/BigQueryAgentAnalyticsPluginTest.java +++ b/core/src/test/java/com/google/adk/plugins/agentanalytics/BigQueryAgentAnalyticsPluginTest.java @@ -112,6 +112,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; import java.util.logging.Handler; import java.util.logging.Level; @@ -1072,9 +1073,14 @@ public void afterModelCallback_populatesCorrectFields() throws Exception { tracer.spanBuilder("ambient").setParent(Context.current().with(parentSpan)).startSpan(); // Set valid ambient span context try (Scope scope = ambientSpan.makeCurrent()) { - state.getTraceManager("invocation_id").pushSpan(mockInvocationContext, "parent_request"); + String parentSpanId = + state.getTraceManager("invocation_id").pushSpan(mockInvocationContext, "parent_request"); state.getTraceManager("invocation_id").pushSpan(mockInvocationContext, "llm_request"); plugin.afterModelCallback(mockCallbackContext, adkResponse).blockingSubscribe(); + // A final response closes llm_request right away, without waiting for a later callback. + assertEquals( + Optional.of(parentSpanId), + state.getTraceManager("invocation_id").getCurrentSpanId(mockInvocationContext)); } finally { ambientSpan.end(); } @@ -1096,6 +1102,7 @@ public void afterModelCallback_populatesCorrectFields() throws Exception { assertNotNull(row.get("parent_span_id")); ObjectNode latencyMs = (ObjectNode) row.get("latency_ms"); assertNotNull("latency_ms should not be null", latencyMs); + assertTrue("latency_ms should contain total_ms", latencyMs.has("total_ms")); assertTrue( "latency_ms should contain time_to_first_token_ms", latencyMs.has("time_to_first_token_ms")); @@ -2840,6 +2847,15 @@ public void onEventCallback_nonLiveUnmatchedEventId_preservesNextStepLlmRequestS step1Context, LlmResponse.builder().content(Content.fromParts(Part.fromText("step 1"))).build()) .blockingSubscribe(); + // Step 1's final response closes its own span before step 2 opens the next one. + String agentSpanId = (String) onlyRow(rows, "AGENT_STARTING").get("span_id"); + assertEquals( + agentSpanId, + seqPlugin + .getState() + .getTraceManager("invocation_id") + .getCurrentSpanId(mockInvocationContext) + .orElse(null)); // Simulate step 2 starting as soon as step 1 persists, before onEventCallback runs for step 1. seqPlugin.beforeModelCallback(step2Context, LlmRequest.builder()).blockingSubscribe(); seqPlugin @@ -2861,7 +2877,6 @@ public void onEventCallback_nonLiveUnmatchedEventId_preservesNextStepLlmRequestS ImmutableList> llmRequests = rowsOfType(rows, "LLM_REQUEST"); ImmutableList> llmResponses = rowsOfType(rows, "LLM_RESPONSE"); - String agentSpanId = (String) onlyRow(rows, "AGENT_STARTING").get("span_id"); assertEquals(2, llmRequests.size()); assertEquals(2, llmResponses.size()); assertEquals(llmRequests.get(1).get("span_id"), llmResponses.get(1).get("span_id")); @@ -3273,6 +3288,17 @@ public void liveOnEventCallback_functionResponse_reopensLlmRequestUnlessConnecti .partial(true) .build()) .blockingSubscribe(); + // The reply's ordered output lets its turn_complete close the reopened span. + livePlugin + .onEventCallback( + mockInvocationContext, + Event.builder() + .id("evt-post-tool-chunk") + .author("agent_name") + .content(Content.fromParts(Part.fromText("72F"))) + .partial(true) + .build()) + .blockingSubscribe(); livePlugin .onEventCallback( mockInvocationContext, @@ -3617,6 +3643,335 @@ public void afterModelCallback_livePartialAndSyntheticResponses_logAtomicSpanAnd assertNull(llmResponses.get(2).get("latency_ms")); } + @Test + public void afterModelCallback_zeroElapsedTime_emitsZeroTotalMsAndTtft() throws Exception { + List> rows = new CopyOnWriteArrayList<>(); + BigQueryAgentAnalyticsPlugin fastPlugin = newRowRecordingPlugin(rows); + // A coarse clock can report the request and its response at the same instant. + when(mockInvocationContext.now()).thenReturn(Instant.ofEpochMilli(100L)); + CallbackContext callbackContext = mock(CallbackContext.class); + when(callbackContext.invocationContext()).thenReturn(mockInvocationContext); + when(callbackContext.eventId()).thenReturn("evt-instant"); + + fastPlugin.beforeModelCallback(callbackContext, LlmRequest.builder()).blockingSubscribe(); + fastPlugin + .afterModelCallback( + callbackContext, + LlmResponse.builder().content(Content.fromParts(Part.fromText("done"))).build()) + .blockingSubscribe(); + + JsonNode latency = (JsonNode) onlyRow(rows, "LLM_RESPONSE").get("latency_ms"); + assertNotNull("latency_ms should be recorded", latency); + assertTrue("latency_ms should contain total_ms", latency.has("total_ms")); + assertEquals(0L, latency.get("total_ms").asLong()); + assertEquals(0L, latency.get("time_to_first_token_ms").asLong()); + } + + @Test + public void beforeModelCallback_concurrentSpanPushDuringContentFormatting_pinsLlmRequestSpanId() + throws Exception { + AtomicReference traceManagerRef = new AtomicReference<>(); + // The formatter runs between the span push and the row's ID lookup, like a racing callback. + BiFunction formatter = + (content, eventType) -> { + if (eventType.equals("LLM_REQUEST")) { + traceManagerRef.get().pushSpan(mockInvocationContext, "concurrent"); + } + return content; + }; + List> rows = new CopyOnWriteArrayList<>(); + BigQueryAgentAnalyticsPlugin formattingPlugin = + newRowRecordingPlugin(config.toBuilder().contentFormatter(formatter).build(), rows); + TraceManager traceManager = formattingPlugin.getState().getTraceManager("invocation_id"); + traceManagerRef.set(traceManager); + CallbackContext callbackContext = mock(CallbackContext.class); + when(callbackContext.invocationContext()).thenReturn(mockInvocationContext); + when(callbackContext.eventId()).thenReturn("evt-concurrent-push"); + + formattingPlugin.beforeRunCallback(mockInvocationContext).blockingSubscribe(); + formattingPlugin.beforeAgentCallback(fakeAgent, callbackContext).blockingSubscribe(); + formattingPlugin.beforeModelCallback(callbackContext, LlmRequest.builder()).blockingSubscribe(); + + // The pushed span now tops the stack, with the llm_request span as its parent. + String llmSpanId = + traceManager.getCurrentSpanAndParent(mockInvocationContext).parentSpanId().orElseThrow(); + String agentSpanId = (String) onlyRow(rows, "AGENT_STARTING").get("span_id"); + assertNotEquals(agentSpanId, llmSpanId); + Map llmRequest = onlyRow(rows, "LLM_REQUEST"); + assertEquals(llmSpanId, llmRequest.get("span_id")); + assertEquals(agentSpanId, llmRequest.get("parent_span_id")); + } + + @Test + public void + onModelErrorCallback_withoutOpenLlmRequestSpan_parentsErrorToInvocationWithoutSelfLoop() + throws Exception { + CallbackContext callbackContext = mock(CallbackContext.class); + when(callbackContext.invocationContext()).thenReturn(mockInvocationContext); + TraceManager traceManager = state.getTraceManager("invocation_id"); + String invocationSpanId = traceManager.pushSpan(mockInvocationContext, "invocation"); + String agentSpanId = traceManager.pushSpan(mockInvocationContext, "agent:agent_name"); + + // An error raised before this plugin's before-model callback finds no llm_request span open. + plugin + .onModelErrorCallback( + callbackContext, mock(LlmRequest.Builder.class), new RuntimeException("model boom")) + .blockingSubscribe(); + + Map llmError = drainRowsByEventType().get("LLM_ERROR"); + assertNotNull("LLM_ERROR row not found", llmError); + assertEquals(agentSpanId, llmError.get("span_id")); + assertEquals(invocationSpanId, llmError.get("parent_span_id")); + assertNotEquals(llmError.get("span_id"), llmError.get("parent_span_id")); + assertNull(llmError.get("latency_ms")); + } + + @Test + public void afterToolCallback_withoutOpenSpan_seedsInvocationSpanForRow() throws Exception { + ToolContext mockToolContext = mock(ToolContext.class); + when(mockToolContext.invocationContext()).thenReturn(mockInvocationContext); + BaseTool mockTool = mock(BaseTool.class); + when(mockTool.name()).thenReturn("test_tool"); + + // No earlier callback has opened a span for this invocation. + plugin + .afterToolCallback(mockTool, ImmutableMap.of(), mockToolContext, ImmutableMap.of("r", "v")) + .blockingSubscribe(); + + Optional seededSpanId = + state.getTraceManager("invocation_id").getCurrentSpanId(mockInvocationContext); + assertTrue(seededSpanId.isPresent()); + Map completedRow = drainRowsByEventType().get("TOOL_COMPLETED"); + assertNotNull("TOOL_COMPLETED row not found", completedRow); + assertEquals(seededSpanId.get(), completedRow.get("span_id")); + } + + @Test + public void onToolErrorCallback_withoutOpenSpan_seedsInvocationSpanForRow() throws Exception { + ToolContext mockToolContext = mock(ToolContext.class); + when(mockToolContext.invocationContext()).thenReturn(mockInvocationContext); + BaseTool mockTool = mock(BaseTool.class); + when(mockTool.name()).thenReturn("failing_tool"); + + // No earlier callback has opened a span for this invocation. + plugin + .onToolErrorCallback( + mockTool, ImmutableMap.of(), mockToolContext, new RuntimeException("boom")) + .blockingSubscribe(); + + Optional seededSpanId = + state.getTraceManager("invocation_id").getCurrentSpanId(mockInvocationContext); + assertTrue(seededSpanId.isPresent()); + Map errorRow = drainRowsByEventType().get("TOOL_ERROR"); + assertNotNull("TOOL_ERROR row not found", errorRow); + assertEquals(seededSpanId.get(), errorRow.get("span_id")); + } + + @Test + public void liveOnEventCallback_emptyOutputTranscription_doesNotMarkOutputObserved() + throws Exception { + List> rows = new CopyOnWriteArrayList<>(); + BigQueryAgentAnalyticsPlugin livePlugin = newRowRecordingPlugin(rows); + when(mockInvocationContext.liveRequestQueue()).thenReturn(Optional.of(new LiveRequestQueue())); + when(mockInvocationContext.runConfig()).thenReturn(RunConfig.builder().build()); + CallbackContext callbackContext = mock(CallbackContext.class); + when(callbackContext.invocationContext()).thenReturn(mockInvocationContext); + when(callbackContext.eventId()).thenReturn("evt-live-empty-transcription"); + Event bareInterrupted = Event.builder().author("agent_name").interrupted(true).build(); + + livePlugin.beforeRunCallback(mockInvocationContext).blockingSubscribe(); + livePlugin.beforeAgentCallback(fakeAgent, callbackContext).blockingSubscribe(); + livePlugin.beforeModelCallback(callbackContext, LlmRequest.builder()).blockingSubscribe(); + TraceManager traceManager = livePlugin.getState().getTraceManager("invocation_id"); + String agentSpanId = (String) onlyRow(rows, "AGENT_STARTING").get("span_id"); + String llmSpanId = (String) onlyRow(rows, "LLM_REQUEST").get("span_id"); + + // An empty finished transcription is no output, so a bare interrupted stays an input ack. + livePlugin + .onEventCallback(mockInvocationContext, outputTranscriptionEvent("", /* finished= */ true)) + .blockingSubscribe(); + livePlugin.onEventCallback(mockInvocationContext, bareInterrupted).blockingSubscribe(); + assertEquals(llmSpanId, traceManager.getCurrentSpanId(mockInvocationContext).orElse(null)); + + // Spoken text is output, so the next bare interrupted ends the turn. + livePlugin + .onEventCallback( + mockInvocationContext, outputTranscriptionEvent("Hi", /* finished= */ false)) + .blockingSubscribe(); + livePlugin.onEventCallback(mockInvocationContext, bareInterrupted).blockingSubscribe(); + assertEquals(agentSpanId, traceManager.getCurrentSpanId(mockInvocationContext).orElse(null)); + } + + @Test + public void + liveOnEventCallback_preOutputTurnCompleteAfterToolResponse_keepsReopenedLlmRequestSpanOpen() + throws Exception { + List> rows = new CopyOnWriteArrayList<>(); + BigQueryAgentAnalyticsPlugin livePlugin = newRowRecordingPlugin(rows); + AtomicLong clockMillis = new AtomicLong(100L); + when(mockInvocationContext.now()) + .thenAnswer(invocation -> Instant.ofEpochMilli(clockMillis.get())); + when(mockInvocationContext.liveRequestQueue()).thenReturn(Optional.of(new LiveRequestQueue())); + when(mockInvocationContext.runConfig()).thenReturn(RunConfig.builder().build()); + CallbackContext callbackContext = mock(CallbackContext.class); + when(callbackContext.invocationContext()).thenReturn(mockInvocationContext); + Event bareTurnComplete = Event.builder().author("agent_name").turnComplete(true).build(); + + livePlugin.beforeRunCallback(mockInvocationContext).blockingSubscribe(); + livePlugin.beforeAgentCallback(fakeAgent, callbackContext).blockingSubscribe(); + TraceManager traceManager = livePlugin.getState().getTraceManager("invocation_id"); + String agentSpanId = (String) onlyRow(rows, "AGENT_STARTING").get("span_id"); + livePlugin.onEventCallback(mockInvocationContext, toolResponseEvent()).blockingSubscribe(); + String reopenedLlmSpanId = traceManager.getCurrentSpanId(mockInvocationContext).orElseThrow(); + assertNotEquals(agentSpanId, reopenedLlmSpanId); + + // The server may end the tool-call turn after the tool response, before the reply starts. + livePlugin + .onEventCallback(mockInvocationContext, outputTranscriptionEvent("", /* finished= */ true)) + .blockingSubscribe(); + livePlugin.onEventCallback(mockInvocationContext, bareTurnComplete).blockingSubscribe(); + assertEquals( + reopenedLlmSpanId, traceManager.getCurrentSpanId(mockInvocationContext).orElse(null)); + + clockMillis.set(400L); + livePlugin.afterModelCallback(callbackContext, spokenChunk("It is 72")).blockingSubscribe(); + livePlugin + .onEventCallback( + mockInvocationContext, outputTranscriptionEvent("It is 72", /* finished= */ false)) + .blockingSubscribe(); + livePlugin.onEventCallback(mockInvocationContext, bareTurnComplete).blockingSubscribe(); + assertEquals(agentSpanId, traceManager.getCurrentSpanId(mockInvocationContext).orElse(null)); + + // The reply is measured on the reopened span rather than a synthetic one without latency. + Map llmResponse = onlyRow(rows, "LLM_RESPONSE"); + assertEquals(reopenedLlmSpanId, llmResponse.get("span_id")); + assertEquals(agentSpanId, llmResponse.get("parent_span_id")); + JsonNode latency = (JsonNode) llmResponse.get("latency_ms"); + assertNotNull("latency_ms should be recorded", latency); + assertEquals(300L, latency.get("total_ms").asLong()); + assertEquals(300L, latency.get("time_to_first_token_ms").asLong()); + } + + @Test + public void + liveOnEventCallback_nonBareTurnCompleteAfterToolResponse_closesReopenedLlmRequestSpan() + throws Exception { + List> rows = new CopyOnWriteArrayList<>(); + BigQueryAgentAnalyticsPlugin livePlugin = newRowRecordingPlugin(rows); + when(mockInvocationContext.liveRequestQueue()).thenReturn(Optional.of(new LiveRequestQueue())); + when(mockInvocationContext.runConfig()).thenReturn(RunConfig.builder().build()); + CallbackContext callbackContext = mock(CallbackContext.class); + when(callbackContext.invocationContext()).thenReturn(mockInvocationContext); + livePlugin.beforeRunCallback(mockInvocationContext).blockingSubscribe(); + livePlugin.beforeAgentCallback(fakeAgent, callbackContext).blockingSubscribe(); + TraceManager traceManager = livePlugin.getState().getTraceManager("invocation_id"); + String agentSpanId = (String) onlyRow(rows, "AGENT_STARTING").get("span_id"); + + // Only a bare turn_complete can trail the tool-call turn; these end the post-tool reply. + ImmutableList turnEnds = + ImmutableList.of( + Event.builder() + .author("agent_name") + .content(Content.fromParts(Part.fromText("Blocked reply."))) + .turnComplete(true) + .build(), + Event.builder() + .author("agent_name") + .outputTranscription( + Transcription.builder().text("Blocked.").finished(false).build()) + .turnComplete(true) + .build(), + Event.builder() + .author("agent_name") + .errorCode(new FinishReason(FinishReason.Known.SAFETY)) + .turnComplete(true) + .build(), + Event.builder().author("agent_name").interrupted(true).turnComplete(true).build()); + for (Event turnEnd : turnEnds) { + livePlugin.onEventCallback(mockInvocationContext, toolResponseEvent()).blockingSubscribe(); + assertNotEquals( + agentSpanId, traceManager.getCurrentSpanId(mockInvocationContext).orElse(null)); + + livePlugin.onEventCallback(mockInvocationContext, turnEnd).blockingSubscribe(); + + assertEquals(agentSpanId, traceManager.getCurrentSpanId(mockInvocationContext).orElse(null)); + } + } + + @Test + public void + liveOnEventCallback_bareBoundaryWithEmptyOutputTranscription_keepsReopenedLlmRequestSpanOpen() + throws Exception { + List> rows = new CopyOnWriteArrayList<>(); + BigQueryAgentAnalyticsPlugin livePlugin = newRowRecordingPlugin(rows); + when(mockInvocationContext.liveRequestQueue()).thenReturn(Optional.of(new LiveRequestQueue())); + when(mockInvocationContext.runConfig()).thenReturn(RunConfig.builder().build()); + CallbackContext callbackContext = mock(CallbackContext.class); + when(callbackContext.invocationContext()).thenReturn(mockInvocationContext); + Transcription emptyTranscription = Transcription.builder().text("").finished(true).build(); + livePlugin.beforeRunCallback(mockInvocationContext).blockingSubscribe(); + livePlugin.beforeAgentCallback(fakeAgent, callbackContext).blockingSubscribe(); + TraceManager traceManager = livePlugin.getState().getTraceManager("invocation_id"); + livePlugin.onEventCallback(mockInvocationContext, toolResponseEvent()).blockingSubscribe(); + String reopenedLlmSpanId = traceManager.getCurrentSpanId(mockInvocationContext).orElseThrow(); + + // An empty transcription adds no output to the boundary that carries it. + livePlugin + .onEventCallback( + mockInvocationContext, + Event.builder() + .author("agent_name") + .outputTranscription(emptyTranscription) + .interrupted(true) + .build()) + .blockingSubscribe(); + assertEquals( + reopenedLlmSpanId, traceManager.getCurrentSpanId(mockInvocationContext).orElse(null)); + livePlugin + .onEventCallback( + mockInvocationContext, + Event.builder() + .author("agent_name") + .outputTranscription(emptyTranscription) + .turnComplete(true) + .build()) + .blockingSubscribe(); + assertEquals( + reopenedLlmSpanId, traceManager.getCurrentSpanId(mockInvocationContext).orElse(null)); + } + + @Test + public void liveOnEventCallback_silentPostToolTurn_secondBareTurnCompleteClosesReopenedSpan() + throws Exception { + List> rows = new CopyOnWriteArrayList<>(); + BigQueryAgentAnalyticsPlugin livePlugin = newRowRecordingPlugin(rows); + when(mockInvocationContext.liveRequestQueue()).thenReturn(Optional.of(new LiveRequestQueue())); + when(mockInvocationContext.runConfig()).thenReturn(RunConfig.builder().build()); + CallbackContext callbackContext = mock(CallbackContext.class); + when(callbackContext.invocationContext()).thenReturn(mockInvocationContext); + Event bareTurnComplete = Event.builder().author("agent_name").turnComplete(true).build(); + livePlugin.beforeRunCallback(mockInvocationContext).blockingSubscribe(); + livePlugin.beforeAgentCallback(fakeAgent, callbackContext).blockingSubscribe(); + TraceManager traceManager = livePlugin.getState().getTraceManager("invocation_id"); + String agentSpanId = (String) onlyRow(rows, "AGENT_STARTING").get("span_id"); + livePlugin.onEventCallback(mockInvocationContext, toolResponseEvent()).blockingSubscribe(); + String reopenedLlmSpanId = traceManager.getCurrentSpanId(mockInvocationContext).orElseThrow(); + + // Only the first turn_complete can trail the tool-call turn; the next ends a silent reply. + livePlugin.onEventCallback(mockInvocationContext, bareTurnComplete).blockingSubscribe(); + assertEquals( + reopenedLlmSpanId, traceManager.getCurrentSpanId(mockInvocationContext).orElse(null)); + livePlugin.onEventCallback(mockInvocationContext, bareTurnComplete).blockingSubscribe(); + assertEquals(agentSpanId, traceManager.getCurrentSpanId(mockInvocationContext).orElse(null)); + + // Later output opens a span of its own, which has no request start to measure from. + livePlugin.afterModelCallback(callbackContext, spokenChunk("Hello")).blockingSubscribe(); + Map llmResponse = onlyRow(rows, "LLM_RESPONSE"); + assertNotEquals(reopenedLlmSpanId, llmResponse.get("span_id")); + assertEquals(agentSpanId, llmResponse.get("parent_span_id")); + assertNull(llmResponse.get("latency_ms")); + } + /** Returns a partial live response carrying one chunk of the model's spoken output. */ private static LlmResponse spokenChunk(String text) { return LlmResponse.builder() @@ -3625,11 +3980,43 @@ private static LlmResponse spokenChunk(String text) { .build(); } + /** Returns a live model event carrying only an output transcription chunk. */ + private static Event outputTranscriptionEvent(String text, boolean finished) { + return Event.builder() + .author("agent_name") + .outputTranscription(Transcription.builder().text(text).finished(finished).build()) + .partial(!finished) + .build(); + } + + /** Returns a live event carrying only a tool's response, which reopens an llm_request span. */ + private static Event toolResponseEvent() { + return Event.builder() + .author("agent_name") + .content( + Content.fromParts( + Part.builder() + .functionResponse( + FunctionResponse.builder() + .id("fc-weather") + .name("lookup_weather") + .response(ImmutableMap.of("temp_f", 72)) + .build()) + .build())) + .build(); + } + /** Returns a plugin whose state also records every appended row, in append order. */ private BigQueryAgentAnalyticsPlugin newRowRecordingPlugin(List> rows) throws IOException { + return newRowRecordingPlugin(config, rows); + } + + /** Returns a plugin for {@code pluginConfig} whose state also records every appended row. */ + private BigQueryAgentAnalyticsPlugin newRowRecordingPlugin( + BigQueryLoggerConfig pluginConfig, List> rows) throws IOException { PluginState recordingState = - new PluginState(config) { + new PluginState(pluginConfig) { @Override protected BigQueryWriteClient createWriteClient(BigQueryLoggerConfig config) { return mockWriteClient; @@ -3648,7 +4035,7 @@ void appendRow( } }; BigQueryAgentAnalyticsPlugin recordingPlugin = - new BigQueryAgentAnalyticsPlugin(config, mockBigQuery, recordingState); + new BigQueryAgentAnalyticsPlugin(pluginConfig, mockBigQuery, recordingState); pluginsToClose.add(recordingPlugin); return recordingPlugin; } diff --git a/core/src/test/java/com/google/adk/plugins/agentanalytics/TraceManagerTest.java b/core/src/test/java/com/google/adk/plugins/agentanalytics/TraceManagerTest.java index f817192ff..dca9a28d2 100644 --- a/core/src/test/java/com/google/adk/plugins/agentanalytics/TraceManagerTest.java +++ b/core/src/test/java/com/google/adk/plugins/agentanalytics/TraceManagerTest.java @@ -28,6 +28,7 @@ import com.google.adk.agents.BaseAgent; import com.google.adk.agents.InvocationContext; import com.google.adk.events.Event; +import com.google.adk.plugins.agentanalytics.TraceManager.LiveTurnBoundaryKind; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Context; @@ -563,7 +564,7 @@ public void popLlmRequestSpanForEvent_andPopLiveLlmRequestSpan_handleEventIdMatc // Live mode closes the active llm_request span regardless of event ID. Optional popped = traceManager.popLiveLlmRequestSpan( - root, /* eventBranch= */ null, /* isBareInterrupted= */ false); + root, /* eventBranch= */ null, LiveTurnBoundaryKind.TERMINAL); assertTrue(popped.isPresent()); assertEquals(llmSpan, popped.get().spanId()); assertEquals(agentSpan, traceManager.getCurrentSpanId(root).orElse(null)); @@ -582,11 +583,12 @@ public void popLiveLlmRequestSpan_bareInterruptedBeforeOrderedOutput_keepsSpanOp assertTrue( traceManager .captureLlmResponseSpan(root, /* isLive= */ true, /* isPartial= */ true) - .firstTokenTime() + .timeToFirstToken() .isPresent()); assertFalse( traceManager - .popLiveLlmRequestSpan(root, /* eventBranch= */ null, /* isBareInterrupted= */ true) + .popLiveLlmRequestSpan( + root, /* eventBranch= */ null, LiveTurnBoundaryKind.BARE_INTERRUPTED) .isPresent()); assertEquals(llmSpan, traceManager.getCurrentSpanId(root).orElse(null)); @@ -594,12 +596,165 @@ public void popLiveLlmRequestSpan_bareInterruptedBeforeOrderedOutput_keepsSpanOp traceManager.markLiveOutputObserved(root, /* eventBranch= */ null); Optional popped = traceManager.popLiveLlmRequestSpan( - root, /* eventBranch= */ null, /* isBareInterrupted= */ true); + root, /* eventBranch= */ null, LiveTurnBoundaryKind.BARE_INTERRUPTED); assertTrue(popped.isPresent()); assertEquals(llmSpan, popped.get().spanId()); assertEquals(agentSpan, traceManager.getCurrentSpanId(root).orElse(null)); } + @Test + public void popLiveLlmRequestSpan_bareTurnCompleteOnReopenedSpan_keepsSpanOpenUntilOutput() { + InvocationContext root = branchContext("inv", null); + setNow(root, 100L); + traceManager.ensureInvocationSpan(root); + String agentSpan = traceManager.pushSpan(root, "agent:root"); + String reopenedSpan = + traceManager.ensureLiveLlmRequestSpan(root, /* eventBranch= */ null).spanId(); + + // Receive-thread firstTokenTime alone must not let a stale turn_complete close the span. + setNow(root, 150L); + assertTrue( + traceManager + .captureLlmResponseSpan(root, /* isLive= */ true, /* isPartial= */ true) + .timeToFirstToken() + .isPresent()); + assertFalse( + traceManager + .popLiveLlmRequestSpan( + root, /* eventBranch= */ null, LiveTurnBoundaryKind.BARE_TURN_COMPLETE) + .isPresent()); + assertEquals(reopenedSpan, traceManager.getCurrentSpanId(root).orElse(null)); + + // Once ordered output is observed, turn_complete closes the span back to agentSpan. + traceManager.markLiveOutputObserved(root, /* eventBranch= */ null); + Optional popped = + traceManager.popLiveLlmRequestSpan( + root, /* eventBranch= */ null, LiveTurnBoundaryKind.BARE_TURN_COMPLETE); + assertTrue(popped.isPresent()); + assertEquals(reopenedSpan, popped.get().spanId()); + assertEquals(agentSpan, traceManager.getCurrentSpanId(root).orElse(null)); + } + + @Test + public void popLiveLlmRequestSpan_secondBareTurnCompleteOnSilentReopenedSpan_closesSpan() { + InvocationContext root = branchContext("inv", null); + traceManager.ensureInvocationSpan(root); + String agentSpan = traceManager.pushSpan(root, "agent:root"); + String reopenedSpan = + traceManager.ensureLiveLlmRequestSpan(root, /* eventBranch= */ null).spanId(); + + // Only the first turn_complete can trail the tool-call turn; the next ends a silent reply. + assertFalse( + traceManager + .popLiveLlmRequestSpan( + root, /* eventBranch= */ null, LiveTurnBoundaryKind.BARE_TURN_COMPLETE) + .isPresent()); + assertEquals(reopenedSpan, traceManager.getCurrentSpanId(root).orElse(null)); + Optional popped = + traceManager.popLiveLlmRequestSpan( + root, /* eventBranch= */ null, LiveTurnBoundaryKind.BARE_TURN_COMPLETE); + + assertTrue(popped.isPresent()); + assertEquals(reopenedSpan, popped.get().spanId()); + assertEquals(agentSpan, traceManager.getCurrentSpanId(root).orElse(null)); + } + + @Test + public void ensureLiveLlmRequestSpan_reusingRacedSyntheticSpan_ignoresOneStaleTurnComplete() { + InvocationContext root = branchContext("inv", null); + setNow(root, 100L); + traceManager.ensureInvocationSpan(root); + String agentSpan = traceManager.pushSpan(root, "agent:root"); + + // The reply's first chunk can open the span before the tool response event is processed. + String outputSpan = + traceManager + .captureLlmResponseSpan(root, /* isLive= */ true, /* isPartial= */ true) + .spanId() + .orElseThrow(); + TraceManager.SpanRecord reused = + traceManager.ensureLiveLlmRequestSpan(root, /* eventBranch= */ null); + assertEquals(outputSpan, reused.spanId()); + assertTrue(reused.hasSyntheticStartTime()); + assertFalse( + traceManager + .popLiveLlmRequestSpan( + root, /* eventBranch= */ null, LiveTurnBoundaryKind.BARE_TURN_COMPLETE) + .isPresent()); + + // The span still has no request start, so later chunks keep omitting latency. + setNow(root, 150L); + TraceManager.LlmResponseSpanSnapshot nextChunk = + traceManager.captureLlmResponseSpan(root, /* isLive= */ true, /* isPartial= */ true); + assertEquals(outputSpan, nextChunk.spanId().orElse(null)); + assertTrue(nextChunk.duration().isEmpty()); + + // Once ordered output is observed, the reply's own turn_complete closes the span. + traceManager.markLiveOutputObserved(root, /* eventBranch= */ null); + Optional popped = + traceManager.popLiveLlmRequestSpan( + root, /* eventBranch= */ null, LiveTurnBoundaryKind.BARE_TURN_COMPLETE); + assertTrue(popped.isPresent()); + assertEquals(outputSpan, popped.get().spanId()); + assertEquals(agentSpan, traceManager.getCurrentSpanId(root).orElse(null)); + } + + @Test + public void popLiveLlmRequestSpan_bareTurnCompleteOnSyntheticSpan_closesBeforeOutput() { + InvocationContext root = branchContext("inv", null); + traceManager.ensureInvocationSpan(root); + String agentSpan = traceManager.pushSpan(root, "agent:root"); + String outputSpan = + traceManager + .captureLlmResponseSpan(root, /* isLive= */ true, /* isPartial= */ true) + .spanId() + .orElseThrow(); + + // Only a tool response makes a span wait out the tool-call turn's turn_complete. + Optional popped = + traceManager.popLiveLlmRequestSpan( + root, /* eventBranch= */ null, LiveTurnBoundaryKind.BARE_TURN_COMPLETE); + + assertTrue(popped.isPresent()); + assertEquals(outputSpan, popped.get().spanId()); + assertEquals(agentSpan, traceManager.getCurrentSpanId(root).orElse(null)); + } + + @Test + public void popLiveLlmRequestSpan_bareTurnCompleteOnCallbackSpan_closesSpanBeforeOutput() { + InvocationContext root = branchContext("inv", null); + traceManager.ensureInvocationSpan(root); + String agentSpan = traceManager.pushSpan(root, "agent:root"); + String llmSpan = traceManager.replaceTopSpanRecord(root, "llm_request", "evt-live").spanId(); + + // A turn that a model callback opened ends on its turn_complete even without any output. + Optional popped = + traceManager.popLiveLlmRequestSpan( + root, /* eventBranch= */ null, LiveTurnBoundaryKind.BARE_TURN_COMPLETE); + + assertTrue(popped.isPresent()); + assertEquals(llmSpan, popped.get().spanId()); + assertEquals(agentSpan, traceManager.getCurrentSpanId(root).orElse(null)); + } + + @Test + public void popLiveLlmRequestSpan_terminalBoundaryOnReopenedSpan_closesSpanBeforeOutput() { + InvocationContext root = branchContext("inv", null); + traceManager.ensureInvocationSpan(root); + String agentSpan = traceManager.pushSpan(root, "agent:root"); + String reopenedSpan = + traceManager.ensureLiveLlmRequestSpan(root, /* eventBranch= */ null).spanId(); + + // Only a bare turn_complete can trail the tool-call turn; any other boundary ends the span. + Optional popped = + traceManager.popLiveLlmRequestSpan( + root, /* eventBranch= */ null, LiveTurnBoundaryKind.TERMINAL); + + assertTrue(popped.isPresent()); + assertEquals(reopenedSpan, popped.get().spanId()); + assertEquals(agentSpan, traceManager.getCurrentSpanId(root).orElse(null)); + } + @Test public void replaceTopSpanRecord_concurrentCalls_neverNestsLlmRequests() throws Exception { InvocationContext ctx = branchContext("inv", null); @@ -697,19 +852,29 @@ public void pushAgentSpanRecord_childBranchWithAncestorLlmRequest_parentsToAnces @Test public void replaceTopSpanRecord_nonLiveAfterPartialChunk_preservesNextTurnFirstTokenTime() { InvocationContext root = branchContext("inv", null); + setNow(root, 100L); traceManager.ensureInvocationSpan(root); traceManager.pushSpan(root, "agent:root"); TraceManager.SpanRecord step1 = traceManager.replaceTopSpanRecord(root, "llm_request", "evt-step-1"); - traceManager.recordFirstToken(step1.spanId()); + setNow(root, 120L); + assertEquals( + Optional.of(Duration.ofMillis(20L)), + traceManager + .captureLlmResponseSpan(root, /* isLive= */ false, /* isPartial= */ true) + .timeToFirstToken()); + // Step 1 never got a final response, so step 2 replaces it and times its own first token. + setNow(root, 200L); TraceManager.SpanRecord step2 = traceManager.replaceTopSpanRecord(root, "llm_request", "evt-step-2"); assertNotEquals(step1.spanId(), step2.spanId()); - assertTrue(traceManager.getFirstTokenTime(step2.spanId()).isEmpty()); - traceManager.recordFirstToken(step2.spanId()); + setNow(root, 250L); + TraceManager.LlmResponseSpanSnapshot step2Chunk = + traceManager.captureLlmResponseSpan(root, /* isLive= */ false, /* isPartial= */ true); - assertTrue(traceManager.getFirstTokenTime(step2.spanId()).isPresent()); + assertEquals(step2.spanId(), step2Chunk.spanId().orElse(null)); + assertEquals(Optional.of(Duration.ofMillis(50L)), step2Chunk.timeToFirstToken()); } @Test @@ -759,6 +924,9 @@ public void replaceTopSpanRecord_withRunningAsyncTool_parentsLlmRequestToAgent() @Test public void ensureInvocationSpan_afterClear_reseedsSpanForSameInvocation() { + // hasAnyRecords() must report EMPTY after clearStack, so a same-invocation ensureInvocationSpan + // re-seeds the root span instead of early-returning on a stale activeInvocationId match. A + // hasAnyRecords()-always-true bug would take the equals() early return and leave no span. try (Scope ignored = Context.root().makeCurrent()) { traceManager.ensureInvocationSpan(mockContext); assertTrue(traceManager.getCurrentSpanId(mockContext).isPresent()); @@ -779,16 +947,39 @@ public void ensureInvocationSpan_afterClear_reseedsSpanForSameInvocation() { getCurrentAgentOrInvocationSpanAndParent_skipsActiveLlmAndToolSpansAndPrefersAuthor() { InvocationContext root = branchContext("inv", null); String invocationSpan = traceManager.pushSpan(root, "invocation"); - String agentSpan = traceManager.pushSpan(root, "agent:root"); + String rootAgentSpan = traceManager.pushSpan(root, "agent:root"); + String workerAgentSpan = traceManager.pushSpan(root, "agent:worker"); traceManager.pushToolSpanRecord(root, "fc-running"); traceManager.replaceTopSpanRecord(root, "llm_request", "evt-turn-1"); - TraceManager.SpanIds nonLlm = + // A matching author wins over the newer agent span of a sub-agent that has already started. + TraceManager.SpanIds authored = traceManager.getCurrentAgentOrInvocationSpanAndParent( root, /* eventBranch= */ null, "root"); + assertEquals(rootAgentSpan, authored.spanId().orElse(null)); + assertEquals(invocationSpan, authored.parentSpanId().orElse(null)); + + // Without a matching agent span, the newest span that is no model or tool span is used. + TraceManager.SpanIds unauthored = + traceManager.getCurrentAgentOrInvocationSpanAndParent( + root, /* eventBranch= */ null, /* author= */ null); + assertEquals(workerAgentSpan, unauthored.spanId().orElse(null)); + assertEquals(rootAgentSpan, unauthored.parentSpanId().orElse(null)); + TraceManager.SpanIds unmatched = + traceManager.getCurrentAgentOrInvocationSpanAndParent( + root, /* eventBranch= */ null, "unmatched"); + assertEquals(workerAgentSpan, unmatched.spanId().orElse(null)); + assertEquals(rootAgentSpan, unmatched.parentSpanId().orElse(null)); - assertEquals(agentSpan, nonLlm.spanId().orElse(null)); - assertEquals(invocationSpan, nonLlm.parentSpanId().orElse(null)); + // With no agent span at all, that fallback is the invocation span. + traceManager.clearStack(); + String loneInvocationSpan = traceManager.pushSpan(root, "invocation"); + traceManager.replaceTopSpanRecord(root, "llm_request", "evt-turn-2"); + TraceManager.SpanIds invocationOnly = + traceManager.getCurrentAgentOrInvocationSpanAndParent( + root, /* eventBranch= */ null, "unmatched"); + assertEquals(loneInvocationSpan, invocationOnly.spanId().orElse(null)); + assertTrue(invocationOnly.parentSpanId().isEmpty()); } @Test @@ -805,24 +996,23 @@ public void captureLlmResponseSpan_liveOpenSpan_recordsMonotonicFirstTokenAndDur traceManager.captureLlmResponseSpan(root, /* isLive= */ true, /* isPartial= */ true); assertEquals(llmSpan.spanId(), firstPartial.spanId().orElse(null)); assertEquals(agentSpan, firstPartial.parentSpanId().orElse(null)); - assertEquals(Instant.ofEpochMilli(100L), firstPartial.startTime().orElse(null)); - assertEquals(Instant.ofEpochMilli(150L), firstPartial.firstTokenTime().orElse(null)); - assertEquals(Duration.ofMillis(50L), firstPartial.duration()); + assertEquals(Optional.of(Duration.ofMillis(50L)), firstPartial.timeToFirstToken()); + assertEquals(Optional.of(Duration.ofMillis(50L)), firstPartial.duration()); assertEquals(llmSpan.spanId(), traceManager.getCurrentSpanId(root).orElse(null)); setNow(root, 220L); TraceManager.LlmResponseSpanSnapshot secondPartial = traceManager.captureLlmResponseSpan(root, /* isLive= */ true, /* isPartial= */ true); - assertEquals(Instant.ofEpochMilli(150L), secondPartial.firstTokenTime().orElse(null)); - assertEquals(Duration.ofMillis(120L), secondPartial.duration()); + assertEquals(Optional.of(Duration.ofMillis(50L)), secondPartial.timeToFirstToken()); + assertEquals(Optional.of(Duration.ofMillis(120L)), secondPartial.duration()); setNow(root, 300L); TraceManager.LlmResponseSpanSnapshot finalResponse = traceManager.captureLlmResponseSpan(root, /* isLive= */ true, /* isPartial= */ false); assertEquals(llmSpan.spanId(), finalResponse.spanId().orElse(null)); assertEquals(agentSpan, finalResponse.parentSpanId().orElse(null)); - assertEquals(Instant.ofEpochMilli(150L), finalResponse.firstTokenTime().orElse(null)); - assertEquals(Duration.ofMillis(200L), finalResponse.duration()); + assertEquals(Optional.of(Duration.ofMillis(50L)), finalResponse.timeToFirstToken()); + assertEquals(Optional.of(Duration.ofMillis(200L)), finalResponse.duration()); assertEquals(agentSpan, traceManager.getCurrentSpanId(root).orElse(null)); } @@ -839,18 +1029,16 @@ public void captureLlmResponseSpan_liveSyntheticSpan_omitsLatencyAndSkipsRunning traceManager.captureLlmResponseSpan(root, /* isLive= */ true, /* isPartial= */ true); assertTrue(partial.spanId().isPresent()); assertEquals(agentSpan, partial.parentSpanId().orElse(null)); - assertTrue(partial.startTime().isEmpty()); - assertTrue(partial.firstTokenTime().isEmpty()); - assertTrue(partial.duration().isZero()); + assertTrue(partial.duration().isEmpty()); + assertTrue(partial.timeToFirstToken().isEmpty()); setNow(root, 250L); TraceManager.LlmResponseSpanSnapshot finalResponse = traceManager.captureLlmResponseSpan(root, /* isLive= */ true, /* isPartial= */ false); assertEquals(partial.spanId(), finalResponse.spanId()); assertEquals(agentSpan, finalResponse.parentSpanId().orElse(null)); - assertTrue(finalResponse.startTime().isEmpty()); - assertTrue(finalResponse.firstTokenTime().isEmpty()); - assertTrue(finalResponse.duration().isZero()); + assertTrue(finalResponse.duration().isEmpty()); + assertTrue(finalResponse.timeToFirstToken().isEmpty()); } @Test @@ -866,9 +1054,8 @@ public void captureLlmResponseSpan_nonLivePartialAndFinal_usesSingleTimestampAnd TraceManager.LlmResponseSpanSnapshot partial = traceManager.captureLlmResponseSpan(root, /* isLive= */ false, /* isPartial= */ true); assertEquals(llmSpan.spanId(), partial.spanId().orElse(null)); - assertEquals(Instant.ofEpochMilli(100L), partial.startTime().orElse(null)); - assertEquals(Instant.ofEpochMilli(130L), partial.firstTokenTime().orElse(null)); - assertEquals(Duration.ofMillis(30L), partial.duration()); + assertEquals(Optional.of(Duration.ofMillis(30L)), partial.timeToFirstToken()); + assertEquals(Optional.of(Duration.ofMillis(30L)), partial.duration()); assertEquals(llmSpan.spanId(), traceManager.getCurrentSpanId(root).orElse(null)); setNow(root, 200L); @@ -876,11 +1063,83 @@ public void captureLlmResponseSpan_nonLivePartialAndFinal_usesSingleTimestampAnd traceManager.captureLlmResponseSpan(root, /* isLive= */ false, /* isPartial= */ false); assertEquals(llmSpan.spanId(), finalResponse.spanId().orElse(null)); assertEquals(agentSpan, finalResponse.parentSpanId().orElse(null)); - assertEquals(Instant.ofEpochMilli(130L), finalResponse.firstTokenTime().orElse(null)); - assertEquals(Duration.ofMillis(100L), finalResponse.duration()); + assertEquals(Optional.of(Duration.ofMillis(30L)), finalResponse.timeToFirstToken()); + assertEquals(Optional.of(Duration.ofMillis(100L)), finalResponse.duration()); assertEquals(agentSpan, traceManager.getCurrentSpanId(root).orElse(null)); } + @Test + public void captureLlmResponseSpan_zeroElapsedTime_preservesZeroDurationAndTtft() { + InvocationContext root = branchContext("inv", null); + setNow(root, 100L); + traceManager.ensureInvocationSpan(root); + traceManager.pushSpan(root, "agent:root"); + traceManager.replaceTopSpanRecord(root, "llm_request", "evt-1"); + + // No time has passed since the request, which is a measured zero and not a missing latency. + TraceManager.LlmResponseSpanSnapshot partial = + traceManager.captureLlmResponseSpan(root, /* isLive= */ false, /* isPartial= */ true); + assertEquals(Optional.of(Duration.ZERO), partial.duration()); + assertEquals(Optional.of(Duration.ZERO), partial.timeToFirstToken()); + + TraceManager.LlmResponseSpanSnapshot finalResponse = + traceManager.captureLlmResponseSpan(root, /* isLive= */ false, /* isPartial= */ false); + assertEquals(Optional.of(Duration.ZERO), finalResponse.duration()); + assertEquals(Optional.of(Duration.ZERO), finalResponse.timeToFirstToken()); + } + + @Test + public void captureLlmResponseSpan_nonLiveEmptyStack_returnsEmptySnapshotWithoutThrowing() { + InvocationContext root = branchContext("inv", null); + TraceManager.LlmResponseSpanSnapshot empty = + TraceManager.LlmResponseSpanSnapshot.create( + /* spanId= */ null, + /* parentSpanId= */ null, + /* duration= */ null, + /* timeToFirstToken= */ null); + + // The branch has no stack yet. + assertEquals( + empty, + traceManager.captureLlmResponseSpan(root, /* isLive= */ false, /* isPartial= */ true)); + assertEquals( + empty, + traceManager.captureLlmResponseSpan(root, /* isLive= */ false, /* isPartial= */ false)); + + // The branch's stack exists but has been drained. + traceManager.pushSpan(root, "agent:root"); + assertTrue(traceManager.popSpan(root, "agent:").isPresent()); + assertEquals( + empty, + traceManager.captureLlmResponseSpan(root, /* isLive= */ false, /* isPartial= */ true)); + assertEquals( + empty, + traceManager.captureLlmResponseSpan(root, /* isLive= */ false, /* isPartial= */ false)); + } + + @Test + public void + captureLlmResponseSpan_nonLiveChildBranchWithAncestorLlmRequest_usesAncestorAgentNoTiming() { + InvocationContext coordinator = branchContext("inv", "par.coord"); + traceManager.ensureInvocationSpan(coordinator); + String invocationSpan = traceManager.getCurrentSpanId(coordinator).orElseThrow(); + String coordinatorSpan = traceManager.pushSpan(coordinator, "agent:coord"); + String coordinatorLlmSpan = + traceManager.replaceTopSpanRecord(coordinator, "llm_request", "evt-coord").spanId(); + InvocationContext worker = branchContext("inv", "par.coord.worker"); + + // The worker has no span of its own, and the coordinator's model call is not the worker's. + TraceManager.LlmResponseSpanSnapshot snapshot = + traceManager.captureLlmResponseSpan(worker, /* isLive= */ false, /* isPartial= */ false); + + assertEquals(coordinatorSpan, snapshot.spanId().orElse(null)); + assertEquals(invocationSpan, snapshot.parentSpanId().orElse(null)); + assertTrue(snapshot.duration().isEmpty()); + assertTrue(snapshot.timeToFirstToken().isEmpty()); + assertTrue(traceManager.getFirstTokenTime(coordinatorLlmSpan).isEmpty()); + assertEquals(coordinatorLlmSpan, traceManager.getCurrentSpanId(coordinator).orElse(null)); + } + @Test public void captureLlmResponseSpan_nonLiveWithoutLlmRequestSpan_preservesIdsWithoutTimingOrMutation() { @@ -895,9 +1154,8 @@ public void captureLlmResponseSpan_nonLivePartialAndFinal_usesSingleTimestampAnd traceManager.captureLlmResponseSpan(root, /* isLive= */ false, /* isPartial= */ true); assertEquals(agentSpan, partial.spanId().orElse(null)); assertEquals(invocationSpan, partial.parentSpanId().orElse(null)); - assertTrue(partial.startTime().isEmpty()); - assertTrue(partial.firstTokenTime().isEmpty()); - assertEquals(Duration.ZERO, partial.duration()); + assertTrue(partial.duration().isEmpty()); + assertTrue(partial.timeToFirstToken().isEmpty()); assertTrue(traceManager.getFirstTokenTime(agentSpan).isEmpty()); assertEquals(agentSpan, traceManager.getCurrentSpanId(root).orElse(null)); @@ -906,9 +1164,8 @@ public void captureLlmResponseSpan_nonLivePartialAndFinal_usesSingleTimestampAnd traceManager.captureLlmResponseSpan(root, /* isLive= */ false, /* isPartial= */ false); assertEquals(agentSpan, finalResponse.spanId().orElse(null)); assertEquals(invocationSpan, finalResponse.parentSpanId().orElse(null)); - assertTrue(finalResponse.startTime().isEmpty()); - assertTrue(finalResponse.firstTokenTime().isEmpty()); - assertEquals(Duration.ZERO, finalResponse.duration()); + assertTrue(finalResponse.duration().isEmpty()); + assertTrue(finalResponse.timeToFirstToken().isEmpty()); assertTrue(traceManager.getFirstTokenTime(agentSpan).isEmpty()); assertEquals(agentSpan, traceManager.getCurrentSpanId(root).orElse(null)); } @@ -941,16 +1198,11 @@ public void captureLlmResponseSpan_concurrentLiveReplace_alwaysReturnsConsistent TraceManager.LlmResponseSpanSnapshot snapshot = captureFuture.get(10, SECONDS); if (snapshot.spanId().isEmpty() || !agentSpan.equals(snapshot.parentSpanId().orElse(null)) - || snapshot.startTime().isEmpty() - || snapshot.firstTokenTime().isEmpty() - || snapshot.duration().isNegative()) { + || snapshot.duration().isEmpty() + || snapshot.timeToFirstToken().isEmpty() + || snapshot.duration().get().isNegative() + || snapshot.timeToFirstToken().get().compareTo(snapshot.duration().get()) > 0) { inconsistent++; - } else { - Duration ttft = - Duration.between(snapshot.startTime().get(), snapshot.firstTokenTime().get()); - if (ttft.compareTo(snapshot.duration()) > 0) { - inconsistent++; - } } } } finally {