Skip to content

fix(trace): read final_response from the current invocation and parse the plugin's parts - #601

Merged
caohy1988 merged 4 commits into
GoogleCloudPlatform:mainfrom
yihuang0830:fix/final-response-followups
Nov 24, 2026
Merged

caohy1988 merged 4 commits into
GoogleCloudPlatform:mainfrom
yihuang0830:fix/final-response-followups

Conversation

@yihuang0830

@yihuang0830 yihuang0830 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #595: the follow-ups from reviewing #593.

Trace.final_response and SessionTrace.extract_final_response() now share one implementation, trace._final_answer. The SQL judge picks the final answer with the same rules. Because the rules in #594 read Trace.final_response, this also covers the AGENT_RESPONSE item of #600.

What changed, by item

1. Only the current invocation is read.

  • The answer comes from the session's latest invocation. A turn that never answered no longer returns the previous turn's answer.
  • ADK rows carry attributes.adk, so their invocation_id always marks the run, even after an event-type filter leaves one row of it.
  • For other producers, ids count only when some id is shared by two rows. seed_events, for example, gives every row its own id. There, the run is the latest id that is shared or that sits on a response row. Otherwise the run is the rows after the last USER_MESSAGE_RECEIVED.
  • A nested invocation (an agent called as a tool) is part of the run, but its turns are not the run's answer. An AgentTool session read on its own is a run of its own.
  • TraceEvent gains an invocation_id field, appended last.

2. The plugin's encoding is applied only to its rows.

  • Rows from the bundled tracing writer (attributes.writer) are verbatim.
  • So are AGENT_COMPLETED rows without attributes.adk. The plugin never fills these; EvalBench imports do.
  • Verbatim rows only lose a text: '...' wrapper, as on main.
  • call: <x> counts as a call only when <x> is a function name. call: 555-0100 is prose; call: 1password_lookup is a call.
  • text_summary is never decoded.

3. Clipped text is not read as a tool call.

  • A text part cut by truncation keeps its visible text and the ...[TRUNCATED] marker.
  • A cut right after a text part (...'ERROR' | c...[TRUNCATED]) stays text, because the cut may as well have landed inside the text.

4. Always a string or None.

  • A structured response or completion becomes its text_summary, or else compact JSON.
  • Completions go through the same filters, so call: exit_loop and None are not answers.

5. _flag treats NaN, NaT, pd.NA and b"false" as false.

6. The is_truncated docs now describe it as the producer's row-level flag.

7. Turns are parsed part by part.

  • A turn that calls a tool holds no answer, wherever the call is. The parser handles call: x | other, a call followed by text, trailing whitespace, and calls with arguments.
  • Text parts are unwrapped and joined with newlines. Turns with no text (other, resp:, code only) are skipped.
  • Model text is not escaped, so | may be text. A text or code part ends at the first separator after which the rest of the turn still parses.
  • Separators are visited once, so parsing takes O(n log n) time. A 500 KB answer, clipped or not, parses in about 0.3 s, and the result is cached per string. The old tail regex rescanned in quadratic time.

8. Pre-existing gaps.

  • extract_final_response now skips empty and usage-only turns, and unwraps text: '...' like Trace does.
  • The loader's {"raw": ...} wrapper is read.
  • AGENT_RESPONSE rows are read as model turns. The plugin writes them for a final response (its text without thoughts, or the arguments of a final_response_tool_names tool), and BQCA compatibility views answer there. A non-blank text_summary is read first, as the plugin's own eval views do. PerformanceEvaluator now fetches AGENT_RESPONSE by default.
  • The SQL judge (AI.GENERATE and ML.GENERATE_TEXT) gets the answer from shared CTEs, trace._final_response_sql, that apply these rules. The insights transcript query drops its final_response column, which no caller read.

Behaviour changes to note

  • SessionTrace.extract_final_response() now returns Done. where it returned text: 'Done.'. On our 933 KramaBench runs, this is the only change: 686 sessions. Trace.final_response is identical on all 933.
  • Multiple text parts are joined with newlines instead of being returned as a' | text: 'b.

Limits

  • Model text that spells out a whole valid turn, such as x' | call: f | text: 'y, reads as those parts. Nothing in the encoding tells the two apart.
  • RE2 has no lookahead, so the SQL looks one part ahead, where Python checks the rest of the turn. The two can still differ on model text that contains ' | followed by a part prefix, or on a code part followed by a clipped call. On generated producer-shaped sessions, that was 0–2 in 4,000.

Testing

  • tests/test_final_response.py (90 tests) runs every case through both accessors and checks that they agree.
  • tests/test_final_response_sql.py (156 tests) runs the judge SQL in SQLite, with BigQuery's functions shimmed in Python, and checks that it returns what Trace.final_response returns. Cases include generated plugin-shaped turns with code, tables and clipping.
  • Fuzzing against an oracle. I compared fix(trace): skip tool-call and empty turns in final_response; keep Span.is_truncated #593, main and this PR on 20,000 turns formatted like _format_content does. On clean, unclipped text this PR is always right. It fixes about 10,500 turns that fix(trace): skip tool-call and empty turns in final_response; keep Span.is_truncated #593 got wrong. fix(trace): skip tool-call and empty turns in final_response; keep Span.is_truncated #593 got 51 right that this PR gets wrong; all are cuts right after a text part, the trade-off in item 3.
  • Mutation testing. I mutated 64 conditions in the new code; each mutant makes at least one test fail.
  • Full pytest on Python 3.13 (macOS): 11619 passed, 87 skipped. I deselected the 4 browser_smoke Looker Studio tests because they hang on macOS.
  • Formatting. bash autoformat.sh leaves no diff.
  • BigQuery dry runs. I ran these against a real ADK agent_events table, with JSON content and attributes.
    • The final-answer CTEs on their own: valid.
    • The rendered AI.GENERATE judge query: valid.
    • The legacy ML.GENERATE_TEXT template fails with "Table-valued function is not expected here: ML.GENERATE_TEXT". The template on main (1e93119) fails the same way, so the cause is pre-existing: the template calls the TVF as a scalar. The error is in the outer SELECT, after the CTEs, so it is out of scope here.
… the plugin's parts

Address the follow-ups in GoogleCloudPlatform#595:

- Read only the session's latest invocation. Nested invocations are part
  of the run but never its answer.
- Parse the ADK plugin's part encoding structurally, in O(n log n): a
  turn that calls a tool holds no answer wherever the call is, clipped
  text keeps its visible text, and a call needs a function name.
- Apply the encoding only to plugin rows; bundled-writer rows and
  AGENT_COMPLETED rows without attributes.adk are verbatim.
- Read AGENT_RESPONSE rows, preferring their text_summary.
- Always return a string or None; skip empty and usage-only turns in
  SessionTrace; read the loader's {"raw": ...} wrapper.
- Make _flag treat NaN, NaT and bytes correctly.
- Pick the SQL judge's final answer with the same rules, and drop the
  unused final_response column from the insights transcript query.

Fixes GoogleCloudPlatform#595.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at ff0ebe7. Putting both accessors and the judge SQL behind one selection path is a nice cleanup, reading AGENT_RESPONSE fixes sessions whose only answer lives there, and the final-response tests plus the evaluator and insights suites pass here.

Approving. I filed #603 for edge cases I could reproduce offline. The most important ones: a new user message whose fresh invocation id hasn't repeated yet can still return the previous turn's answer, nested invocations deeper than one level make SQL drop the parent's answer, a JSON-string answer can lose fields in the row loader, and native content objects or part lists (including a function-call-only content) reach the judge as serialized JSON. A few Python/SQL parity gaps are listed there too.

haiyuan-eng-google and others added 2 commits November 23, 2026 22:44
LEFT() is reserved in SQLite, so the CI parity tests failed to parse the query. SUBSTR(..., 1, 1) is the same in BigQuery.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants