Skip to content

feat(agentanalytics): add ToolResultClassifier hook and schema lifecycle callbacks - #2180

Merged
wojtas000 merged 3 commits into
google:mainfrom
haiyuan-eng-google:feat/bqaa-2014-v1-classifier-and-schema-callbacks
Nov 19, 2026
Merged

wojtas000 merged 3 commits into
google:mainfrom
haiyuan-eng-google:feat/bqaa-2014-v1-classifier-and-schema-callbacks

Conversation

@haiyuan-eng-google

@haiyuan-eng-google haiyuan-eng-google commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Please ensure you have read the contribution guide before creating a pull request.

Linked issue

1. Link the issue this change is for. Required for everything except small
documentation and typo fixes. If no issue exists yet, please open one first.

2. Describe the change:

If applicable, please follow the issue templates to provide as much detail as
possible.

Problem:
A clear and concise description of what the problem is.

Relative to main, plugin/agentanalytics lacked two configuration hooks present in adk-python's BigQuery Agent Analytics plugin:

  1. Callers had no callback to classify domain-level errors encoded inside successful (err == nil) tool results (beyond the built-in MCP top-level boolean "isError" / "is_error" rule), forcing domain failures to be logged as TOOL_COMPLETED (and emitting AGENT_RESPONSE rows for tools in FinalResponseToolNames).
  2. Callers had no lifecycle callbacks (OnSchemaReady / OnSchemaError) to observe when BigQuery destination table setup succeeds or fails and when startup view creation completes.

