Repository navigation
feat(agentanalytics): add pre-built agent evaluation views (v_eval_session, v_eval_turn) - #2175
Conversation
|
Thanks for the PR, @haiyuan-eng-google. One thing before review. Our contribution guide asks for an issue behind each change, and I could not find one linked here.
If this is a small doc or typo fix, ignore me. A maintainer can open the issue for you if you would rather. |
3265e87 to
a01179f
Compare
…ssion, v_eval_turn) Add Config.CreateEvalViews, Config.EvalViewDefinitions(), and BigQueryAgentAnalyticsPlugin.SyncEvalViews(ctx) to create and synchronize the pre-built v_eval_session and v_eval_turn BigQuery evaluation views: - Reconstruct multi-turn session and single-turn AgentData trajectories, agent_configs maps, token usage rollups, error flags, and consecutive identical tool-call loop detection from the events table. - Scope session and turn rollups, window partitions, and agent_configs maps by ADK's composite session identity (app_name from attributes $.adk.app_name, user_id, session_id) with invocation-level backfill and NULL-safe IS NOT DISTINCT FROM joins. - Deduplicate retried Storage Write API rows sharing a non-empty event_id before trace reconstruction and metric aggregation while preserving rows with empty or NULL event_id and preferring complete, non-failed copies. - Reconstruct AGENT_RESPONSE response_text from ordered plain-text content_parts before falling back to formatted content.response when content_parts is empty or omitted. - Project typed NULL fallbacks in raw_events when content_parts, attributes, or latency_ms are listed in PayloadColumnDenylist, and reject CreateEvalViews / SyncEvalViews when content or required trace events are excluded. - Honor Config.ViewPrefix, identifier validation, table-collision checks, and Close() / SyncViews() view-gate preemption.
a01179f to
58c0070
Compare
wolo-lab
left a comment
There was a problem hiding this comment.
One thing must change before merge: the eval-view validator accepts a filter configuration under which the views can never mark a final-response-tool turn complete, and nothing tells the user.
Must change before merge: the "EVENT" alias does not cover the AGENT_RESPONSE row that a final-response tool writes
validateEvalViewConfig treats the legacy "EVENT" allowlist alias as covering AGENT_RESPONSE (views.go lines 370 to 380 and 405 to 419). That holds for the AGENT_RESPONSE row of a final model event, which goes through logSessionEvent. It does not hold when FinalResponseToolNames is set: the AGENT_RESPONSE row for the tool is written by afterTool through logEvent, and shouldLogEvent has no alias handling, so the row is dropped. The umbrella allowlist that the new test accepts at views_test.go lines 4072 to 4085, plus FinalResponseToolNames, therefore passes construction and SyncEvalViews, and every turn whose only AGENT_RESPONSE comes from the tool has no such row. By the view SQL that turn gets is_complete = false and eval_ready = false, the session view's eval_ready goes false with it, and the final response is missing from trace. No error, no log. The doc at config.go lines 491 to 493 promises a configuration error for exactly this.
The runtime asymmetry itself predates this PR and is pinned by the existing events_test.go cases around lines 920 to 945. What this PR adds is the validator's claim that the alias is enough, and adk-python requires every event by name. Whichever side you fix, the property to keep is: for each of the 15 required event types, the config-time accept or reject decision matches what every emitter of that type does at runtime under the same allowlist, denylist and FinalResponseToolNames, with CreateEvalViews=false behavior unchanged. A test that writes rows under the umbrella allowlist with a final-response tool would pin it. Two of the inline notes below (the alias-set comment and the denylist error message) are side effects of the same mismatch.
Reproduction. Drop into package agentanalytics and run go test -run TestRepro_Umbrella -v ./plugin/agentanalytics/
func TestRepro_UmbrellaAllowlistDropsFinalResponseAgentResponse(t *testing.T) {
umbrella := []string{"EVENT", EventAgentStarting, EventInvocationCompleted, EventLLMRequest, EventToolCompleted, EventToolStarting, EventUserMessageReceived}
run := func(t *testing.T, allowlist []string) (types []string) {
p, requests, mCtx := setupTestPluginWithConfig(t, func(c *Config) {
c.DisableCreateViews = true
c.CreateEvalViews = true
c.FinalResponseToolNames = []string{"final_answer"}
c.EventAllowlist = allowlist
})
mCtx.functionCallID = "fc-final-1"
finalTool := &fakeTool{name: "final_answer", description: "final"}
var errs callbackErrors
errs.add(p.OnUserMessageCallback()(mCtx, &genai.Content{Role: "user", Parts: []*genai.Part{{Text: "hi"}}}))
errs.add(p.BeforeRunCallback()(mCtx))
errs.add(p.BeforeAgentCallback()(mCtx))
errs.add(p.BeforeToolCallback()(mCtx, finalTool, map[string]any{"answer": "42"}))
errs.add(p.AfterToolCallback()(mCtx, finalTool, map[string]any{"answer": "42"}, map[string]any{"ok": true}, nil))
errs.add(p.AfterAgentCallback()(mCtx))
errs.check(t)
p.AfterRunCallback()(mCtx)
for _, r := range collectRows(t, requests, untilEventType(EventInvocationCompleted)) {
types = append(types, r["event_type"].(string))
}
return types
}
// Construction succeeds (the validator accepts the umbrella), but no AGENT_RESPONSE row is written:
// [USER_MESSAGE_RECEIVED AGENT_STARTING TOOL_STARTING TOOL_COMPLETED INVOCATION_COMPLETED]
if got := run(t, umbrella); slices.Contains(got, EventAgentResponse) {
t.Fatalf("unexpected AGENT_RESPONSE under umbrella allowlist: %v", got)
}
// Control, changing only the allowlist: the row comes back.
if got := run(t, append(slices.Clone(umbrella), EventAgentResponse)); !slices.Contains(got, EventAgentResponse) {
t.Fatalf("control failed: %v", got)
}
}A third arm that also sends a final model event with visible text gets exactly one AGENT_RESPONSE row, the text one. The tool-driven row is still absent.
Smaller things
- When only the eval views run at startup (
DisableCreateViews=true), a failed pass still logs "call SyncViews to retry", andSyncViewswould also create the 25 per-event views the user opted out of. That line is not in this diff, so no inline note. - Pre-existing, no action needed here: the
logSessionSpanEventdoc comment says final-response-tool AGENT_RESPONSE rows go through it, andConfig.EventAllowlistsays"EVENT"matches AGENT_RESPONSE. Both describe the path the blocking item shows is not taken. Worth fixing alongside, since they are the likely reason the validator was written this way.
The remaining notes are inline. Only the alias item above gates the merge.
Ensure validateEvalViewConfig matches runtime EVENT filter semantics: - Include TOOL_COMPLETED in evalViewLegacyDeniedEvents (resumed tool calls emit through logSessionSpanEvent). - Split legacy allowlist matching into evalViewLegacyAlwaysAllowedEvents and allow EVENT to satisfy AGENT_RESPONSE only when FinalResponseToolNames is empty. - Isolate per-event and eval startup view errors so eval TableName collisions or errors skip eval views without blocking per-event views. - Hint SyncEvalViews when an eval-only startup view pass fails DDL, and clarify Config and SyncEvalViews godoc comments. - Add regression tests for EVENT alias parity, startup isolation, SyncEvalViews preemption/validation ordering, and USER_MESSAGE_RECEIVED function_response JSONPath coverage.
… user text and instruction fallbacks When ContentFormatter returns an error for USER_MESSAGE_RECEIVED or AGENT_STARTING, addContent writes the scalar "[FORMATTER_FAILED]" to content with no content_parts. Wrap scalar JSON_VALUE(content, '$') fallbacks in NULLIF(..., '[FORMATTER_FAILED]') so a failed user-message formatter does not satisfy has_user_message (keeping eval_ready=false in v_eval_session and v_eval_turn) and a failed agent-starting formatter falls back to attributes.static_instruction, while preserving structured user messages whose text_summary or content_parts literally contain "[FORMATTER_FAILED]".
There was a problem hiding this comment.
Earlier review of a previous revision; the latest notes are in #2175 (review).
|
Hi @wolo-lab — this PR is ready for re-review at Summary of Fixes Since Review 5811304493
Whenever you have a chance, could you please take a quick look at |
wojtas000
left a comment
There was a problem hiding this comment.
One thing has to change before this merges: a user prompt that was offloaded to GCS counts as ready for evaluation, even though the view only has a 200-character preview of it.
Must change before merge:
- Offloaded user prompts are marked eval-ready. The user-message text selector accepts
GCS_REFERENCEparts (views.go lines 600 to 602). When a prompt is larger thanMaxInlineTextSize(32 KiB by default) and GCS offload is on, that part's text is only the first 200 runes plus... [OFFLOADED](gcs_offloader.go lines 840 to 841), andis_truncatedstays false. The turn then getseval_ready = trueandhas_truncated_content = false, so a consumer that selectseval_ready AND NOT has_truncated_contenthands the evaluator a prompt cut off after 200 runes. I reproduced it through the plugin callbacks with a fake offloader and a prompt whose question sits at the end. Both views returned the 215-character preview witheval_ready=trueandhas_truncated_content=false, and the question was gone. adk-python accepts onlyINLINEparts here (eval_view_ctes_v1.sql at v2.14.1) and gives the reason: offloaded input "leaves the judge without a prompt" (v2.13.0). The property to keep is that a turn is eval-ready only when its trace holds the whole user message. I tried restricting this selector toINLINE: my reproduction passes, and the only tests that fail are the ones asserting the preview behavior (views_test.go lines 6865 to 6878) and the SQL hash pins. I'd hold the merge on it, because it produces wrong evaluation input with no signal that anything is missing, in a configuration the package documents. - The table-name change has no test that pins it.
isValidTableNamenow accepts non-decimal numbers (views.go line 1579), but no accept case uses one, so switchingIsNumberback toIsDigitkeeps the suite green. Let's add accept cases fortbl²andtblⅫ, the two examples in the description.
Two questions, both optional:
- The testing plan lists
go vet,golangci-lintandapidiffas verifying GoogleSQL compilation, but none of them parse the SQL, and the semantic tests run a SQLite translation of it. Has the DDL been run against BigQuery? If it has, could you say so in the description? Nothing in CI checks it. - adk-python has changed this SQL since v2.13.0. v2.14 falls back to the
LLM_REQUESTsystem prompt for agents with an instruction provider, and main (not yet released) addsTOOL_ERROR, leaves the HITL tools out of the tool counts, and stops truncated turns from counting as eval-ready. Matching v2.13.0 is what the description promises, so a follow-up issue to track the newer changes is enough.
The inline notes are optional.
When Cloud Storage offloading is configured, a user text part longer than MaxInlineTextSize is uploaded, and its content_parts entry keeps only the first 200 runes followed by "... [OFFLOADED]", without setting is_truncated. The eval views read that preview as the user message, so the turn came out eval_ready with has_truncated_content false while the question past the preview was gone. The user message text selector now reads only INLINE parts, as adk-python does, and a message that has any text part stored by GCS reference yields no user text at all, so a prompt whose other parts stayed inline is not rebuilt from those parts alone. Offloaded media placeholders are still skipped without holding back the inline text beside them. Also: - Document on CreateEvalViews the content keys that a custom ContentFormatter must keep, and that with a ContentFormatter the views read AGENT_RESPONSE text from $.response alone. - Drop the UTF-8 validity check in isValidTableName: ranging over the string decodes invalid bytes to U+FFFD, which the loop already rejects. - Pin the non-decimal Unicode numbers that isValidTableName accepts with tbl² and tblⅫ test cases. - Copy content parts with maps.Copy in a test helper, as the modernize linter now enabled on main asks.
|
Thanks for the careful review, @wojtas000. I merged 1. Offloaded user prompts no longer count as eval-ready. The user message text selector now reads only 2. Your questions:
|
caohy1988
left a comment
There was a problem hiding this comment.
The new views are in good shape overall. Identifier validation, the denylist-aware projections, the event-filter checks and the composite session scoping all hold up, and the description is unusually upfront about what changed. There's one thing I think needs fixing before this lands, plus a few smaller gaps.
A pipeline that's still waiting on a tool result is already marked eval_ready. The completeness check (views.go:978) only asks for any AGENT_RESPONSE plus any INVOCATION_COMPLETED in the invocation. The pause predicate at views.go:964 needs zero response rows. In a sequential agent, the first sub-agent can answer with text and the next one can then pause on a long-running tool. The runner ends that call normally and INVOCATION_COMPLETED is written, so both views return eval_ready=true with only the first sub-agent's answer, even though the work is still waiting on the external result. I reproduced this with a real runner (two sequential agents, the second calling a long-running tool with no result) and the existing SQLite translation. Resuming afterwards does flip it correctly. Matching outstanding pause/HITL requests to their resumed completions by call identity, instead of treating any response as completion, would fix it. Python has the same expression, but here it's new code, and anyone selecting "ready" trajectories would be scoring unfinished work.
Smaller things:
- Resumed invocations under-report latency. A matching function response reuses the original invocation ID (runner/run_node.go:431), but each run gets its own INVOCATION_COMPLETED with its own duration. Taking the max (views.go:960) drops the shorter runs: two runs of 54 ms and 23 ms show up as 54 ms in both views, and that flows into
total_latency_ms. Summing distinct completed runs after dedup would fix it. - Replies that are literally
[BINARY DATA],[MEDIA OFFLOADED]or[UPLOAD FAILED]disappear (views.go:704), and the turn never becomes ready, because the non-empty parts array blocks the fallback tocontent.response. It's an edge case, but part provenance would distinguish a real placeholder from text. - Offloaded text on shared tables. The no-user-text rule for offloaded user parts (views.go:593-604) only fires when
part_attributesis NULL or'{}'. That's true for today's Go and Python writers, but any writer that adds attributes to text parts would let partial user text through. On the response side, GCS_REFERENCE previews are aggregated as the full reply (views.go:693-707). Go never offloads AGENT_RESPONSE, but Python does, so on a shared table a 200-character "... [OFFLOADED]" preview would be scored as the complete answer. Mirroring the user-text rule there, or at least documenting it, seems worth doing. - SyncViews. The deferred group validation error built at views.go:1787-1810 is only joined at the very end of
syncViewsWithDefs. A canceled context, a closed plugin or a gate failure return without it. Separately, the post-sync closed check (views.go:1868-1871) now turns a fully successful sync into a "plugin closed" error. That second change is disclosed, but I don't think it's needed. I'd keep the old rule, where closed only overrides a failure. - The startup log still says "skipping view creation" when only one group is skipped, and the retry hint suggests SyncEvalViews even when it's the per-event views that need SyncViews.
Every item in this review is fixed on the current head.
wojtas000
left a comment
There was a problem hiding this comment.
Approving. The single-message offload case and the IsNumber widening both have tests that fail without the fix.
Two optional notes, neither blocks:
- A turn resumed after a pause can still come out eval-ready with its offloaded prompt missing, when the resume message carries text next to the function response. The resume reuses the paused invocation ID, so
has_user_messagesees the resume's text. It needs offloading on and a prompt over the inline limit, so a follow-up issue is fine. Optionally, narrow the newCreateEvalViewsdoc sentence, which says this can't happen. - Optionally, the
ContentFormatterdoc could say that for USER_MESSAGE_RECEIVED and LLM_RESPONSE the formatter gets the typed value, which has notext_summaryorusagekeys.
Linked issue
Summary
Adds opt-in pre-built BigQuery evaluation views (
<ViewPrefix>_eval_sessionand<ViewPrefix>_eval_turn, defaulting tov_eval_sessionandv_eval_turn) toplugin/agentanalytics, reconstructing multi-turn session and single-turnAgentDataevaluation trajectories,agent_configsmaps, token usage rollups, error flags, and consecutive identical tool-call loop detection directly from the BigQueryagent_eventstable.Public API & Configuration
Config.CreateEvalViews bool(opt-in, defaultfalse): when enabled on an active plugin with a non-nilbqClient, creates/replaces<ViewPrefix>_eval_sessionand<ViewPrefix>_eval_turnasynchronously during startup (independently ofDisableCreateViews, so standalone evaluation-view startup withCreateEvalViews: true, DisableCreateViews: truecreates only the 2 evaluation views) and includes them inSyncViews(ctx)(with per-group validation isolation so valid per-event or evaluation views still sync and return joined errors if the other group fails validation). Its doc lists the content keys that a customContentFormattermust keep for the views.(Config).EvalViewDefinitions() ([]ViewDefinition, error): deterministically renders the twoCREATE OR REPLACE VIEWstatements without requiring live clients, validating project/dataset/table/prefix identifiers, view-name length (<= 1024bytes), and case-insensitive collisions with the events table.(*BigQueryAgentAnalyticsPlugin).SyncEvalViews(ctx context.Context) error: synchronously creates or replaces only the two evaluation views (even whenCreateEvalViewsisfalse), validating configuration and view definitions before preempting any in-flight startup pass and coordinating withClose()andSyncViews(ctx)via the view gate.Denylist & Event-Filter Validation
PayloadColumnDenylistprojection: projects typedNULL/ empty-array stand-ins inraw_eventswhen optional payload columnscontent_parts,attributes, orlatency_msare listed inPayloadColumnDenylist. RejectsCreateEvalViews,EvalViewDefinitions, andSyncEvalViewswhencontentis denied (required forAgentDatatrace reconstruction); unsupported column names remain rejected byPayloadColumnDenylistvalidation.EventDenylist/EventAllowlistvalidation: rejectsCreateEvalViewsandSyncEvalViewswhen any of the 15 required trajectory/HITL/completion event types would be dropped by runtime emitters — accounting for"EVENT"inEventDenylistsuppressing the 9 session-level events plus resumed-toolTOOL_COMPLETED, and"EVENT"inEventAllowlistcovering the 8 pure session/HITL/pause events unconditionally while coveringAGENT_RESPONSEonly whenFinalResponseToolNamesis empty (since final-response tools emitAGENT_RESPONSEthroughlogEvent).Semantic Hardenings Beyond
adk-python v2.13.0While preserving the
v_eval_session(21 columns) andv_eval_turn(22 columns) output schemas andAgentDataJSON contract fromadk-python v2.13.0, the Go view SQL includes three semantic hardenings:(app_name, user_id, session_id)session scoping & NULL-safe joins: partitions and groups turn rollups, turn indices (turn_index), HITL pause/resume windows (LAG(is_paused)/LEAD(has_function_response)), session rollups, andagent_configsmaps by(session_id, user_id, app_name)(fromattributes.adk.app_name, with invocation-level backfill when a fallback row omitsuser_idoradk.app_name), usingIS NOT DISTINCT FROMjoin predicates soNULLuser_idor"attributes"-deniedNULLapp_namerows preservetrace.agents. When"attributes"is inPayloadColumnDenylist, session scoping falls back to(user_id, session_id).event_id: deduplicates retried rows sharing a non-emptyevent_idindeduped_eventsbefore windowing, token/tool/error aggregation, and trace construction, preserving all rows withNULLor emptyevent_idand preferring non-[FORMATTER_FAILED], non-[UPLOAD FAILED],GCS_REFERENCE, and non-truncated copies.content_parts-firstUSER_MESSAGE_RECEIVED&AGENT_RESPONSEtext reconstruction (excluding[FORMATTER_FAILED]scalar sentinels): whenevercontent_partsis non-empty, reconstructsUSER_MESSAGE_RECEIVEDmessage_textandAGENT_RESPONSEresponse_textfrom ordered non-attributedtext/plainparts (excluding'','[BINARY DATA]','[MEDIA OFFLOADED]', and'[UPLOAD FAILED]', joined with\nbypart_index), avoiding false delimiter rejection or splitting when literal response text contains' | call: ',' | resp: ',' | other', or"' | text: '". User text comes only fromINLINEparts, as in adk-python: a text part offloaded to Cloud Storage (GCS_REFERENCE) holds only a 200-rune preview, and a message with such a part has no user text at all (stricter than adk-python, which keeps the message's other inline parts), so its turn is noteval_ready. Response text also readsGCS_REFERENCEtext parts, which only another writer sharing the table produces: this plugin writesAGENT_RESPONSEparts inline, cut atMaxContentLenwithis_truncatedset. Whencontent_partsis empty (FinalResponseToolNames,LogMultiModalContent: false, customContentFormatter, orcontent_partsinPayloadColumnDenylist), the views fall back tocontent.text_summary/content.responseand to non-sentinel scalar output, excluding root scalar"[FORMATTER_FAILED]"on bothUSER_MESSAGE_RECEIVEDandAGENT_STARTING, so failed user-message formatters evaluateeval_ready = falseand failedAGENT_STARTINGformatters fall through tostatic_instruction.Behavior change
Config.CreateEvalViews,Config.EvalViewDefinitions,(*BigQueryAgentAnalyticsPlugin).SyncEvalViews).isValidTableName) now accepts non-ASCII space separators (Zs), combining marks (M*), and non-decimal Unicode numbers (Nl/No, such astbl²ortblⅫ), which also allows standard per-event view creation to proceed for such table names whenCreateEvalViewsisfalse.SyncViewschanges for every caller, including withCreateEvalViews=false: whenCloselands after every view DDL has succeeded, it now returns theagentanalytics: plugin is closederror where it returnednilbefore, and a view-definition validation error now comes back wrapped byerrors.Joineven when it is the only error (the message is unchanged, anderrors.Isanderrors.Asstill match it).Testing Plan
go build,go vet,gofmt,go mod tidy -diff,golangci-lintv2.15.0, and.github/scripts/apidiff.sh(no incompatible changes) on a cleangit archivecheckout in ago workworkspace like CI's.plugin/agentanalyticstest suite, once without-raceand once with-race -shuffle=on.TestEvalViews_SemanticExecutionruns the generated SQL through a SQLite translation of it (the test needspython3and SQLite 3.25 or later, and skips otherwise) over rows written through the plugin's own callbacks, and the length and SHA-256 pins catch any change to the generated SQL text.plugin/agentanalytics/views_test.go):TestEvalViews_SemanticExecution/cross_user_and_cross_app_session_isolation_and_pause_windowsandnull_app_name_and_null_user_id_join_preserves_agent_configsfail if(session_id, user_id, app_name)scoping orIS NOT DISTINCT FROMjoins are reverted.TestEvalViews_SemanticExecution/deduplicates_retried_event_id_and_preserves_empty_event_id_and_prefers_clean_copyfails ifdeduped_eventsretry deduplication or clean-copy tie-breaking is removed.TestEvalViews_SemanticExecution/agent_response_reconstructs_from_content_parts_and_preserves_fallbacksfails ifcontent_parts-firstAGENT_RESPONSEtext reconstruction is removed.TestEvalViews_SemanticExecution/user_message_needs_whole_inline_text_and_skips_media_offloadedfails if the user text selector reads offloadedGCS_REFERENCEpreviews again, if a message keeps its inline parts when another text part was offloaded, or if an offloaded media placeholder holds back the inline text beside it. Its end-to-end case goes through the plugin callbacks with a fake offloader and the defaultMaxInlineTextSize: a prompt longer than 32 KiB whose question sits past the 200-rune preview is noteval_readyin either view, on its own or as the second part of a two-part message, while the same prompt stored inline is ready with its whole text.TestViewAndEvalViewDefinitions_TableNameUnicodeAndControlChars/accept_Unicode_No_superscript_twoandaccept_Unicode_Nl_Roman_numeral_twelvefail ifisValidTableNameaccepts only decimal digits (unicode.IsDigit) instead of any Unicode number.TestCreateEvalViews_StartupAndSyncLifecycle/SyncViews_isolates_per-event_and_eval_failures_so_valid_view_groups_still_sync_and_return_joined_errorsfails ifSyncViewsper-group error isolation is removed.