In addition, edge cases in ModeTask finish_task span attribution (reused tool-call IDs across overlapping, held, or concurrent fan-out activations; multi-part FunctionResponse events under ADK's first-response isFinishTaskSuccessFR rule; overruled sentinel responses behind empty-ID failures; delayed failure retirement; and parallel-tool merged event timestamps), evicted-and-restored invocation reconciliation at run end, and BigQuery schema/view verification (VIEW / MATERIALIZED_VIEW / EXTERNAL / SNAPSHOT destination objects, 409 conflicts on table.Create when DisableSchemaUpgrade is true, and 409 AlreadyExists DDL conflicts before a view is ready) needed hardening.

Solution:
A clear and concise description of what you want to happen and why you choose
this solution.

  • Tool result classification (Config.ToolResultClassifier, ToolResultVerdict, ToolResultDecision):
    • Adds ToolResultClassifier func(ctx agent.Context, t tool.Tool, args, result map[string]any) ToolResultVerdict with decisions ToolResultAbstain (zero value, deferring to the built-in "isError" / "is_error" check), ToolResultOK, and ToolResultError.
    • Passes ctx, t, args, and result directly from AfterToolCallback without cloning (callers must not mutate args or result, as documented on ToolResultClassifier in config.go), redacts ToolResultVerdict.ErrorMessage unless DisableSensitiveKeyRedaction is true, and recovers panics or unknown decision values in runToolResultClassifier by abstaining and logging only the pre-formatted panic type string (%s via fmt.Sprintf("%T", r), without passing the raw panic value as a Logger.Printf argument) or numeric decision (%d) via safeLogf (which silently swallows any Logger panic without logging tool names or payloads).
  • Schema lifecycle callbacks & destination/view validation (Config.OnSchemaReady, Config.OnSchemaError):
    • Invokes OnSchemaError synchronously at most once when destination table metadata lookup, creation, type validation, or schema upgrade fails, pre-formatting any callback panic type via fmt.Sprintf("%T", r) before passing to safeLogf.
    • Invokes OnSchemaReady at most once after table setup succeeds: synchronously when both DisableCreateViews is true and CreateEvalViews is false (without validating view definitions at startup), or after the background startup view pass creates every enabled view group (ViewDefinitions when !DisableCreateViews, EvalViewDefinitions when CreateEvalViews) without a validation failure in either enabled group. A failed startup view logs a warning (through a non-default Config.Logger) and returns without invoking either OnSchemaReady or OnSchemaError (only table setup failures invoke OnSchemaError; SyncViews and SyncEvalViews return view errors directly). Releases both callback closures once startup settles so captured state is not retained for the plugin's lifetime.
    • Validates destination table metadata via validateDestinationTableType in ensureTableAndSchema and maybeUpgradeSchema (including on 412 PreconditionFailed schema-upgrade retries and after HTTP 409 / AlreadyExists conflicts on table.Create even when DisableSchemaUpgrade is true), failing fast and routing to OnSchemaError on disappearing (404) or non-TABLE objects (VIEW, MATERIALIZED_VIEW, EXTERNAL, SNAPSHOT).
    • Verifies HTTP 409 / AlreadyExists view DDL conflicts in resolveDDLConflict by polling table.Metadata with exponential backoff within the caller's ctx deadline (falling back to viewDDLTimeout when ctx has no deadline), retrying transient 404, 429, 5xx, and stale ViewQuery states, returning immediately on non-VIEW objects or non-retryable 400/401/403 errors, preserving context.DeadlineExceeded alongside metadata errors in unverifiedViewConflictError.Unwrap(), formatting only structured status codes via safeErrorStatus, and passing sanitized err.Error() strings (%s) to logf in syncAnalyticsViewsWithRetryHint while keeping %w on the returned error.
  • Task-mode finish_task attribution & trace reconciliation (classifyTaskResponses, resolveFinishedTaskLocked, retireFailedTaskAttemptsAtLocked, endInvocationTarget):
    • Mirrors ADK's first-response isFinishTaskSuccessFR rule in classifyTaskResponses, collecting all non-empty endingCallIDs, tracking leadingActionCallID and mergedResponse, and recording overruledEndingCallIDs behind a failed first response.
    • Records weak references to each finish_task call's EventActions maps (StateDelta/ArtifactDelta) in noteTaskStart and noteTaskAttempt so resolveFinishedTaskLocked and retireFailedTaskAttemptsAtLocked match the originating activation directly on single-part or leading-part FunctionResponse events (even under frozen/equal clocks) without retaining user state payloads.
    • Evaluates all non-empty endingCallIDs in resolveFinishedTaskLocked before consuming any attempt (consumeWinner), filters by timestamp plausibility (skipping per-attempt recordedAt bounds on merged multi-tool responses so parallel tool timestamps do not exclude sibling attempts), applies an O(N log N) suffix-maximum causal supersession pass, requires a single activation to cover all surviving observed call IDs in a merged response (returning taskMatchAmbiguous without consuming if disjoint activations conflict), and breaks same-tier single-call ties by earliest-recorded attempt (recordedAt, then seq, then stack order) so concurrent call_0 fan-outs close every run cleanly.
    • Passes ev.Timestamp and leading dispatch maps to retireFailedTaskAttemptsForEvent, falls back in unobservedTaskLocked to ctx's plausible activation or the newest plausible matching activation for both empty and non-empty unobserved call IDs, reads platform.Now(ctx) in pushAgentSpan before acquiring inv.mu and only when children.taskMode is true, and reconciles evicted-and-restored invocations sharing rootSpanID under tm.mu in endInvocationTarget and completeRunEndTarget so restored traces close and unlink from tm.invocations and tm.evicted.

Behavior change

What behaves differently for someone already on the current release?

Write "nothing" if that is the answer. Bug fixes count: a fix that alters an
observable result is still a behavior change.

Relative to main:

  • Config.ToolResultClassifier (ToolResultVerdict, ToolResultDecision): New opt-in hook; when nil (default), tool classification behaves as before. When set, runToolResultClassifier recovers classifier panics or out-of-range decisions, logs only the pre-formatted panic type string (%s) or numeric decision (%d) via safeLogf (which silently ignores panics from Config.Logger itself and omits tool names and payloads), and falls back to the built-in "isError" / "is_error" rule.
  • Config.OnSchemaReady & Config.OnSchemaError: New opt-in startup callbacks invoked at most once when enabled and bqClient != nil. Only destination table setup failures invoke OnSchemaError; a failed startup view logs a warning (through a non-default Config.Logger) and returns without invoking either OnSchemaReady or OnSchemaError (SyncViews and SyncEvalViews return view errors directly). When both DisableCreateViews is true and CreateEvalViews is false, view definitions are not validated at startup and OnSchemaReady fires synchronously once table setup succeeds; when either view group is enabled, OnSchemaReady fires only after every enabled view group validates and completes startup creation. ViewPrefix remains validated unconditionally during construction even when DisableCreateViews is true.
  • ensureTableAndSchema & validateDestinationTableType: Pointing Config.TableName at an existing non-TABLE BigQuery object (VIEW, MATERIALIZED_VIEW, EXTERNAL, or SNAPSHOT), encountering a non-TABLE destination on schema-upgrade retry, or hitting an HTTP 409 / AlreadyExists conflict on table.Create whose follow-up table.Metadata read fails (such as 404) or returns a non-TABLE object now fails plugin construction immediately (and triggers OnSchemaError if configured) even when DisableSchemaUpgrade is true, rather than succeeding at startup and failing later on BigQuery Storage Write AppendRows.
  • resolveDDLConflict & unverifiedViewConflictError: An HTTP 409 / AlreadyExists response during CREATE OR REPLACE VIEW is now treated as success only after table.Metadata confirms a VIEW with the expected SELECT body within the caller's ctx deadline (retrying 404, 429, 5xx, and stale view queries, and failing fast on non-VIEW objects or 400/401/403). Unverified conflicts return unverifiedViewConflictError, whose Error() and startup warning (err.Error() via %s) expose only structured HTTP/gRPC status codes via safeErrorStatus without echoing raw server response bodies or passing raw error structs to Logger.Printf, while Unwrap() preserves the underlying conflict, metadata error, and context.DeadlineExceeded.
  • First-response classifyTaskResponses, finish_task span attribution, and trace-end reconciliation:
    • Multi-part finish_task FunctionResponse events follow ADK's first-response rule (classifyTaskResponses): a non-ending first finish_task part keeps the task open (retiring failedCalls and overruledEndingCallIDs) rather than ending the span on a trailing sentinel part.
    • Observed finish_task completions now resolve across all endingCallIDs before consuming any attempt, using leading-part EventActions map identity, event-timestamp plausibility, O(N log N) causal supersession, tier precedence, and earliest-recorded tie-breaking. Unlike main, if a single merged event carries surviving observed finish_task call IDs split across disjoint activations (without dispatch-map disproof), resolveFinishedTaskLocked returns ambiguous and leaves spans open rather than guessing across conflicting call IDs.
    • Failed finish_task responses (retireFailedTaskAttemptsAtLocked) preserve sibling activations' recorded terminal outcomes when retiring failedCalls, exclude activations and single-call attempts recorded after ev.Timestamp, and retire overruledEndingCallIDs behind empty-ID first failures.
    • pushAgentSpan skips calling custom platform.TimeProvider on non-task agents (!children.taskMode), and endInvocationTarget / completeRunEndTarget close and unlink evicted-and-restored invocations sharing the same rootSpanID.

Testing Plan

Please describe the tests that you ran to verify your changes. This is required
for all PRs that are not small documentation or typo fixes.

Unit Tests:

  • All unit tests pass locally.

With your source change reverted and your tests kept, which test fails?

Name it. If nothing fails, the tests do not yet cover the change. This is the
cheapest moment to find that out.

Please include a summary of passed go test results.

  • Reverting ToolResultClassifier / runToolResultClassifier: TestToolResultDecision_String, TestPlugin_ToolResultClassifier_Verdicts, TestPlugin_ToolResultClassifier_ErrorMessageRedaction, TestPlugin_ToolResultClassifier_EventFilters, TestPlugin_ToolResultClassifier_FailuresAreSkipped, TestPlugin_ToolResultClassifier_Precedence, TestPlugin_ToolResultClassifier_Runner, and TestDocParity_ToolResultClassifierBuiltInRules.
  • Reverting OnSchemaReady / OnSchemaError, ensureTableAndSchema, validateDestinationTableType, or resolveDDLConflict: TestNotifySchemaCallbacks, TestPlugin_OnSchemaError, TestPlugin_OnSchemaReady_TablePass, TestPlugin_OnSchemaReady_ViewPass, TestPlugin_SchemaCallbacks_ConcurrentPlugins, TestPlugin_SchemaCallbacks_ClosuresReleased, TestDocParity_SchemaCallbacksAtMostOnce, TestEnsureTableAndSchema_ConflictOnCreateRecovery, TestValidateDestinationTableType, TestMaybeUpgradeSchema_RetryRevalidatesDestinationTableType, TestIsRetryableConflictVerifyError, and TestResolveDDLConflict_EdgeCases.
  • Reverting classifyTaskResponses, resolveFinishedTaskLocked, retireFailedTaskAttemptsAtLocked, noteTaskStart, pushAgentSpan task-mode clock gating, or endInvocationTarget trace reconciliation: TestClassifyTaskResponses_MultiPartOrderings, TestPlugin_FinishTask_OverlappingErrorDoesNotStealCompletion, TestPlugin_FinishTask_PromotedErrorClosesOriginatingSpan, TestPlugin_FinishTask_MixedResponseEventEndsOwnActivation, TestPlugin_FinishTask_FailedFirstThenCompletedInSameEventStaysOpen, TestPlugin_FinishTask_FailedEmptyIDThenCompletedStaysOpenAndRetiresOverruledCall, TestPlugin_FinishTask_ReusedCallID_AttributionOrderings, TestPlugin_FinishTask_PromotedRun2DeliveredBeforeHeldRun1Completion, TestPlugin_FinishTask_TrailingObservedEndingCallIDResolvesActivation, TestPlugin_FinishTask_ConcurrentCall0ReuseFanOut, TestPlugin_FinishTask_MergedReusedLeadingShortCircuitedAndUniqueTrailingCallID, TestPlugin_FinishTask_CoordinatorBufferedFailureDoesNotRetireNewerWorkerAttempt, TestPlugin_FinishTask_MergedParallelToolTimestampPredatingAfterToolRecordedAt, TestPlugin_FinishTask_NoteTaskStartAndOverruledEndingGuards, TestTraceManager_FinishedTaskLocked, TestRetireFailedTaskAttemptsLocked_PreservesSiblingRecordedSuccess, TestEndInvocation_ReconcilesEvictedAndRestoredActiveTrace, TestPushAgentSpan_PlatformClockOutsideLockAndTaskModeOnly, and TestResolveFinishedTaskLocked_512OverlappingActivationsEquivalence.

Verification summary at 621b5462 (rebased directly on origin/main 6b4c6d55) for plugin/agentanalytics:

  • gofmt -l plugin/agentanalytics, git diff --check, and GOWORK=off go -C plugin/agentanalytics mod tidy -diff: clean
  • go -C plugin/agentanalytics vet ./... and golangci-lint run --max-same-issues=0 --max-issues-per-linter=0 ./... (in plugin/agentanalytics): PASS (0 issues)
  • Targeted -race -mod=readonly -count=1 across classifier, schema-callback, resolveDDLConflict, ensureTableAndSchema, finish_task, trace reconciliation, eval-view, doc.go, and afterRun suites: PASS (23.939s)
  • Full go -C plugin/agentanalytics test -mod=readonly -count=1 ./...: PASS (145.159s)

Manual End-to-End (E2E) Tests:

Please provide instructions on how to manually test your changes, including any
necessary setup or configuration. Please provide logs or screenshots to help
reviewers better understand the fix.

Not manually run against a live BigQuery dataset in this environment; covered by unit tests and mock HTTP/gRPC BigQuery and BigQuery Storage Write transports in plugin/agentanalytics. To verify manually against live BigQuery, configure BigQueryAgentAnalyticsPlugin with ProjectID, DatasetID, TableName, ToolResultClassifier, OnSchemaReady, and OnSchemaError, run an llmagent tool call returning a domain error map, and inspect the resulting TOOL_ERROR row and v_tool_error view in BigQuery.

Checklist

  • I have read the CONTRIBUTING.md document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • I have manually tested my changes end-to-end.
  • Any dependent changes have been merged and published in downstream modules.

Additional context

Add any other context or screenshots about the feature request here.

Aligns plugin/agentanalytics with adk-python's tool_result_classifier and schema readiness/error callback surface while documenting Go-specific contract details in config.go and doc.go.

caohy1988

This comment was marked as outdated.

caohy1988

This comment was marked as outdated.

@haiyuan-eng-google
haiyuan-eng-google force-pushed the feat/bqaa-2014-v1-classifier-and-schema-callbacks branch from 3c304c1 to d91de5a Compare November 7, 2026 00:54
caohy1988

This comment was marked as outdated.

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Addressed in 8b1d2ad:

  1. Classified finish_task activation attribution (plugin/agentanalytics/bigquery_agent_analytics_plugin.go, config.go):
    • Extracted isTaskCompletedResult (result["result"] == "Task completed.", shared with hasTaskCompletedResponse) and recorded noteTaskFinished in afterTool before returning on ToolResultError, while leaving non-completion error envelopes unmarked.
    • Added TestPlugin_ToolResultClassifier_Runner/ERROR_verdict_on_runtime-successful_finish_task_preserves_activation_attribution covering buffered task runs where the first runtime-completed finish_task call is classified as ToolResultError, alongside the existing rewritten error-envelope subtest.
  2. PR description wording: Updated the Behavior change and Summary paragraphs to include confirmation request/rejection outcome maps (excluding unrecovered ordinary tool errors and errors already recorded by OnToolErrorCallback) and accurate finish_task span-attribution semantics.

caohy1988

This comment was marked as outdated.

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Updated the Behavior change section in the PR description per Review 5814165169 to disclose that afterTool now gates noteTaskFinished on isTaskCompletedResult(result) even when ToolResultClassifier is nil, correcting task-completion span attribution when an earlier callback rewrites a finish_task result into a non-completion envelope while keeping all other behavior unchanged when the three hooks are nil.

@caohy1988 caohy1988 left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Earlier review of a previous revision; the latest notes are in #2180 (review).

@wojtas000 wojtas000 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

One doc change is needed before this merges: the Config doc says the three hooks reach the same verdicts as adk-python on the same inputs, and at this head they don't.

Must change before merge:

  • config.go#L287-L289: adk-python records a ReflectAndRetry answer as a tool error before its classifier runs, and when the classifier abstains or fails it still records a result with a top-level isError or is_error of true as a tool error (_callback_helpers.py). Here a retry-and-reflect answer goes to the classifier, so an OK or abstain verdict records TOOL_COMPLETED, and an abstain on {"isError": true} records TOOL_COMPLETED too. I know #2177 and #2178 add those rules. Until they land, let's name these differences in the sentence or drop the "same verdicts" claim, so someone porting a Python classifier doesn't expect retry answers to be recorded as errors by default.

Not blocking, but I'd like your view: OnSchemaReady runs on the view goroutine before it closes done (views.go#L751-L754), and Close waits on done with no bound (views.go#L799-L801) before it flushes the queue (bigquery_agent_analytics_plugin.go#L508-L511). The doc tells callers not to block, so this is the documented behavior. Still, a callback that blocks, for example an unbuffered send whose reader already gave up, keeps Close from returning and the queued rows are never flushed. I ran a test that holds the callback on a channel, and Close stayed blocked until I released it. adk-python's close() doesn't wait for the readiness pass, so the Go port could avoid tying Close to user code too.

Comment thread plugin/agentanalytics/config.go Resolved
Comment thread plugin/agentanalytics/config.go Resolved
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks for the careful read. The changes below are in d8d2bd4e, on top of the reviewed head. The branch head is now e4cb35eb: it also merges main (a merge, no rebase), and a small test-only commit rewrites four counted loops as range-over-int loops for the modernize linter that main now enables and drops an unread channel from a test helper.

Must change: the "same verdicts" sentence in the Config doc

You're right. I checked it against _callback_helpers.py at the commit you linked: adk-python runs three checks in turn (retry answer, classifier, top-level isError/is_error), and this head has only the middle one. The Config doc no longer says the hooks reach the same verdicts. It now names both differences:

  • adk-python records a ReflectAndRetryToolPlugin answer as a tool error before its classifier runs. Here, when a plugin/retryandreflect plugin that is registered before this one answers a tool error, the answer reaches ToolResultClassifier like any other result.
  • adk-python records a result whose top-level isError or is_error is true as a tool error unless its classifier returns OK. Here, both kinds of result are recorded as TOOL_COMPLETED when the classifier is nil, fails, or returns ToolResultOK or ToolResultAbstain.

It also says what a port has to do: return ToolResultError for those results itself. The ToolResultClassifier type doc points at that paragraph. The PR description had the same problem ("matching adk-python v2.13.0's tool_result_classifier semantics"), so I rewrote that line and added the two differences there too.

The paragraph is now backed by tests, so it can't drift quietly: a real retryandreflect plugin registered first (nil, abstaining, OK and ERROR classifier), and a {"isError": true} result under a nil, abstaining and failing classifier (plus {"is_error": true} under an abstaining one). When #2177 and #2178 add the two rules, those tests fail and the paragraph has to change with them.

OnSchemaReady and Close

I reproduced what you saw: with the callback held on a channel, Close stays blocked until the callback is released. One refinement on the consequence: the batch processor keeps running while Close waits, so with the default BatchFlushIntv a queued row was still written by the periodic flush about a second after Close was called. What doesn't run is the drain in Close. With a one-hour flush interval the row sat in the queue until I released the callback, and a process that gives up on a stuck Close loses whatever was queued since the last flush.

Why Close waits today: it waits for the view goroutine, so that no DDL request is in flight when it closes the BigQuery client and a pass that Close ended can't report readiness afterwards. Neither of those needs Close to wait for user code. That part is a side effect of the pass calling OnSchemaReady before it signals that it is done.

So my view is that you're right: Close shouldn't depend on user code. I tried two ways to get there, both on d8d2bd4e:

  1. Drain before waiting. Close cancels the pass, drains the queue, then waits for the pass. A stuck callback still keeps Close from returning, but it can no longer hold rows back: the row was written a few milliseconds after Close was called, with the callback still held. The documented contract doesn't change.
  2. Don't wait for the callback. The pass decides readiness under the lock that Close takes, signals done, and only then calls OnSchemaReady. Close returned a few milliseconds after it was called with the callback still held, and the row was written. Close and SyncViews no longer wait on user code, the callback may call either of them, and a pass that Close or SyncViews ended still never calls it. The cost is that a callback the pass had already decided to make can run during or just after Close, the same way the stop function of context.AfterFunc doesn't wait for f. This is the closer match to adk-python's close().

The package's tests pass unchanged with either one, which also tells me nothing in the suite depends on Close waiting for a running callback, so whichever we pick needs its own tests. (A timeout on the wait would be a third way, but it adds a knob and the goroutine still leaks.)

I prefer 2. It changes a contract that this PR documents ("Close and SyncViews wait for the callback to return"), so I left it out of this push to keep the push to what you asked for. For now the OnSchemaReady doc states the consequence outright (a callback that never returns keeps Close from returning and from draining the queued rows) instead of only saying "non-blocking". I can add 2 to this PR or send it as a follow-up right after this one, whichever you prefer.

Inline threads

  1. Classification ahead of the event filters: added TestPlugin_ToolResultClassifier_EventFilters. Moving classification behind the filters fails it.
  2. CaptureFullMessageContent: the ErrorMessage doc now says the message isn't truncated when it is set, with a test next to the truncation one.
  3. The finish_task subtest: renamed to say the result isn't a completion envelope, and it now has a nil-classifier case. Details are in each thread.

Verification at e4cb35eb: the full package passes with -race -parallel=1 -shuffle=on, and with coverage (93.6%). go vet and gofmt are clean, golangci-lint v2.15.0 reports 0 issues in both modules, go mod tidy -diff is clean, and apidiff.sh origin/main passes.

@caohy1988 caohy1988 left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Earlier review of a previous revision; the latest notes are in #2180 (review).

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks for catching these! Updated on the branch:

  • HTTP 409 view conflict verification (views.go): RunViewDDL now routes 409 / AlreadyExists errors through resolveDDLConflict, which reads back the target view metadata (table.Metadata) and verifies both md.Type == bq.ViewTable and that md.ViewQuery matches the expected SELECT body, returning *unverifiedViewConflictError when the view is missing, not a view, or has an empty/stale query so syncAnalyticsViews does not trigger OnSchemaReady prematurely.
  • finish_task span attribution across AfterToolCallback errors, confirmation outcomes, and rewrites (trace_manager.go, bigquery_agent_analytics_plugin.go, tool_result_classifier_test.go): afterTool now records the owning activation for every finish_task call via noteTaskAttempt before err != nil early returns or confirmation-outcome handling (marking it completed only when err == nil && !confirmationOutcome && isTaskCompletedResult(result)) and retires non-completing call IDs when the final FunctionResponse arrives via retireFailedTaskAttempts, so promoted attempts close the originating activation's span while failed or confirmation-gated overlapping runs retire only their own pending attempt without stealing another run's callID. A completion event now matches activations only by the call IDs of its completed finish_task responses, so a failed finish_task merged into the same event cannot match another activation that reused its ID. These cases run through runner.New with an llmagent.ModeTask agent run twice by a custom parent, so ADK's own tool dispatch drives the callbacks.
  • Panicking Config.Logger.Printf inside recovery paths (schema_upgrade.go, bigquery_agent_analytics_plugin.go): Added safeLogf to swallow secondary logger panics and wired it into notifySchemaReady, notifySchemaError, runToolResultClassifier, and recoverCallback (covered by TestPlugin_PanickingLoggerInRecovery, which runs a function tool through runner.New and checks that the TOOL_COMPLETED row is kept when the classifier fails, and that a row dropped by recoverCallback is counted in DropStats without the logger's panic reaching the agent).
  • Releasing callback closures (bigquery_agent_analytics_plugin.go): Captured OnSchemaReady and OnSchemaError in constructor locals and cleared config.OnSchemaReady = nil and config.OnSchemaError = nil before passing Config into NewBatchProcessor / *BatchProcessor and analyticsPlugin.
  • adk-python parity docs (doc.go, doc_test.go, schema_callbacks_test.go, tool_result_classifier_test.go): Added the new behavioral-difference bullets to doc.go covering when Config.ToolResultClassifier is nil, abstains, panics, or returns an undefined decision (recording every nil-error tool result as EventToolCompleted, including plugin/retryandreflect guidance maps and "isError" / "is_error" maps) and the at-most-once Config.OnSchemaReady / Config.OnSchemaError lifecycle callbacks; bumped TestDocGo_ParityBulletsReferenceExistingTests in doc_test.go to 26 bullets, with TestDocParity_ToolResultClassifierNoImplicitErrorRules and TestDocParity_SchemaCallbacksAtMostOnce in schema_callbacks_test.go and TestPlugin_ToolResultClassifier_FailuresRecordToolCompleted in tool_result_classifier_test.go.

@caohy1988 caohy1988 left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Earlier review of a previous revision; the latest notes are in #2180 (review).

@wojtas000
wojtas000 dismissed their stale review November 18, 2026 08:48

Every item in this review is fixed on the current head.

wojtas000
wojtas000 previously approved these changes Nov 18, 2026

@wojtas000 wojtas000 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving. caohy1988's finish_task case is fixed: when an agent-level AfterToolCallback turns the validation failure into a completion, each AGENT_COMPLETED row now carries its own activation's span. My earlier item, the adk-python paragraph, is fixed too.

Two optional wording notes on config.go, neither blocks:

  • The sentence about the classifier seeing every result holds for a tool that ran. For a missing tool or a non-function tool, retryandreflect answers and ADK skips the after-tool callbacks, so the classifier never sees that answer.
  • "both kinds of result" could name the two it means.

On OnSchemaReady and Close, your option 2 in a follow-up PR is fine with me.

@wojtas000

Copy link
Copy Markdown
Contributor

This conflicts with main in bigquery_agent_analytics_plugin.go and trace_manager.go now that #2178, #2376, #2379 and #2250 have merged. Could you resolve it?

These PRs touch the same files, so could you rebase them as one stack, each on top of the one before: #2375, #2180, #2381, then #2380 and #2389? I'll merge each one as soon as it's up to date with main and green.

@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

@wojtas000 Thanks! I rebased #2180 cleanly onto #2375 as Layer 2 of the linear stack (main <- #2375 <- #2180 <- #2381 <- #2380 <- #2389), updated the PR description, and confirmed all 15 CI checks are green.

@caohy1988 caohy1988 left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Earlier review of a previous revision; the latest notes are in #2180 (review).

@haiyuan-eng-google
haiyuan-eng-google force-pushed the feat/bqaa-2014-v1-classifier-and-schema-callbacks branch from 64c0667 to 72817a9 Compare November 19, 2026 05:02
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review. All findings have been addressed:

  1. Blocking: finish_task span attribution and failed-attempt retirement across reused call IDs:

    • In finishedTaskLocked (trace_manager.go), recorded terminal outcomes (taskAttemptCompleted / taskAttemptFailedEnd, Tier 1 and Tier 2) now outrank pending attempts (taskAttemptPending, Tier 3), after filtering by eventTime plausibility and superseding earlier attempts only when a newer activation started after the earlier attempt and eventTime is at or after the newer activation's attempt. Allowing a newer taskAttemptPending to supersede an earlier recorded completion in that causal-supersede step is a deliberate trade-off to support AfterToolCallback promotion of a failed finish_task attempt on the newer activation; if an older concurrent same-node activation's own merged FunctionResponse event is stamped at or after a newer activation's failed attempt (after the newer activation started), those timestamps match the promoted-attempt ordering and resolve to the newer activation.
    • In retireFailedTaskAttemptsLocked (trace_manager.go), non-ending finish_task responses no longer delete a sibling activation's recorded terminal outcome for failedCalls while another run is open, while still retiring overruledEndingCallIDs when the failed first finish_task FunctionResponse had an empty call ID (falling back to ctx's matching activation or the newest open matching activation holding an observed ending for that ID, which can still retire a concurrent same-node sibling's recorded outcome if it reuses the overruled ID behind an empty-ID first failure). classifyTaskResponses and popTaskAgentSpanForCalls also carry all non-empty endingCallIDs so a trailing observed ending call ID resolves the activation when an earlier ending part had an empty or unobserved ID.
    • Updated TestTraceManager_FinishedTaskLocked in trace_manager_test.go to expect the completed activation rather than ambiguity, added TestRetireFailedTaskAttemptsLocked_PreservesSiblingRecordedSuccess in trace_manager_test.go to pin that failedCalls retirement leaves a sibling activation's recorded outcome intact when another activation is open with no pending match, and added runner tests covering both forwarding orders and promoted completions (TestPlugin_FinishTask_ReusedCallID_AttributionOrderings, TestPlugin_FinishTask_PromotedRun2DeliveredBeforeHeldRun1Completion, TestPlugin_FinishTask_FailedEmptyIDThenCompletedStaysOpenAndRetiresOverruledCall, and TestPlugin_FinishTask_TrailingObservedEndingCallIDResolvesActivation).
  2. Bounded verification after 409 on view DDL:

    • resolveDDLConflict (views.go) now polls table.Metadata with exponential backoff within the caller's ctx deadline (falling back to viewDDLTimeout when ctx has no deadline), retrying transient 404, 429, 5xx, and stale ViewQuery states while returning immediately on non-VIEW objects (TABLE, etc.) or non-retryable 400/401/403 errors. Covered by TestResolveDDLConflict_EdgeCases and TestPlugin_OnSchemaReady_ViewPass in schema_callbacks_test.go.
  3. Destination validation before firing OnSchemaReady (including 409 on table.Create with DisableSchemaUpgrade: true):

    • Added validateDestinationTableType in ensureTableAndSchema and maybeUpgradeSchema (schema_upgrade.go) to reject non-TABLE destinations (VIEW, MATERIALIZED_VIEW, EXTERNAL, and SNAPSHOT), and updated ensureTableAndSchema so an HTTP 409 / AlreadyExists conflict on table.Create always re-reads table.Metadata and validates its table type even when DisableSchemaUpgrade is true. Any 404, permission failure, or VIEW destination after a 409 now fails construction and routes to OnSchemaError rather than OnSchemaReady. Covered by TestEnsureTableAndSchema_ConflictOnCreateRecovery and TestValidateDestinationTableType in schema_upgrade_test.go and TestPlugin_OnSchemaError in schema_callbacks_test.go.
  4. Omitting remote response text from view conflict diagnostics:

    • Added unverifiedViewConflictError and safeErrorStatus (views.go) so Error() and startup warnings render only the operation, view name, and structured HTTP/gRPC status codes while keeping both the underlying DDL error and metadata verification error accessible via Unwrap(). Covered by TestPlugin_OnSchemaReady_ViewPass ("409 conflict error and logger omit raw response bodies while preserving Unwrap").
  5. Omitting function-call names and raw panic values from runToolResultClassifier warnings:

    • Updated runToolResultClassifier (bigquery_agent_analytics_plugin.go) to omit toolName and log only the pre-formatted panic type string (%s via fmt.Sprintf("%T", r), so the raw panic value is never passed as a Logger.Printf format argument) or the numeric decision (%d via int(verdict.Decision)). Covered by TestPlugin_ToolResultClassifier_FailuresAreSkipped in tool_result_classifier_test.go.
  6. Documentation and PR description alignment:

    • Aligned doc.go, config.go, and the PR description with the OnSchemaError field docs: only table setup failures invoke OnSchemaError, whereas a failed startup view logs a warning (through a non-default Config.Logger) and returns without invoking either OnSchemaReady or OnSchemaError (SyncViews returns view errors directly).
    • Clarified in Config.OnSchemaReady (config.go) that invalid view definitions prevent OnSchemaReady only when views are enabled (DisableCreateViews is false); when DisableCreateViews is set, view definitions are not validated at startup and OnSchemaReady fires synchronously once table setup succeeds.
    • Marked the PR description at the top as stacked on the prerequisite Close idempotency PR and stated the behavior changes relative to that base (while explicitly noting the cached Close result behavior relative to main).

@caohy1988 caohy1988 left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Earlier review of a previous revision; the latest notes are in #2180 (review).

@wojtas000

Copy link
Copy Markdown
Contributor

#2375 is merged, so could you rebase the rest of the stack onto main? Each branch still carries its two original commits, which landed on main as one squashed commit, so git rebase --onto main d3cb41e1 on this branch drops them. Your first commit here also conflicts with #2175, merged this morning, in views.go and bigquery_agent_analytics_plugin.go. #2381, #2380 and #2389 then go on top as before.

I went through caohy1988's latest items on all four PRs and none of them blocks merge for me, so once the stack is rebased and green I'll approve each one in turn. If you're touching the code anyway, three optional fixes from that pass:

  • Here, when two open runs of one task agent on the same branch both recorded call_0, finishedTaskLocked returns ambiguous and the completion is dropped. Ending the earliest recorded attempt would keep every run closed.
  • In #2381, a buffered call_0 success that arrives after the next attempt's OnToolErrorCallback clears the new attempt's error record, so the failure is written as two TOOL_ERROR rows. Retiring the record per dispatch avoids it.
  • In #2380, the new InvocationContext and ReadonlyContext lookups in contextPath miss and fall back to reflect.FieldByName's allocating search, which added about 9% allocations per run in my benchmark. directStructField would remove it.

…cle callbacks

Add Config.ToolResultClassifier, a hook that decides whether a tool result
returned without an error is recorded as TOOL_ERROR, with the classifier's
message or adk-python's default message when that is empty, or as
TOOL_COMPLETED. As in adk-python, it runs ahead of the built-in rule that
records a result whose top-level isError or is_error is true as TOOL_ERROR:
a ToolResultOK verdict overrides that rule, and a nil, abstaining, panicking
or undefined verdict leaves the result to it. The classifier runs after the
checks it cannot override (a tool error that OnToolErrorCallback recorded,
an error that reached AfterToolCallback unrecovered), sees a confirmation
outcome as the result ADK sends the model, and is skipped, with a warning
that names only the tool, when it panics or returns a decision that is not
defined. ToolResultVerdict has a blank first field, so code outside the
package builds it with keyed literals only.

Record every finish_task attempt on the calling activation before error
returns and classification run, as one that ended the task, one that ended
it with a tool result error, or one that did not end it and that a later
AfterToolCallback can still turn into a completion. A finish_task response
that does not end the task retires its own attempt, and one that ends the
task ends the activation that holds an attempt for one of its ending calls,
so a reused call ID cannot claim or retire another run's attempt. The
verdict decides only the tool call's rows: a runtime-successful finish_task
completion still completes the task span.

Add Config.OnSchemaReady and Config.OnSchemaError: the first is called once
the events table and, unless view creation is disabled, every startup view
are ready; the second with the error when the table cannot be read, created
or upgraded. Each is called at most once per plugin, and a panic in either
is recovered and logged. A 409 or AlreadyExists response to a view DDL job
counts as success only once the view is read back with the expected query.

Part of google#2014
…tion, and view table checks

Use the first finish_task response to decide task completion, attribute reused call IDs using leading EventActions map identity, O(N log N) causal supersession, event timestamps on failure retirement, multi-ID resolution before consumption, earliest-recorded tie-breaking, and unobservedTaskLocked fallback, and read platform.Now(ctx) before inv.mu only for task-mode agents. Reconcile evicted and restored traces under tm.mu at run end, retry 409 view metadata checks with status-only error logs and DeadlineExceeded unwrapping, validate ViewPrefix unconditionally, reject non-regular destination tables before OnSchemaReady, pre-format panic types as strings, and omit unregistered tool names from classifier warnings.
@haiyuan-eng-google
haiyuan-eng-google force-pushed the feat/bqaa-2014-v1-classifier-and-schema-callbacks branch from 72817a9 to 621b546 Compare November 19, 2026 19:05
@haiyuan-eng-google

Copy link
Copy Markdown
Contributor Author

@wojtas000 @caohy1988 Thanks for the reviews and the rebase pointer! I rebased the branch directly onto main (dropping the already-merged #2375 commits, resolving the #2175 conflicts in bigquery_agent_analytics_plugin.go and views.go, and merging CreateEvalViews startup handling with OnSchemaReady), and addressed all blocking and follow-up items:

  1. Blocking — Concurrent runs reusing call_0 dropping AGENT_COMPLETED rows (resolveFinishedTaskLocked):

    • In trace_manager.go, noteTaskStart and noteTaskAttempt now record weak references (weak.Pointer[byte] via taskDispatchMaps) to the tool dispatch's EventActions maps (StateDelta/ArtifactDelta), and resolveFinishedTaskLocked matches leading-part EventActions map identity first (without retaining user state payloads).
    • Remaining same-tier single-call ties now resolve to the earliest-recorded attempt (earlierTaskAttempt: recordedAt, then seq, then stack order) instead of returning taskMatchAmbiguous and leaving later runs poisoned.
    • Covered by TestPlugin_FinishTask_ConcurrentCall0ReuseFanOut (both the deterministic 2-way 3-wave frozen-clock runner test and the 8-way × 10-round concurrent fan-out), plus updated expectations in TestTraceManager_FinishedTaskLocked and TestFinishedTaskLocked_RequiresOneRunOnTheEventPath.
  2. Blocking — Ownership mix-ups across sibling runs, merged responses, and delayed failures (resolveFinishedTaskLocked, retireFailedTaskAttemptsAtLocked):

    • resolveFinishedTaskLocked now evaluates all non-empty endingCallIDs together before consuming any attempt (consumeWinner), filters out candidates disproved by the event's leading EventActions dispatch maps when another candidate or plausible open activation exists, skips per-attempt recordedAt exclusion on merged multi-tool responses (!mergedResponse) so parallel tool timestamps do not drop sibling attempts, and returns taskMatchAmbiguous without consuming if surviving observed call IDs split across disjoint activations.
    • retireFailedTaskAttemptsForEvent / retireFailedTaskAttemptsAtLocked now accept ev.Timestamp and leading-part dispatch maps, preferring exact dispatch-map matches and excluding activations or single-call attempts recorded after eventTime so a delayed older failure cannot retire a newer activation's pending attempt.
    • Covered by TestPlugin_FinishTask_MergedReusedLeadingShortCircuitedAndUniqueTrailingCallID, TestPlugin_FinishTask_CoordinatorBufferedFailureDoesNotRetireNewerWorkerAttempt, and TestPlugin_FinishTask_MergedParallelToolTimestampPredatingAfterToolRecordedAt.
  3. Blocking — Evicted and restored active trace staying open on run end (endInvocationTarget, completeRunEndTarget):

    • Under tm.mu in endInvocationTarget and completeRunEndTarget, when cur != inv && cur.rootSpanID == inv.rootSpanID, both inv and cur are now published to rememberCompletedAtLocked (while preserving non-empty traceID / rootAgentName), ensuring cur is closed and unlinked from tm.invocations and tm.evicted. Covered by TestEndInvocation_ReconcilesEvictedAndRestoredActiveTrace (both paths at capacity 1).
  4. Log argument sanitization, DeadlineExceeded unwrapping, and ViewPrefix / #2175 alignment:

    • notifySchemaReady and notifySchemaError (schema_upgrade.go) now pre-format panic types with fmt.Sprintf("%T", r) (%s), and syncAnalyticsViewsWithRetryHint (views.go) passes sanitized err.Error() (%s) to logf while preserving %w on returned errors; both are verified against recordingLogger.argsSnapshot() in TestNotifySchemaCallbacks and TestPlugin_OnSchemaReady_ViewPass.
    • unverifiedViewConflictError.Unwrap() (views.go) now preserves deadlineErr (verifyCtx.Err() / ctx.Err()) when view conflict verification exceeds its deadline, verified in TestResolveDDLConflict_EdgeCases.
    • Kept main's unconditional ViewPrefix validation in validateConfig (bigquery_agent_analytics_plugin.go) alongside #2175 CreateEvalViews + OnSchemaReady startup integration (tested in TestPlugin_OnSchemaReady_TablePass), and documented the finish_task attribution changes relative to main in the PR description.
  5. Performance, lock ordering, unobservedTaskLocked fallback, and newly pinned guards:

    • Replaced the quadratic candidate supersession loop in resolveFinishedTaskLocked with an O(N log N) sorted suffix-maximum pass (verified at 512 overlapping activations in TestResolveFinishedTaskLocked_512OverlappingActivationsEquivalence), moved platform.Now(ctx) before inv.lockLive() in pushAgentSpan gated on children.taskMode (TestPushAgentSpan_PlatformClockOutsideLockAndTaskModeOnly), and restored unobservedTaskLocked tie fallback for non-empty call IDs (TestTraceManager_UnobservedTaskLocked).
    • Added pinning tests for noteTaskStart, concurrent frozen-clock overruledEndingCallIDs (TestPlugin_FinishTask_NoteTaskStartAndOverruledEndingGuards), validateDestinationTableType on maybeUpgradeSchema retry (TestMaybeUpgradeSchema_RetryRevalidatesDestinationTableType), and 5xx coverage in isRetryableConflictVerifyError (TestIsRetryableConflictVerifyError and TestResolveDDLConflict_EdgeCases).

Verified at 621b5462: gofmt, git diff --check, mod tidy -diff, go vet, golangci-lint (0 issues), targeted -race, and full go test -mod=readonly -count=1 ./... in plugin/agentanalytics all pass.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The new merged-response matching still misattributes completions in a few concurrent cases, and a couple of the new error paths leak response bodies. I reproduced each of the issues below with a targeted test that fails at this head and passes at the merge base (6b4c6d5), so they look introduced by this change.

Merged-response attribution

  • trace_manager.go (~4632): a later attempt can supersede earlier candidates across different call IDs, and the set of observed IDs is built after that pruning. If worker A completes shared and unique while its leading lookup is still in flight, worker B's later pending attempt for shared can wipe out A's evidence for both IDs. The runner then writes A's AGENT_COMPLETED on B's span and B's AGENT_ERROR on A's. Keeping the full observed-ID set when deciding which activations could have produced the merged event, and only then applying timing/outcome preferences, should fix it.
  • trace_manager.go (~5029): after the leading response's action maps have already identified the batch owner (~4974), the sibling search for leftover overruled call IDs still runs and can delete a different worker's recorded success with the same ID. Once the owner is known, retirement should be limited to that activation.
  • trace_manager.go (~4924-4931, ~4982-4988): treating mergedResponse as a blanket exemption from the recordedAt plausibility check, combined with the newest-first retirement scan, lets a delayed merged failure led by another tool retire a newer activation's attempts. A following completion with cleared EventActions then closes the older activation's span and leaves the real one open. I'd keep the timestamp check across different activations and only relax it once the event's activation is positively identified; when it can't be identified, leave the ambiguous newer attempts alone.

Trace restoration

  • trace_manager.go (~2923 / ~3317): when the two copies of the root are reconciled, the restored copy's nonempty trace ID wins, but it can still hold the generated ID from eviction even though the end row just adopted the ambient trace ID. Late rows then share the end row's root span ID with a different trace ID. The adopted ID should be preserved.

Error redaction

  • views.go (~1936): ordinary (non-409) view failures are now passed to the logger as err.Error() strings, so a logger that strips bodies from error-typed arguments receives the service response body. Formatting these with safeErrorStatus before logging, while keeping the typed cause on the returned error, would restore the previous behavior.
  • schema_upgrade.go (~134): the new post-conflict metadata read wraps its error with %w, so the constructor error and the OnSchemaError callback both include the upstream response body. Returning an error whose Error() reports the operation and status, with Unwrap() keeping the service error, avoids that.

Two smaller things worth addressing while you're in there: matching one merged batch is quadratic in the number of distinct call IDs while holding the invocation lock (roughly 32 ms at 2,048 IDs), and the eviction/restore test relies on a 5 ms sleep after a signal that fires before the original invocation lookup, so it can pass or fail depending on scheduling. Synchronizing after the lookup (e.g. in the agent metadata callback) would make it deterministic.

Full module tests, -race, vet, tidy and gofmt are all clean otherwise, and the classifier's zero-value behavior and at-most-once schema callbacks look good.

@wojtas000 wojtas000 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving. I re-checked the rebased commits against the earlier audit: the reused call_0 case now keeps both AGENT_COMPLETED rows with their own spans, the evicted-and-restored run is reconciled under tm.mu, and the eval views from #2175 came through the rebase unchanged. Build, vet, tidy and the race suite pass on the head and on its merge with main. Optional cleanup: popTaskAgentSpan, popTaskAgentSpanForCalls, finishedTaskLocked and the two retireFailedTaskAttempts helpers no longer have production callers.

@wojtas000
wojtas000 merged commit 98275d2 into google:main Nov 19, 2026
15 checks passed
indurireddy-TF pushed a commit to indurireddy-TF/adk-go_local that referenced this pull request Nov 24, 2026
…cle callbacks (google#2180)

* feat(agentanalytics): add ToolResultClassifier hook and schema lifecycle callbacks

Add Config.ToolResultClassifier, a hook that decides whether a tool result
returned without an error is recorded as TOOL_ERROR, with the classifier's
message or adk-python's default message when that is empty, or as
TOOL_COMPLETED. As in adk-python, it runs ahead of the built-in rule that
records a result whose top-level isError or is_error is true as TOOL_ERROR:
a ToolResultOK verdict overrides that rule, and a nil, abstaining, panicking
or undefined verdict leaves the result to it. The classifier runs after the
checks it cannot override (a tool error that OnToolErrorCallback recorded,
an error that reached AfterToolCallback unrecovered), sees a confirmation
outcome as the result ADK sends the model, and is skipped, with a warning
that names only the tool, when it panics or returns a decision that is not
defined. ToolResultVerdict has a blank first field, so code outside the
package builds it with keyed literals only.

Record every finish_task attempt on the calling activation before error
returns and classification run, as one that ended the task, one that ended
it with a tool result error, or one that did not end it and that a later
AfterToolCallback can still turn into a completion. A finish_task response
that does not end the task retires its own attempt, and one that ends the
task ends the activation that holds an attempt for one of its ending calls,
so a reused call ID cannot claim or retire another run's attempt. The
verdict decides only the tool call's rows: a runtime-successful finish_task
completion still completes the task span.

Add Config.OnSchemaReady and Config.OnSchemaError: the first is called once
the events table and, unless view creation is disabled, every startup view
are ready; the second with the error when the table cannot be read, created
or upgraded. Each is called at most once per plugin, and a panic in either
is recovered and logged. A 409 or AlreadyExists response to a view DDL job
counts as success only once the view is read back with the expected query.

Part of google#2014

* fix(agentanalytics): harden finish_task attribution, 409 DDL verification, and view table checks

Use the first finish_task response to decide task completion, attribute reused call IDs using leading EventActions map identity, O(N log N) causal supersession, event timestamps on failure retirement, multi-ID resolution before consumption, earliest-recorded tie-breaking, and unobservedTaskLocked fallback, and read platform.Now(ctx) before inv.mu only for task-mode agents. Reconcile evicted and restored traces under tm.mu at run end, retry 409 view metadata checks with status-only error logs and DeadlineExceeded unwrapping, validate ViewPrefix unconditionally, reject non-regular destination tables before OnSchemaReady, pre-format panic types as strings, and omit unregistered tool names from classifier warnings.

---------

Co-authored-by: Jan Wojtas <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants