Repository navigation
Conversation
…2316) The model sometimes calls a tool the agent does not have. adk-go sent it straight to the on-tool-error callbacks, and the model got the lookup error. That error lists the available tools in Go map order, followed by a block of debuging advice meant for developers. adk-python 2.12 runs the before-tool callbacks first, so a plugin or agent callback can still answer the call. An answer then goes through the after-tool callbacks, as for a tool that exists. With no answer, the on-tool-error callbacks get the lookup error, and the after-tool callbacks are skipped because no tool runs. If no callback answers, the model gets a short text that names the tools it can call, or "none". adk-go now follows the same order. A before-tool error for an unknown tool goes through the on-tool-error and after-tool callbacks, as it does for a tool that exists. The model gets adk-python's not-found text, and the callbacks keep the lookup error. adk-python lists tools in declaration order. adk-go only has a map at this point, so it sorts the names in both texts.
A live session sent no ADK tracking labels. ADK set its tracking headers only on generate requests, and the genai SDK builds the live WebSocket handshake from the client's headers alone, so the handshake carried `User-Agent: Go-http-client/1.1` and no `x-goog-api-client`. genai rejects LiveConnectConfig.HTTPOptions, so the headers cannot be passed per connection. NewModel now merges ADK's tracking labels into the client's x-goog-api-client and user-agent headers, so the live handshake and every other call made through Client() carry them. Generate requests still replace those headers with their own, so they are unchanged. The merge rule moves from mcptoolset into version.WithTrackingHeaders, now shared by both: ADK's tokens first, then the caller's tokens without duplicates, matching header names in any casing. That is the rule adk-python's merge_tracking_headers applies. Matching any casing also changes mcptoolset: a request header set under a non-canonical key is now merged instead of sent alongside ADK's. Fixes #2365 Co-authored-by: wolo <[email protected]>
…stom metadata truncation flag (#2020) * fix(agentanalytics): preserve retired late parent cancel cause and custom metadata truncation flag - dropRetiredLateContextsLocked cleared canceled on every agent span retired from a late trace, even one that an open span still reaches through its parent chain. contextFailureCause, canceledByStop and collateralFailureCause read canceled on each record of that chain, so a context.Canceled error that the open span recorded after its parent retired was a failure in the late state where the live state records it as collateral, and the failure kept the activation from retiring. canceled is now cleared together with parent, on the records that nothing reaches anymore. The drop also walks up from each of them through the retired records above it, up to the first span that is still open or still reached, so that a record kept for a span under it no longer keeps canceled and parent once that span retires too. - completeResponse retired settled late activations only before its last return. Its early returns for an author with no open span and for an event that selectResponseOwnerLocked absorbs can also leave an activation that nothing can end anymore, so the call is now deferred. - The comments on popUnclosedAgentSpans, settleEndedInSubtreeLocked, retireLateSettledLocked, retireAgentLocked, purgeActivationLocked and spanRecord.canceled now describe what the code does. - New tests pin that a record retired from a late trace drops ended and activation. The records that the existing checks retire had already cleared both. - attributes() never set is_truncated when scrubbing replaced a custom_metadata value with a safety placeholder, so of the session-event rows only EVENT_COMPACTION, AGENT_STATE_CHECKPOINT and A2A_INTERACTION, which fold it in themselves, reported it. scrubA2ACustomMetadata now returns the keys whose values lost content, and attributes() sets is_truncated when custom_metadata keeps one of them. Part of #2014 * fix(agentanalytics): retire settled late activations whose cause nothing reads - retireLateSettledLocked kept a settled late activation that carries a failure cause (see spanRecord.openFailureCause) as failed, and marked the agents above it as failed too, until the completed run was pruned. Since a retired record that an open span still reaches keeps canceled, a sub-agent on the branch of a parallel branch whose context a failing sibling canceled carries that cause through the branch. When its last model call ended after the branch and the agent above it had ended, it stayed on the late agentStack with openAgents set, while it retires with the branch when the call ends first. - A failure cause now keeps an activation only while something can still read it: an agent above it that is still open, following parent across the agents that already retired, through which failure reporting reads the cause and whose end moves the cause up (see retireAgentLocked), or, for an activation right under the invocation span on a node path below that span's, a tool call under the invocation span that is still open, as the root agent's calls are in RunLive, since the end of the last such call reports the failures of those activations (see endToolRunsLocked). The cause no longer marks the agents above the activation as failed, so an agent above it that only an open call keeps retires once the call returns, even if it carries the same cause, and the activation retires right after it. Nothing else reads a late cause, so no row changes. - TestLateRecoveryEventRetiresSettledActivation keeps an agent open above the activation, so that the cause still keeps the activation until the recovery event clears it. - New tests cover each order of the last call against the ends of the agents above, including the one from the review, an agent above the activation that only its open tool call keeps, an activation that the first of two tool calls of the root agent ran, whose AGENT_ERROR row the end of the last of them writes, whichever of them ends last, and an activation under the invocation span that a tool call of another agent ran, which retires once that call returns. Part of #2014 * fix(agentanalytics): keep a root tool run whose subtree carries a late cause - retireLateSettledLocked kept a settled late activation for a failure cause only if the activation carried the cause itself. While a tool call under the invocation span is open, as the root agent's calls are in RunLive, the end of the last such call reads the causes in the whole subtree of each activation right under the invocation span through that activation (see endToolRunsLocked and failuresLocked). So when call-1 of the root agent ran g, g ran x, only x carried a cause, and call-1 returned while call-2 was still open, g retired as it carried no cause, x then retired as nothing above it was open, and the end of call-2 wrote no AGENT_ERROR row, where the end of call-1 writes one for g when no other call is open. - A cause now keeps an activation that carries it or runs an activation that does, while something can still read the cause through it: an agent above it that is still open, or, for an activation right under the invocation span on a node path below that span's, a tool call under the invocation span that is still open. Failure reporting writes the rows of the activations that failed along their lineage on agentStack, so the activations between the one that carries the cause and the reader stay as well: one whose parent ended first no longer retires before the reader reads the cause, which dropped its row. Once nothing can read the cause, it keeps no activation, as before, so the late state still drains. - The doc of TestLateCauseKeepsNoAgentAbove now says that the cause keeps none of the agents above the activation once nothing above them can read it. - New tests run each order of the two calls against the order in which no other call is open, for a cause on a child of the root tool run, either its own context cause or one that a parallel branch left on it, next to a sibling that carries none and leaves with the run without a row, and for a cause below an activation whose parent ended first, read through the calls of the root agent or of an agent that is still open, and check that once the root tool run ended first, nothing keeps the activations under it. Part of #2014 * docs(agentanalytics): scope the late-cause timing comment to failure causes - The comment above retireLateSettledLocked said that the rows do not depend on whether failure reporting reads the causes as soon as the activations settle or only later. That holds for a failure cause (see spanRecord.openFailureCause), which heldByCause keeps an activation for and retireAgentLocked moves up, including the cause of a collateral error whose cancellation started at a parallel branch, which is that branch's context failure cause. It does not hold for a collateral error whose cancellation started at another stop point, such as a workflow node: openFailureCause does not return its cause and the scan of the unrecovered errors skips the error, so nothing keeps an activation for it, and the rows depend on whether the reading comes before the activation that the error is attributed to retires or only later. The comment now says so, and that a failure cause keeps no activation once nothing that is open can read it. - The doc of TestLateCauseRetiresWithoutRootToolCall now says what a tool call under the invocation span that starts after the call that ran g returned finds: g already retired, so its end writes no AGENT_ERROR row for g, whereas a call that is open when that call returns keeps g, and on a live trace, which retireLateSettledLocked leaves alone, g is still open. Comment-only change; no behavior change. Part of #2014 * test(agentanalytics): pin the late causes a root tool call cannot read - While a tool call under the invocation span is open, as the root agent's calls are in RunLive, heldByCause in retireLateSettledLocked keeps a settled late activation right under the invocation span only if the end of the last such call can read a failure cause through it: the cause must be in the activation's own subtree, and the activation must run on a node path below the invocation span's, as only those are read by endToolRunsLocked. No test failed when either restriction was dropped. - TestLateRootToolCallHoldsOnlyCausesItReads covers both. When g and h each run on a branch and node path of their own and only h carries a cause, g retires once call-1 returns while call-2 is still open, h stays, and the end of call-2 writes only h's AGENT_ERROR row. When g carries a cause but runs on the invocation span's own node path, g retires once call-1 returns although call-2 is still open, and the end of call-2 writes no AGENT_ERROR row. Without the subtree check, the late agentStack keeps [g h] instead of [h] in the first case; without the node-path check, it keeps [g] instead of none in the second. - The doc of TestLateCauseRetiresWithoutRootToolCall now calls the call that is open when o's call returns "such a call", one under the invocation span. Test-only change; no behavior change. Part of #2014 * fix(agentanalytics): hold late failure cause while any tool call remains open When an agent ends before its tool call does, findAgentForContext returns -1 and endToolRunsLocked resolves the owner to the invocation span via max(0, ...), reporting the failures of activations right under the invocation span. retireLateSettledLocked previously checked only call.parentSpanID == invSpan.spanID, prematurely retiring late activations whose failure cause could still be read by an open tool call whose caller already retired. Checking len(inv.toolSpans) > 0 ensures the cause is held while any tool call remains open. * fix(agentanalytics): stage retired late root subtrees for later root tool calls When a settled late activation right under the invocation span on a sub-node path retires in retireLateSettledLocked while no tool call is open, keep any ancestor whose subtree still has an unsettled descendant on agentStack until the whole subtree settles, then stage the settled subtree and its failure causes on invocationTrace (pendingRootToolFailures) before removing the spans from agentStack and dropping their callback contexts. If a late recovery event arrives in completeResponse after the subtree was staged, clear matching swallowableBySelf causes and settle staged response owners just as on agentStack. When a subsequent tool call under the invocation span finishes in endToolRunsLocked, materialize and drain any remaining staged subtree failures in (rootSeq desc, seq desc) order so the emitted AGENT_ERROR rows match live traces without retaining callback contexts after retirement. * fix(agentanalytics): hold direct sub-node failure causes on agentStack Keep settled activations directly under the invocation span on a sub-node path carrying a failure cause on agentStack rather than staging them off-stack in pendingRootToolFailures, so later child activations, response recovery routing, error recording, retries, and hasOpenLateSpans observe the same state on late and live traces. Restore direct settled-activation retirement without subtreeSettled so a settled activation carrying no cause retires above still-open children. --------- Co-authored-by: Jan Wojtas <[email protected]>
) * fix(session): apply persistent changes only after database commit Keep rejected events and ordinary state out of the local session when persistence fails, including commit failures. Serialize appends on the same session so local updates follow database commit order. Fixes #2304 * test(session): cover stale and deleted append failures Relax the queued cancellation timeout and remove an outdated trimming comment. Refs #2304 --------- Co-authored-by: Jan Wojtas <[email protected]>
Cutting with a byte slice could split a multi-byte UTF-8 character and log invalid UTF-8. Truncate by rune count instead, as adk-python's text[:max_length] does. Fixes #2341 Co-authored-by: Jan Wojtas <[email protected]>
…ion (#2322) * fix(runner): skip nil parts in response events and input blob extraction Guards against nil parts in Content.Parts when checking for tool calls, inline data, and input blob extraction in the runner. Previously, an event or user message with a nil part caused a nil pointer dereference panic. Fixes #2321 * test(runner): strengthen live nil part tests and document python parity Adds live runner tests covering nil before tool call buffering and nil before inline data, and documents adk-python divergence when skipping nil parts during artifact extraction. Addresses review comments from #2322 --------- Co-authored-by: Jan Wojtas <[email protected]>
… state names (#2334) * fix(llminternal): accept Unicode identifier characters in instruction state names isIdentifier said it matched Python's str.isidentifier(), which adk-python's _is_valid_state_name uses, but it accepted only letters, decimal digits and "_". Placeholders whose names contain combining marks, such as most Thai and Devanagari words, were left in the instruction unchanged instead of being filled from session state. Check the first character against "_" or ID_Start and the rest against ID_Continue (Unicode UAX #31), using the standard unicode tables. Fixes #2333 * fix(llminternal): reject U+309B and U+309C in state names and document the rule U+309B and U+309C are ID_Start only through Other_ID_Start and are not XID_Start or XID_Continue, so Python's str.isidentifier rejects them. Exclude them so that {a゛} stays literal as in adk-python, and say in the isIdentifier comment that the check is the Unicode ID_* rule with this one difference. Add cases for connector punctuation, Other_ID_Continue, Other_ID_Start and a combining mark in the first position, each of which fails if the matching table or the first-character check is dropped. Update the Instruction, GlobalInstruction and InjectSessionState doc comments, which still described state names as ^[a-zA-Z_][a-zA-Z0-9_]*$. --------- Co-authored-by: Jan Wojtas <[email protected]>
A batch span processor starts its goroutine when it is built, and New built one for each span exporter before creating the exporters that follow it. When a later exporter failed, such as the OTLP metric exporter rejecting a certificate for a plain HTTP endpoint, New returned the error and left that goroutine running with nothing able to stop it. Exporters are now collected first, and span and log processors are built only once every exporter was created, the rule metric readers already followed. The OTLP metric export test now checks that a flush reaches the endpoint, not only that Shutdown sends nothing, and the exporter configuration test shuts down every processor it builds. Fixes #2317 Co-authored-by: Jan Wojtas <[email protected]>
…2332) A summary redacted and cut the code of an executable code part and the output of a code execution result part, but printed the part's language and outcome as they came. Both are plain string types that a model or a remote agent can set to anything, so a credential-shaped or oversized value in either one reached content.response and text_summary unredacted and uncut. Both summary builders now pass the label through the same redaction as the rest of the summary and cut it at 256 runes, the bound function names already have in response summaries. A negative limit lifts the cut and keeps the redaction. An empty label is still shown as "unknown", and the documented enum values are unchanged. Fixes #2259 Co-authored-by: Jan Wojtas <[email protected]>
* feat(vertexairagtool): expose RAG retrieval configuration * docs(examples): demonstrate Vertex AI RAG retrieval configuration * docs(examples/tools): demonstrate Vertex AI RAG retrieval configuration * fix(vertexairagtool): reject conflicting retrieval settings and correct test fixtures * docs(examples/tools): remove comment describing unused retrieval fields * refactor(vertexairagtool): use a sentinel error for conflicting retrieval settings --------- Co-authored-by: Jan Wojtas <[email protected]>
#2384) Add package gcsskill, a skill.Source that reads skills from a Cloud Storage bucket. Skills are the immediate subdirectories of an optional base path, laid out as skill.NewFileSystemSource expects. The caller creates the *storage.Client and passes it in Config.Client; the source neither creates nor closes one. Listing fails on the first invalid skill. Config.OnListInvalidSkill lets the caller skip an invalid skill instead. A request to Cloud Storage that fails always fails the listing and is never offered to it, as in adk-python. Of a SKILL.md object only the frontmatter is read, unless the instructions are asked for. Instructions are loaded from objects of at most 10 MiB and returned without the white space around them. Resources are named as adk-python names them: in the name of an object a backslash separates like a slash, and empty and "." segments are dropped. An object whose name has a ".." segment or starts with a separator or a drive ("c:"), and two objects that name one resource, are rejected. Resources are served only for a valid skill. The source remembers the skills whose SKILL.md it found valid, so that it does not read a SKILL.md again before every resource. Tests build the source with NewSource over a real storage client that talks to an in-process HTTP fake of the JSON API.
#2377) * refactor(agentanalytics): add args digest and context identity helpers * fix(agentanalytics): harden bounded args digest and tool context identity * fix(agentanalytics): harden context identity, StateDelta pinning, and struct copy bounds - Drop bare ctxPtr/ctxTyp on the weak EventActions branch of toolCallIdentityOf so live EventActions equality is the attempt identity (preventing recycled-address false matches and keeping WithAgentTimeout contexts aligned), and skip pointer identity for zero-size pointee context types. - Retain the captured EventActions.StateDelta map directly in taskDeltaRef.m across wrapped context paths so replacing StateDelta cannot let GC recycle the captured map address. - Charge inline struct byte size in typeDigestCostDetail and hash so maps and arrays of structs exceeding the copy bound truncate before copying elements. - Add tests covering [N]byte digest sensitivity, same-address different-type pointer contexts (&outer vs &outer.embedded), WithAgentTimeout identity, zero-size pointer contexts, StateDelta replacement under GC, and bounded allocation on maps/arrays of structs. * fix(agentanalytics): guard zero node budget in struct digest cost - Reject remNodes < 1 in typeDigestCostDetail for reflect.Struct so zero-node array traversals of small structs emit a single budget marker instead of iterating elements. - Add a unit test pinning zero-node struct and struct-array digest behavior, and give sibling_mid_struct_map 64 KiB of TotalAlloc headroom above maxDigestBytes. * fix(agentanalytics): match an error-ended tool call to its own attempt
* refactor(auth): build the ADC paths on cloud.google.com/go/auth The Agent Identity client and auth.ADC minted their tokens through golang.org/x/oauth2/google and wrote the bearer header by hand over a plain transport. That path knows nothing about client certificates or the quota project, so an agent whose environment configures a workload certificate reached the credential services without presenting it, and one whose ADC names a quota project got billing mismatches. The auth/gcp default client now comes from httptransport.NewClient, the transport the Google Cloud client libraries use, which presents the configured client certificate, forwards the ADC quota project and caches tokens. auth.ADC discovers credentials through credentials.DetectDefault, bridged to the oauth2.TokenSource the public API keeps exposing. Neither path captures the construction context any more. Test fixtures move from an authorized_user file to a service-account key, because credential discovery only honors token_uri for the latter. * refactor(auth): review fixes for the go/auth ADC paths - gcp.NewProvider no longer retains its context: the only reader was the default client's build, which takes nothing from it. The lazy build runs on the first waiting request's context with its cancellation stripped. - docs: a client certificate is only presented to an endpoint that requests one, and the default endpoints do not; the oauth2.HTTPClient context hook (v2.5.0 through v2.8.0) is documented as gone; the PollTimeout recipe is spelled out in full; universe-domain and error-type notes. - adcTokenSource clones the scopes before DetectDefault, because the compute credential keeps the slice and reads it on every refresh. - a default client that cannot be built reports "build default credentials client" rather than "find default credentials". - tests: the fixtures pin the rest of the ADC environment the library reads, the quota-project test asserts the bearer and the requested scope, the auth mint test asserts the scope per provider and cancels the Credential context before the first Apply, and three stale comments are corrected. * refactor(auth): second round of review fixes for the go/auth ADC paths The detached-context test canceled the request from inside the builder and still demanded that request succeed, so its ctx.Done arm raced the published result and failed about once in 55 runs under -race. The test now accepts either outcome for the canceled waiter and checks the cached client on a second call instead. TestCredentialSurfacesAnUnavailableClient ran the real default builder with only GOOGLE_APPLICATION_CREDENTIALS pinned, which executed a workstation's certificate signer and could fix the once-per-process trust boundary opt-in for every later test. It now pins the same environment the in-package tests do, through a test-only export. Restore the empty-scopes ServiceAccount ADC fallback row, which the previous round had replaced rather than kept, and correct the NewClient migration sentence: a plain client under Config.HTTPClient sends no credentials, so the PollTimeout recipe is the replacement, not that field. * docs(auth): narrow two claims the review refuted by execution The RetrieveCredential doc promised *auth.Error for any rejected token request, but only the service-account key and authorized_user providers return that type. Metadata-server, impersonated and external-account credentials report a plain message on this release and on the oauth2-based ones, so the sentence now names the types it covers. The auth package's isolateADCEnv said the trust boundary variable would change what its tests send. Nothing on that path starts the lookup, since the token is applied by OAuth2Credential rather than the library's transports. Say so, and keep the pins for parity with the gcp copy. * docs(auth): stop enumerating token error types per credential source Every version of the RetrieveCredential paragraph that listed which credential sources yield which error type was wrong for at least one of them (the metadata server wraps *metadata.Error, impersonation yields *auth.Error on its source key). Promise only what the package controls: the error is the auth library's, and for a service-account key it is *auth.Error where it was *oauth2.RetrieveError. Scope the auth package's isolateADCEnv doc to the service-account-key fixture its tests use. An impersonated credential does read the quota project and trust boundary variables on this path. * docs(auth): drop the per-source detail from the isolateADCEnv doc The parenthetical said an impersonated credential sends the quota project on this path. That holds for the ID-token path and not for ADC or the no-audience fallback, so say only what the pins are for. * fix(auth): keep the ADC token exchange out of SDK debug logs and spans With GOOGLE_SDK_GO_LOGGING_LEVEL=debug the auth library's default logger wrote the signed assertion and the minted token to stderr on both ADC paths. Both now pass a discarding logger. The default gcp client also turns the library's telemetry off, as through v2.8.0, so no client span is opened per call. Docs: where the quota project header comes from, the token endpoint a certificate moves user credentials to, the per-process certificate source cache, and the SecureConnect helper among the calls that ignore cancellation. Tests: debug-log and span pins, the token error type, an explicit-scope ADC row, and atomics for handler-written values.
…ps (#2376) * fix(agentanalytics): isolate BigQuery RowErrors and track RowErrorDrops Isolate per-row AppendRowsResponse.RowErrors rejections in BatchProcessor so surviving valid rows in the same batch are still written instead of dropping the whole batch. - Add DropStats.RowErrorDrops (included in TotalDrops) to count rows permanently rejected by BigQuery RowErrors. - Guard ExactlyOnceDelivery against replaying surviving rows after an ambiguous send on the stream so duplicate delivery cannot occur. Related: #2014 * fix(agentanalytics): harden RowErrors isolation, log sanitization, and pass cap Address review feedback on RowErrors isolation in BatchProcessor: - Drop free-form RowError.Message text from the row-error warning (logging message_bytes instead) and sanitize control characters and credentials in fallback response logs and errors. - Guard ambiguous-send RowErrors before the ExactlyOnceDelivery AlreadyExists shortcut so contradictory responses drop the batch without advancing streamOffset. - Bound per-chunk RowErrors isolation to maxRowErrorIsolationPasses (8) passes, counting remaining unconfirmed rows under AppendFailureDrops. - Detect nil-only RowErrors entries cleanly instead of reporting an out-of-range index. - Scope Arrow record construction and append calls in a closure with deferred Release() so panics do not leak Arrow buffers. - Add tests covering PermissionDenied/Unavailable + RowErrors, pass cap, fallback log sanitization, nil-only RowErrors, AlreadyExists + RowErrors after ambiguous send, and panic record release. * fix(agentanalytics): normalize JSON/URI controls in sanitizeErrorForLog and pin pass cap Address follow-up review feedback on RowErrors isolation in BatchProcessor: - Replace ASCII C0, DEL/C1 (U+007F-U+009F), U+2028/U+2029 control runes, and invalid UTF-8 bytes in sanitizeErrorForLog; update trimLogSpace to strip leading/trailing invalid 1-byte UTF-8 sequences alongside whitespace and control runes while preserving valid 3-byte U+FFFD; fail closed on control-bearing URIs before control normalization can split them; reject invalid UTF-8 JSON inputs before encoding/json can substitute U+FFFD (without falling back to prose for brace/bracket containers or container-prefixed quoted strings); and recursively normalize JSON object keys, strings, and nested JSON values before re-marshaling so JSON escapes and json.Marshal escapes (\u000b, \u0085, \u2028, \u2029) cannot bypass redaction, failing closed on malformed JSON or backslash/percent control escapes hiding credentials. - Log only code, row_errors, and message_bytes in the appendChunkRows fallback warning so callers logging the returned sanitized error do not duplicate backend status text. - Pin literal 10-row / 8-pass / 8-row-drop / 2-append-drop expectations in the RowErrors pass-cap subtest, scale the linear-time URI test wall-clock cap under -race, and expand sanitization tests for C0/C1/line-separator controls, JSON-escaped and re-marshaled payloads, control-bearing URIs, invalid UTF-8 JSON/URI/leading-byte inputs, valid U+FFFD preservation, and fallback log framing. * fix(agentanalytics): simplify log control sanitization and address review feedback - Remove the JSON/URI scrubbing helpers from batch_processor.go while keeping isLogControlRune (C0, DEL/C1 U+007F-U+009F, U+2028, U+2029) and invalid UTF-8 replacement in sanitizeErrorForLog, and remove dead sanitizeErrorForLog assignments in streamWriter.append's retry loop. - Clarify maxRowErrorIsolationPasses, RetryConfig, Config, doc.go, and appendChunkRows comments for pass-cap semantics, isolation preconditions, AlreadyExists confirmation, and adk-python RowErrors parity. - Preserve Unwrap and include prior RowErrors-rejected row counts when a later resend or chunk fails in tryAppendBatch. - Drop the test-only appendChunk and appendChunkWithRotationBudget wrappers and point those tests directly at appendChunkRows. - Add unit tests for prior RowErrors counts with Unwrap and multi-pass unconfirmed-row reporting. * fix(agentanalytics): gate RowErrors on nil AppendResult and tighten control sanitization --------- Co-authored-by: Jan Wojtas <[email protected]>
…s, and empty error messages (#2047) (#2178) * fix(agentanalytics): align checkpoint gating, MCP isError tool results, and empty error messages (#2047) - Read reserved AGENT_STATE_CHECKPOINT keys directly from ev.CustomMetadata (guarded by shouldLogSessionEvent) without requiring CustomMetadataAllowlist, while keeping attributes.custom_metadata allowlist-filtered and computing content truncation directly via jsonColumn/smartTruncate. - Classify top-level boolean true isError and is_error tool result maps as TOOL_ERROR with message "Tool returned an MCP result with isError=true." before noteTaskFinished, TOOL_COMPLETED, and FinalResponseToolNames AGENT_RESPONSE. - Fall back to fmt.Sprintf("%T", err) in logToolError when err.Error() is empty so TOOL_ERROR rows never write NULL error_message. Part of #2014 Closes #2047 * fix(agentanalytics): deduplicate recovered MCP tool errors and preserve checkpoint metadata truncation * fix(agentanalytics): reject tool result errors before finish_task completion Classify MCP tool result errors before finish_task bookkeeping in afterTool, and exclude classified tool result errors from isTaskCompletedResult and hasTaskCompletedResponse so mixed sentinel and error-flag responses emit TOOL_ERROR without recording task completion or emitting AGENT_COMPLETED. * fix(agentanalytics): record unreadable tool errors and failed finish_task activations - Read tool error messages through orZero in logToolError, so an error whose Error method panics, such as a typed nil pointer to a type with a value receiver Error method, records its type name instead of losing the TOOL_ERROR row when a later plugin answers the error with an isError result. - End a task-mode activation on every finish_task response that carries the completion sentinel, as ADK does, and write AGENT_ERROR instead of AGENT_COMPLETED when the response is also a classified tool result error. Failed finish_task calls are noted apart from completed ones, so runs that reuse a call ID each end their own activation; calls that fail without the sentinel, such as validation errors, are not noted. - Describe classifyToolResultError and eventData.customMetadataTruncated as they behave today. Related: #2047 * test(agentanalytics): keep test-only finish_task helpers in tests and range over ints - Move isTaskCompletedResult and hasTaskCompletedResponse into the tests, their only callers since afterTool and OnEventCallback use taskEndResult and taskEndResponse. - Use range-over-int loops for the two task activations in the finish_task runner tests. Related: #2047 * fix(agentanalytics): scrub checkpoint state, guard confirmation errors, and preserve finish_task attribution --------- Co-authored-by: Jan Wojtas <[email protected]>
…utine (#2379) * fix(agentanalytics): scope lookalike parent resolution to active goroutine Scope lookalike parent resolution in parentForRunLocked to the active or starter goroutine via excludePeerLookalikesLocked and runningLookalikeLocked, fall back to enclosingOpenSpanLocked across intermediate non-callback goroutines (including when a candidate sits under an unmatched multi-lookalike ancestor), avoid mutating or aliasing the caller's exclude map in parentForRunLocked, and preserve ParallelWorker retry purging across enclosing-span demotion. * fix(agentanalytics): collapse non-concurrent lookalikes and make parent lookup sub-quadratic - Index inv.agentStack into an O(N) open-span Euler-tour tree (openSpanTree) so ancestor, subtree-exclusion, enclosingOpenSpanLocked, and workflow-lookalike scheduler checks run in O(N) total time even under deep non-group ancestor chains. - Condense lookalike group dependencies via iterative Tarjan SCC before min-heap Kahn topological sorting (with first-occurrence tie-breaking) across two priority tiers (live goid match before origin.parent starter match), ensuring outer cyclic ancestor SCCs resolve strictly before downstream inner groups. - Precompute per-node deepest enclosing goid and starter ancestors (deepestGoidAnc, deepestStarterAnc) in one O(N) pass so Pass 2 starter resolution and ancM active-scope narrowing scope strictly to the active enclosing subtree (ignoring later siblings or unrelated branches sharing goid) and pickWinner never lets out-of-scope outer witnesses shadow valid in-scope starter matches. - Share excludeLosers across both passes, ensuring direct matchGoid winners still exclude cross-goroutine inner peers even when an inline child frame shares the winner's goroutine, and scope unmatched lookalike records to bm/ancM only when a non-direct winner matches via a descendant subtree. - Maintain subtree witness maxima lazily via an iterative max-segment tree (maxSegTree) whenever an earlier group excludes a witness node, keeping multi-group resolution O(N log N) worst-case (O(N + G log G) when no witness is excluded mid-pass). - Filter superseded same-goroutine activations before Euler-interval ancestor collapsing in countEffectivePeers so nested superseded peers do not mask live concurrent siblings, store all live scoped members in unmatched for parent-chain ambiguity detection and enclosingOpenSpanLocked scoping, and re-collapse surviving non-concurrent pairs in the post-exclusion filter. - Deduplicate unmatched group slices across the entire parent ancestor chain in parentForRunLocked's ambiguity loop so narrower outer unmatched ancestors cannot overwrite wider-scope inner unmatched lookalikes. - Remove the redundant runningLookalikeLocked pass from parentForRunLocked and reuse parentForRunLocked in pushAgentSpan when nothing was purged. - Document on Config that an unclosed prior activation on a different goroutine cannot be distinguished from a live peer across an intermediate goroutine. - Update the laterAttempt doc comment and retry test comment, tighten the ParallelWorker retry test to reject the already-closed workflow span, and add regression, invariant, and scaling benchmark tests (100/1k/10k). * fix(agentanalytics): address lookalike parent review feedback --------- Co-authored-by: Jan Wojtas <[email protected]>
#2250) * fix(agentanalytics): redact compound and state-prefixed sensitive keys Redact compound key names (such as DB_PASSWORD, GITHUB_TOKEN, dbPassword, and spring.datasource.password) and session state prefixes (user:, app:, temp:, and stacked forms like user:temp:access_token) consistently across structured JSON values, STATE_DELTA entries, URL query parameters, nested YAML/text blocks, and prose-embedded key-value or JSON snippets. Keep non-credential names and pagination cursors (page_token, next_page_token, prev_page_token, token_count, secretName, api_key_id, exchangedAuthCredential) unredacted while preserving linear-time matching, monotonicity, and fail-closed handling on truncated or unparseable JSON. * fix(agentanalytics): handle nested, cursor, idempotent, and dotted keys Address follow-up review feedback on compound and state-prefixed sensitive key redaction: - Handle nested bare, quoted, padded, and container-valued sensitive keys under quoted compound and state outer keys in redactJSONKeyValues without leaving the inner credential in clear, keep quoteScanState spans interval-bounded so backward re-scans and nested-key rewinds never hit stale unclosed marks, prevent punctuation-joined bare/bracketed values from consuming a following sensitive key, and require compound nested keys on a new line to start at the line's key token rather than after a value prefix (e.g. s3cr3t/dbPassword). - Preserve line breaks inside quoted JSON keys, allow "{" in "temp:" keys, fold dotted capital I (U+0130) alongside U+017F and U+212A, and match word-boundary transitions into non-ASCII folded start runes (such as xſecret=...). - Exempt sync, continuation, next, prev, previous, and pad token cursors (sync_token, continuation_token, syncToken, continuationToken, NextToken, nextSyncToken, next_token, pad_token) while keeping fb_page_token sensitive, keep URL path-segment pair redaction scoped to exact sensitive keys so route slugs like /account/reset-password/confirm stay intact, and skip bare path-prefixed dotted filename segments before ":" so Go *os.PathError text (e.g. open /etc/ssl/private.key: no such file or directory) is preserved. - Treat already-redacted placeholder values after quoted sensitive keys as idempotent on second pass while keeping fail-closed boundaries on suffixed or truncated inputs, match dotted exact sensitive key names, align scanner doc comments, and add a generated differential test comparing the scanners against the reference regular expressions. * fix(agentanalytics): close nested key leaks and keep main redactions Address review findings on compound, state-prefixed, and nested key redaction, and keep every value that the regular expressions on main removed out of the output: - Add a legacy-pattern backstop to scrubErrorText. legacyScrubErrorTokens redoes the header, bearer, basic, quoted JSON, and key-value expressions of main, including their nested-key handling and their RE2 case folding (U+017F and U+212A, and word boundaries read as ASCII-only), with linear-time matchers, and compoundLegacyScrubErrorTokens does the same for every key that isSensitiveKey accepts. leavesLegacyValue fails the text closed to [REDACTED_SENSITIVE_TEXT] when the scanners keep a word that either one redacts, or when either one would fail the text closed through hasBackslashEscapedCredentialWith while the scanners keep a word of it. Only the key of a redacted pair (redactedKeyBytes: the name after the last path separator unless the whole name is a key, a quoted name within one token, and keys of [REDACTED_SENSITIVE_URI] too) and the rest of the value token that a placeholder starts (wordsAfterPlaceholder) do not count, so redacted text stays stable. Against the expressions on main, a compound or "temp:" name within a line counts only for the fixed key at its end (exemptKeyStart, fixedKeySuffixStart), so words before it that a header line redacted still count, while a name at the start of a line, after an opening quote that may be escaped by one backslash (startsLineAt), counts as a whole. Only [REDACTED] and [REDACTED_SENSITIVE_URI], the placeholders of redacted values, start such a value token, and its words count again, also in text that the scrub leaves as it is, when their run holds any ":" or "=" whose value is not such a placeholder as a whole, or ends in a key whose delimiter follows after whitespace (dropGluedBeforeUnredactedPair, hasUnredactedPairIn, isRedactedPairValueAt): the placeholder may follow spaces or tabs and one quote, which may be escaped, but no line break, and its value must end with the text or the line, a value stop or closing punctuation, or another pair after spaces, and for an Authorization or API-key header with the line (endsRedactedValueAt, isHeaderKeyBefore). So password: [REDACTED]SECRET[api_key: v, password: [REDACTED]/SECRET/api_key:v,other=[REDACTED], and password: [REDACTED]SECRET/api_key: [REDACTED] v fail closed, as do runs into an empty quoted string, a value on the next line, [BINARY DATA], or text in or glued to the quotes of a placeholder. knownSentinelLenAt reads up to maxKnownSentinelLen, the length of the longest of knownSentinels. - Check each decoded URI component as scrubErrorText checks text (redactURIComponent, scrubURIComponentText): rerun the scrub until it stops changing, check escapes, and run the legacy-pattern backstop, without exempting words glued to a placeholder, as the check of the whole text reads the component escaped; a URI in a component is never parsed again, so the work stays linear. So file URIs that FormatContentParts formats on their own are checked as error text is. The legacy scrubs read URI components as main did (legacyRedactURIComponent through sanitizeURIWith and scrubURITokensWith), on the decoded component, in which a "+" of a query is a space. sanitizeQueryPairs reads a query key with each "+" as a space, as url.QueryUnescape does, and also counts a key that ends in a sensitive key name, possibly before delimiter whitespace, after a byte that no key name holds, as the text scrub of an error message reads it (endsInSensitiveTextKey), so that FormatContentParts redacts ?+token=SECRET, ?token+=SECRET, ?my+token=SECRET, and ?my+token%09=SECRET as it redacts ?%20token=SECRET, while ?a+b=c stays; the legacy scrubs still read keys as main did (decodeQueryKeys). - Count text that the legacy expressions would change as a credential marker in malformed JSON text (legacyScrubChanges), as on main, so that "{" or "["-led text with a header whose value starts on the next line fails closed. - Run redactErrorMessage, sanitizeRawText, scrubErrorText, and SmartTruncate string values (redactStringValue) to a fixed point (maxRedactionPasses = 4, failing closed beyond that); a changed text that does not start with "{", "[", or a quote is a fixed point of scrubErrorText and needs no further pass. Read text that starts with a redacted URI as text. Fail quote-led text closed to [UNPARSEABLE_JSON_BLOB] when it has a quoted sensitive key and malformed members (hasMalformedQuotedMembers: a string glued to a word, adjacent strings unless a complete "[REDACTED]" follows a string that ends in a delimiter, "," and a quote of any kind after any value, a quote after a placeholder, unquoted or in quotes, other than the quoted value of an unquoted key, or an unquoted placeholder as the value of a quoted sensitive key and ":"), which isBalancedAlreadyRedactedProse, which also rejects escaped quotes, no longer accepts as redacted prose; a "[REDACTED]" counts as a container opener while a quoted sensitive key keeps an unredacted value. - Keep the line break of multiline Authorization and API-key header values (authHeaderLineBreak), continue quoted header values past escaped line breaks (authHeaderValueEnd), and redact a header value up to the fixed key at the end of a trailing nested key whose value starts on the next line (nestedKeyBeforeNextLine, including padded quoted keys that are fixed keys as a whole); the key-value passes keep that pair's line break (headerLineBreak), so fields after the value stay. A quoted compound or "temp:" key, or a name that ends in no fixed key, leaves the whole line to the header redaction. - Read a quoted value that ends in a sensitive key at any boundary that findTextKeyStart accepts as a nested key (quotedValueEndsInKey), also past maxNestedKeyLen; a key closed by a dangling quote before a delimiter (danglingQuoteKeyAt, over budget also when its quoted or container value runs past the scanned value, valueEndsPast, which skips a quoted string or container that closes inside it, so that a container that closes at the end of the text is read once rather than again from each dangling key quote nested in it, which took quadratic time; such a quote never opens a string that pairs with a later quote); a quoted string whose closing quote opens a quoted member of a container that opens in it (opensContainerMember, containerMemberOpener, quotedContainerOpeners, isQuotedMemberAt, quotedMemberEnd: a key that may span lines and hold control bytes, as the strings that the container scans skip may, followed by ":" or "=", or, in an array, a string followed by "," or "]", after the opener or a "," and any delimiter whitespace, line breaks and vertical tabs included, or the quoted value of an unquoted key, with quotes that may be escaped and hold inner escaped quotes, skipping brackets inside inner quoted strings and caching closed quotes and container spans in quoteScanState so repeated stray-quote checks stay linear), which is not skipped as a whole, also when the value seems to end at a space or "," before that quote (strayQuoteOuter) or when a spanning quote encloses delimited containers that hold a member in other quotes at any depth, also after a delimiter right after the opening quote and with any delimiter whitespace, such as a vertical tab, around the members, between the containers, which a "," may also separate, or before the closing quote (enclosesMixedQuoteContainer, scanMixedQuoteContainers, isTripleEscapedMemberAt, isQuotedMemberValueAt, memberFlagsAt), and under maxNestedKeyLen, where a container after a delimiter that is still open at the end of the value is redacted with it; isRegexpSpace, the \s of the regular expressions, stays only where a scan must agree with them; a quoted value whose closing quote opens a nested value (quotedValueRealEnd, also for a nested value in a container tail); stray quotes after keys; and stolen or path-joined dangling keys after a quote ends. A line-start name whose prefix holds a non-ASCII space or control character only ends in a key name, and a padded quoted key at the start of a line is a nested key whatever its quote and delimiter. - Require every other ":" or "=" in a redacted over-budget tail to be followed by a placeholder (hasUnredactedDelimiter), redact path-prefixed ".key" pairs after a container value, drop the Go *os.PathError ".key" exception when a quoted or container value is glued to the colon (isPathErrorColon), redact the next string when a key ends one string (isQuoteGapBeforeNextString), and fail quote-led key text with an unbalanced quote closed (isUnbalancedQuotedKeyText). - Scope isPathPrefixedDottedKey (isDottedKeyFilename, isPathErrorOpBefore) to dotted ".key" file names after a path separator or a Go file-operation verb, keep malformed "{" and "[" JSON strict in the quoted-key checks, unify container and spanning-quote scanning in classifyNestedKey and classifyOverBudgetNestedKey, and check nonCredentialSegments after case folding. - Keep the backstop linear and cheap: scrubErrorText remembers the scrubs its checks repeat (scrubMemo), mayMatchTextPatterns folds the text as it reads it, a character at a time, and the escape checks copy runs of bytes at once. - Bound the container scans of each quoteScanState (scanOpenersInSpan, scanTripleEscapedQuoteEnd, enclosesMixedQuoteContainer, and scanMixedQuoteContainers) to max(8*len(s), 8192) bytes (openerScanBudgetMultiplier, minOpenerScanBudget, consumeOpenerBudget). JSON-escaped runs of escaped quotes next to \' or ' and [ kept each check of a quoted string, made from inside it, from reusing the scans cached for that string, so every check scanned the rest of the text again and 224 KiB took seconds. Once the budget runs out, the value runs to the end of the text and redactJSONKeyValues and redactTextKeyValues fail the whole text closed to [REDACTED_SENSITIVE_TEXT], so the work stays linear and no value is kept. innerContinuesIntoGluedToken, which reads the text before each ":" or "=" of a quoted string glued to the word after it, charges those reads to the same budget and finds the last text-value stop once, so many delimiters in such a string stay linear. - End a glued value in extendGluedValueEnd where hasGluedSuffixAfterQuotedValue ends a quoted one: before the closing quote of a string that encloses the pair, a ":" followed by whitespace, or an escaped whitespace sequence, so that msg: "DB_PASSWORD: x"S0/creds:{ 'k': 'v'}"" for user "bob" keeps for user "bob". - Redact the containers that a quoted string encloses after a ":" or "=" in it when the string seems to close inside them (spacedStrayQuoteContainer, enclosedContainerRun): at a member in the same quote, as in DB_PASSWORD: x": {'msg': "it's ok", 'k': 'SECRET'}", the repr Python gives a dict that holds a string with an apostrophe, or DB_PASSWORD: x": [1, "SECRET"]"; at that quote in a member in other quotes, as in DB_PASSWORD: x": {'msg': 'say "hi"', 'k': 'SECRET'}", whether whitespace follows the delimiter or not; or in the first of several containers separated by whitespace or a ",", as in DB_PASSWORD: x": {'a': "1"} {'b': 'SECRET'}" or DB_PASSWORD: x": {'a': "1"}, {'b': 'SECRET'}", also when the string seems to close at a member of a container that opens in the value (strayQuoteOuter). Containers right after the quote, possibly after delimiter whitespace, as in DB_PASSWORD: x"{'msg': 'say " hi"', 'k': 'SECRET'}" or DB_PASSWORD: x"{'k': 'SECRET'}", count too, and so do containers after other text in the string, as in DB_PASSWORD: x"prefix {'a': '1', 'k': 'SECRET'}" (spacedStrayQuoteContainer, behind the gate of a quoted value below, and enclosesMixedQuoteContainer, through mixedQuoteContainersCached and, from the first container on, mixedQuoteContainersAfterText). The containers are redacted with the value, within the nested-key budget and past it, when they close and the same quote closes the string right after the last one, possibly after delimiter whitespace such as a vertical tab and the ")" of groups around them, as in DB_PASSWORD: x"({'k': 'SECRET'})" (skipGroupClosers); containers that stay open, that the string does not close right after, that the string seems to close after, or that a "," follows with no container after it keep the text after the value. A sensitive value that is such a string itself, in quotes that may be escaped, as in DB_PASSWORD: "{'msg': 'say "hi"', 'k': 'SECRET'}", DB_PASSWORD: '{"msg": "it's ok", "k": "SECRET"}', DB_PASSWORD: "{'a': "1"} {'b': 'SECRET'}", DB_PASSWORD: "{'msg': 'say "hi"'}, {'b': 'SECRET'}" or DB_PASSWORD: "S0/x: {'msg': 'say "hi"', 'k': 'SECRET'}", runs on to the quote that closes the string after the containers (quotedValueRealEnd, quotedValueContainerRun), within the nested-key budget and past it and in a JSON member: from the outermost container open where the string seems to close, when that quote opens a member of a container or a part of one after a "(", a "+", or another string (quotedContainerOpeners), or when the quote comes inside a member of a container that opens in the string, after any text, a "(" or a backslash, which escapes only a quote or a backslash (closingQuoteInMember), as in DB_PASSWORD: "prefix {'a': 'say " hi', 'k': 'SECRET'}", DB_PASSWORD: "({'a': 'say " hi', 'k': 'SECRET'})", or DB_PASSWORD: "\{'a': 'say " hi', 'k': 'SECRET'}", or else from a container right after the opening quote or after a ":" or "=" in the string, when a token is glued to that quote. The quote comes inside a member when it is inside a string in other quotes that opens a member, also after a "(", or a part of one after a "+" or another string, and closes past the quote, as the " hi" of DB_PASSWORD: "{'msg': 'say " hi"', 'k': 'SECRET'}", of DB_PASSWORD: "{'a': ('say " hi'), 'k': 'SECRET'}" or of DB_PASSWORD: "{'a': 'x' + 'say " hi', 'k': 'SECRET'}" (opensMemberAfter, closedString), or where a member or such a part starts, also right after a string prefix, the quote opening a string that may hold a line break, as in DB_PASSWORD: "{'a': " 1\n2", 'k': 'SECRET'}", DB_PASSWORD: "{'k': b" SECRET", 'm': 'SECRET'}" or DB_PASSWORD: "{'a': 'x' b" SECRET", 'k': 'v'}", either string followed by ",", ":", "=", "}", "]", or ")", a "+", or another string, with or without a prefix, or, right after its closing quote, by a subscript or an attribute (memberStringEnds). So a value such as "{abc", "{", or "{'a': 'x" that a stop follows is not scanned. These scans are charged to the opener scan budget, so that repeated unclosed containers stay linear and 224 KiB of them fail closed. - Read a quote after a Python string prefix that is a whole word (b, r, u, or f, or br, rb, fr, or rf, in either case) as opening a string in the container scans (scanMixedQuoteContainers, scanOpenersInSpan, closingQuoteInMember) when that string closes, also past a line break, before a ",", ":", "=", "}", "]", or ")", a "+", or another string, or right before a subscript or an attribute, as in b'x}y'[0] or b'x}y'.decode() (isStringPrefixQuote, stringPrefixStart, memberStringEnds), charging what it reads to the scan budget, so that a bracket in it closes no container, as in DB_PASSWORD: x"S0/creds:{b: b'x}SECRET'}", DB_PASSWORD: x"S0/creds:{'a': b'x}SECRET'.decode(), 'b': '1'}", DB_PASSWORD: "{'a': b'x}\nSECRET', 'b': 'say " hi"', 'c': 'SECRET'}", the (b'x}y'), b'x}y' + 'z', or b'x}y' 'z' of DB_PASSWORD: "{'a': (b'x}y'), 'b': 'say " hi"', 'c': 'SECRET'}", or a Python 2 repr such as {u'k': u'x}SECRET'}; a closing quote right after such a prefix where a member or a part of one starts reads that member from the byte before the prefix (closingQuoteInMember, quotedContainerOpeners); other quotes joined to a word, as in it's, don't, Plan B's budget, or Plan B's.txt, still open no string. - Go on past a quote in a value whose string no check places, as the apostrophe of DB_PASSWORD: user's": {'msg': "it's ok", 'k': 'SECRET'}" or the ' of DB_PASSWORD: a'x": {'a': "1", 'b': 'SECRET'}", within the nested-key budget and past it, so that a later quote that opens the string around a container is still read. Only a later quote is read, since the string of such a quote may enclose the rest of the value: a container that no stray quote leads to, as in DB_PASSWORD: x"S0/creds:{a: it's}" other=ok, ends the scan and keeps the text after the value. - Split redaction.go into redaction.go (entry points and JSON text), redaction_keys.go, redaction_uri.go, redaction_scanners.go, redaction_nested.go, and redaction_backstop.go, and drop nestedPairEnd, which only a test called; it calls nestedPairEndWithState. - Add TestCompoundKeyDifferentialAndIdempotencyRegressions, TestCompoundKeyReviewLeakRegressions, TestLegacyPatternBackstop, TestLegacyRegexCompositeParity, TestAdversarialScaling, and, in redaction_regression_test.go, TestCompoundKeyMemberListHeaderAndBackstopRegressions, TestBarePlaceholderHeaderCompoundAndContainerRegressions, TestGluedPlaceholderBeforeUnredactedPair, TestOverBudgetDanglingKeyQuoteRegressions, TestEscapedQuoteLineStartKeys, TestAdversarialScalingDanglingKeyQuoteShapes, TestLegacyPatternBackstopOnUnchangedText, TestStrayQuoteContainersUnderBudget, TestQuotedContainerMembersWithAnyBytes, TestPaddedLineStartQuotedKeys, TestGluedPlaceholderBeforeAnyUnredactedPair, TestURIComponentsCheckedAsText, TestKnownSentinelLengths, TestAdversarialScalingContainerGluedAndURIShapes, whose nested containers close at the end of the text with quotes that pair up, TestGluedPlaceholderBeforeUnredactedValues, TestSpacedAndMixedContainerMembers, TestPlusPaddedQueryKeys, TestAdversarialScalingSpacedContainersAndRedactedValues, TestEscapedMemberQuotesAndOppositeQuoteContainerBrackets, TestDelimSpaceTrimmedQueryKeys, TestMixedQuoteContainerMembersAndBoundaries, TestExtendGluedValueEndOuterQuoteBoundaries, TestOpenerScanBudgetLinearScaling, TestOpenerScanBudget, TestSpacedStrayQuoteContainers, TestSpacedStrayQuoteAfterApostropheOrOtherQuote, TestSpacedStrayQuoteContainerRuns, TestOpenerScanBudgetGluedTokenKeys, TestValueEndingInsideEnclosedContainers, TestMixedQuoteContainersAfterControlSpace, TestValueEndingInsideEnclosedContainersBeforeStops, TestMixedQuoteMembersAfterControlSpace, TestMixedQuoteContainersWithStringPrefixes, TestClosingQuoteAfterStringPrefix, TestContainersRightAfterStrayQuote, TestStrayQuoteContainerMembersWithControlBytes, TestPrefixedStringsInParenthesesAndConcatenations, TestConcatenatedStringsInEnclosedContainers, TestContainersAfterTextGroupsAndBackslashes, TestPrefixedStringsWithSubscriptsAndAttributes, and focused tests of the member-list, placeholder, nested-header, exemption, container-value, case-folding, and SmartTruncate fixed-point rules, and linearRatio, which alternates the runs it times and re-measures a scaling ratio above its limit, at last with the runs timed alone, before failing. The redaction tests run in parallel with each other (runInParallel, with scalingMu letting such a re-measurement run while no other redaction test does), and under the race detector, which slows these single-goroutine scans by more than ten times, the linear-scaling checks compare a quarter of the units and run 32 KiB rather than 224 KiB texts (scalingUnits, largeTextLen), while every other check, and every text that must run the scan budget out, stays as it is, so that the package runs well within the default test timeout. SmartTruncate now fails {"msg":"password=..."} closed, as its second pass did, while sanitizeRawText keeps its result, and a redacted chain that runs into an Authorization or API-key header whose value holds a word glued to its placeholder fails closed. * fix(agentanalytics): check main parity by byte span and align URIs Address review of the backstop, the nested-key scans, URI rewrites and JSON values: - Compare by byte span. Each pass of the scanners and of the legacy expressions writes through a spanWriter that can record which runs of its output it copied from its input; the legacy passes also record the spans they remove (a value, a header value, a credential). Composing the runs maps every kept byte back to the input, so leavesLegacyValue fails the text closed when the scrub keeps any byte that the legacy expressions remove, punctuation and words spelled like keys included, instead of comparing word spellings. Only whitespace, a placeholder that stands as a whole value in the input, and the name, quotes and delimiter of a sensitive key whose value the scrub redacts are exempt. The word comparison and its glued-placeholder exemptions are gone. The legacy scrub reads the keys of a URI as main did (legacyURIKeys). - Align a URI that sanitizeURIWith rewrites with the text part by part (uriAligner): the scheme, the authority, each path segment, and the key and the value of each query and fragment pair, reading escapes and "+" as the bytes they stand for. A byte that url.URL.String escapes, as the ^ of a path that it writes as %5E, maps to the byte it stands for, so a byte after the URI that equals a hex digit of such an escape no longer pulls the alignment past the fragment or query that the rewrite keeps, and the backstop sees what main redacted there. A search never leaves its part and reads at most a budget linear in both texts, so runs of rewritten pairs and paths of escaped bytes stay linear; past the budget the trace is unaligned and the text fails closed. The rewrite records the bytes it does not keep as removed, so a credential that the legacy scrub removes from a URI component counts against the scrub. - A URI key that reads as sensitive is scrubbed as text too, as main scrubbed a key that it did not read as sensitive, also when its value is redacted already: ?Bearer+SECRET+token=v becomes ?Bearer+%5BREDACTED%5D+token=%5BREDACTED%5D. - One scrubErrorText remembers what the scrubs of URI components return (componentScrub), as its checks read the same components again. - A placeholder glued to other text is no whole value: classifyNestedKey no longer treats a leading [REDACTED] with bytes after it as an already-redacted chain, so the value is redacted with the pair it runs into. password: [REDACTED]hunter2ZQ/token: [REDACTED] now becomes password:[REDACTED], with or without text after it. - A value past maxNestedKeyLen is redacted as a value again; only a value that ends in, or is followed by, a delimiter with a value after it takes that value too (classifyOverBudgetNestedKey). extendGluedValueEnd moves past each value it reads and charges it to the scan budget, so runs of glued pairs such as "token":"x"/ repeated stay linear. - A key name on a line of its own is a nested key, kept with the words before its key, only where main read it so (mainReadsNestedKey): not a path that holds a backslash, as C:\ssl\password, nor a path before a key that main did not have, as /etc/ssl/secret_key. main redacted such a name as the value of the pair on the line above, and so does the scrub now, with the value of the pair that the name starts; the backstop no longer exempts the words before the key of such a name. A path before a key of main, as /etc/ssl/password, stays a nested key. - Drop the scans of containers inside quoted values (repr and mixed-quote members, string prefixes, concatenation, stray-quote containers) and the over-budget dangling-quote scans. The byte-span check fails such text closed where main removes more; shapes that main also keeps are left for a follow-up. - JSON values keep their structure. SmartTruncate redacts a string that is a JSON object or array, or a JSON string literal that holds one, leaf by leaf, as redactErrorMessage does, which reads such a string literal that way too; a string leaf that is JSON text is redacted leaf by leaf as well; and sanitizeRawText does the same for a document that a pass of its text scrub would leave as [UNPARSEABLE_JSON_BLOB], or whose leaves are redacted already. A string leaf that starts with a redacted URI and that the passes redacted already is kept. A document whose text scrub reads a credential across its strings (a header value that runs on into the next string, a key with a credential in it) goes through the text passes as on main (leavesScrubApart), and a JSON string literal whose document fails closed there fails closed as a whole. - leavesScrubApart reads each key and string as the text spells it, not only decoded: the decoded {"a":"Authorization:\n","b":"SECRET"} ends the header at a line break, while main scrubs the escape \n, past which the header value runs on into SECRET. Each string is read with a sentinel after it, spaced and compact, decoded with scrubErrorText, and JSON-encoded, with "<", ">" and "&" as they are and as json.Marshal escapes them, with the expressions of main, which read the run-on that the decoded string hides; for a document in a string or in a JSON string literal the encoded text is encoded again for the outermost text and the one inside it. A sensitive key may run on into the placeholder of its value but not past it. The expressions of main are also applied to the document as it is, at every level of JSON text in its strings (expressionsKeepStringsApart): nothing they remove may hold the start of another value, as when a quote opened in one string closes in a later one, or a quote is spelled \u0022. The document before the leaves are redacted is checked that way too, as written and as the redaction of its sensitive keys writes it again, which main scrubs when it redacts a key there, with an escape such as \u003a written as the byte it stands for: a leaf that the redaction replaces may run on into the next in such text. - expressionsKeepStringsApart also reads the document as main read it before it failed text closed (escapedReadings): with its \uXXXX, \xXX, percent and escaped-quote escapes decoded, and with its backslash escapes decoded as many times as they nest, each reading mapped back to the bytes of the document. What the expressions remove from such a reading may hold no first or last byte of a value that they keep as written, but for both of one value that the leaves redact anyway, the value of a sensitive key, and for a bare value that ends at the closing quote of its string; a quote that an escape opens and the closing quote of its string closes counts where the expressions as written keep part of the value. So ["Bearer '","SECRET","\u0027"], ["Authorization%3A x\t","SECRET"], {"temp%3aa":"SECRET"} and {"m":"access_token=%22a;key=SECRET;token=c"} go through the text passes and fail closed wherever main failed them closed. - The redaction of sensitive keys fails a JSON document closed where the expressions of main read one of its values across strings in the text as written, or with its keys sorted, as main writes it again once it redacts a key (keyRedactionHidesRunOn): the redaction may take a header that main keeps in the value of a compound key, or write the document again with other strings after that value, and keep a string that main redacts with it. - eos_token, bos_token, unk_token, cls_token, sep_token and mask_token are not sensitive, as pad_token is not. Tests: TestRedactionBaseParity runs testdata/redaction_base_corpus.json, 739 inputs with the outputs of the five entry points at the merge base, and checks that no planted secret occurs more often than there. TestGluedPlaceholderBeforeUnredactedValues now expects the glued word to be redacted, and covers the review reproducers and bytes of every kind glued to placeholders. New tests cover URI keys that hold a credential, the alignment of rewritten URIs and its budget, rewritten URI pairs and escaped paths at 16, 64 and 224 KiB, JSON values that stay valid JSON, JSON leaves in SmartTruncate, JSON strings read as the text spells them and the checks behind leavesScrubApart with their scaling, documents whose escapes, decoded, read a credential across strings, the decoded readings against the decoders of the scrub, key names on a line of their own after a path, tokenizer names, runs of glued pairs at 224 KiB, URI keys as on main, and the trace invariants. A wall-clock check of the redaction tests that its first run exceeds times the runs again while no other redaction test runs (withinWallClock), and the check of long backslash runs compares texts 16 times apart rather than one text against a fixed limit. Tests of the removed container and chain handling are removed, and rows whose secret main also keeps are dropped. * fix(agentanalytics): scrub JSON string values as text and bound rewrite growth Address review of the leaf-by-leaf JSON preservation path: - Defer leaf-by-leaf JSON preservation to a follow-up. Remove redactJSONDocumentText, redactJSONDocumentLeaves, scrubJSONDocumentLeaves, leavesScrubApartFrom, endsApart, and encodedEndsApart so JSON documents in string values, JSON string literals, and nested string leaves go through redactJSONTextWithBudget and scrubErrorText as on main, without consuming a speculative node budget pass before the fallback. - Record closeEnd on jsonValueSpan in appendValueSpans as the end of the outer-text source span of a value's closing quote, including when spelled as an escape such as \" inside a JSON string literal, and check v.end == e.pos && to <= v.closeEnd in keepsValueEdge so a decoded credential ending at an escaped closing quote is not skipped when a raw match already covers e.pos. - Bound the output size of re-marshaled JSON values in redactJSONTextWithBudget and sortedJSONTextDepth with rewritesTooLong (maxRewriteGrowth*len(in) + maxRewriteSlack, capped at maxInspectableJSONTextBytes) before keyRedactionHidesRunOn, propagate rewriteExceeded when a child value trips rewritesTooLong, share a single nodeBudget across recursive sortedJSONTextDepth calls, and run keyRedactionHidesRunOn once at the actual outermost JSON value (!inContainer, setting inContainer = true on entering any outer quote-led literal or container rather than deferring past single-leaf wrappers, plus expressionsKeepStringsApart on inner containers with hex/percent escapes). - In redactJSONTextInner, for quote-led JSON string literals followed by a non-empty suffix, fail closed when scrubErrorText returns a non-quote or placeholder result, check literalRunsIntoSuffix across raw and escape-decoded readings so inner key redaction cannot hide a cross-boundary run-on into the suffix, and re-check the marshaled candidate at the same depth with a fresh pass budget (guarded by allowCandidateRecheck) and scrubErrorText so a second pass is a fixed point with stable contentLost. - Ensure maxSanitizeNodes truncation in redactJSONValueInner shrinks maps and slices strictly (deleting the last inserted map key or replacing/popping the last slice element when placing [SANITIZE_BUDGET_EXCEEDED]) and set settled = !lost in sanitizeRawTextOnce and redactStringValueOnce (and !strChanged && !valLost / scrubbed == redacted in redactErrorMessageOnce) so Pass 2 never re-hits the budget or drifts. - Keep positively harmless malformed JSON text in redactStringValueOnce, as sanitizeRawTextOnce does, while checking !hasJSONEscapedCredential and !(quote-led && startsLikeEncodedContainer) in isPositivelyHarmlessProse and decoding \u0130, \u017f, \u212a, and \uXXXX Unicode whitespace in canonicalizeCredentialMarker and canonicalizeMapped so escaped case-folded or whitespace-padded credential keys fail closed. - Update the redactURIComponent doc comment in redaction_uri.go to refer to the byte-span backstop (leavesLegacyValue), add the 56 review and parity reproducer cases to testdata/redaction_base_corpus.json (795 cases total), and add TestJSONDocumentsScrubbedAsText, TestNestedJSONTextDepthScaling, and TestOuterRunOnBudgetIdempotencyAndCandidateRecheck. * fix(agentanalytics): fold Unicode spaces in prose checks and stabilize scaling tests - Fold non-ASCII Unicode whitespace, U+FEFF (BOM), and line/paragraph separators to ASCII whitespace via foldUnicodeSpaces (and decode \ufeff in isFoldedEscapeRune) in isPositivelyHarmlessProse and hasAnyCredentialMarker so malformed JSON and quote-led blobs carrying literal or \uXXXX-escaped Unicode spaces, BOMs, or line separators (such as U+00A0, U+2000, U+3000, U+FEFF, U+0085, U+2028, and U+2029) around credential delimiters, schemes, or multiline quotes fail closed to [UNPARSEABLE_JSON_BLOB], restoring main behavior in SmartTruncate while preserving benign Unicode-space prose. - Update the keyRedactionHidesRunOn comment in redaction.go to reference sortedJSONTextDepth. - Drop nested t.Parallel() calls inside TestOuterRunOnBudgetIdempotencyAndCandidateRecheck (running the node-budget boundary checks via a bounded WaitGroup while holding the parent test slot) so -parallel=2 cannot deadlock against withinWallClock or linearRatio exclusive scalingMu retries. - Replace absolute wall-clock bounds on the 12- and 15-level subtests of TestNestedJSONTextDepthScaling with equal-length 1-level vs multi-level linearRatio checks, and add regression cases for Unicode-space/BOM/line-break credential blobs and malformed or Pass-2-invalidated JSON string leaves. * fix(agentanalytics): preserve legacy backstop escapes, fold vtab/percent spaces, and tune depth scaling - Keep merge-base ASCII-only escape decoding (r <= 0x7F via canonicalizeLegacyCredentialMarker) in the legacy parity backstop (exposesLegacyEncodedPattern, hasLegacyBackslashEscapedCredentialWith, legacyRedactURIComponentWith, legacyURIKeys, and compoundLegacyURIKeys) so BOM/Unicode-space/case-fold decoding in canonicalizeCredentialMarker does not disable URI backstop checks (e.g. {"s":"https\\ufeff://h/a;Bearer+SECRETZQ+token=x"}). - Fold ASCII vertical tab (\v / U+000B) and percent-encoded UTF-8 whitespace/BOM/line-separator sequences (such as %C2%A0 and %EF%BB%BF via parsePercentUTF8SpaceAt) in foldUnicodeSpaces for isPositivelyHarmlessProse and hasAnyCredentialMarker, keeping benign prose intact while failing malformed blobs closed across SmartTruncate and sibling entry points. - Trim BOM and whitespace with trimBOMAndSpace in isSensitiveKey so BOM-padded keys (e.g. {"password\ufeff":"SECRET"}) are recognized as sensitive. - Relax the 15-level equal-length depth-scaling bound in TestNestedJSONTextDepthScaling from 8x to 64x, add a fixed-depth growing-payload check and a 24x 12-level 49k-int array-leaf check (preserving outer-only keyRedactionHidesRunOn), add the escaped-scheme BOM case to redaction_base_corpus.json (796 cases), pin quoted sensitive key space-folding checks, and align the 49,997..50,001 boundary comment. * fix(agentanalytics): preserve overlapping URI path redaction, harden prose exemption, and tune 12-level array scaling - Keep redactNext armed in sanitizePathSegments when the consumed segment is itself a sensitive path segment (e.g. /secret_key/password/SECRET123, /signing_key/token/SECRET123, /user:temp:a/password/SECRET123, and Unicode/escape-padded names such as /%5Cu00a0api_key/password/SECRET123 or /api_%5Cu212aey/password/SECRET123), compute fromLegacy via canonicalizeLegacyCredentialMarker(rawSeg) rather than expanded canonicalization, and trim BOM/space consistently in isSensitivePathSegment, closing file-part content_parts[].uri leaks through sanitizeURI and FormatContentParts. - Tighten isPositivelyHarmlessProse and hasAnyCredentialMarker (via hasSteppedCredentialMarker, hasCredentialPatternsAtStep, hasDirectCredentialPattern, decodeCredentialEscapes, hasIncompleteCredentialConstruct, and parsePercentStatusAt) to run bounded unescapeCredentialStep passes (up to 2*maxCanonicalUnescapePasses, breaking early when unchanged) with foldUnicodeSpaces and single-pass O(N) full escape decoding (\uXXXX including UTF-16 surrogate pairs, \xXX, and %XX) so non-ASCII escapes (\u2014, \u3010, \ud83d\ude00, %E2%80%94, \x94) restore true word boundaries around credential markers in malformed/truncated JSON; reject incomplete, closed quoted/backticked Basic credentials (when non-empty and not [REDACTED]), glued credentials after closed empty or [REDACTED] quotes/backticks on both Bearer and Basic schemes (via isIncompleteClosedQuotedAuthScheme and isRedactedPlaceholderBoundary), text glued after a bare placeholder of an earlier pass in any letter case (Bearer [REDACTED]'SECRET, Bearer [REDACTED])SECRET, Basic [REDACTED]dXNlcjpwYXNz, Basic [redacted]dXNlcjpwYXNz, or Bearer [REDACTED_SENSITIVE_TEXT]'SECRET via isGluedPlaceholderAt and endsAtPlaceholderBoundary), truncated unpadded Basic base64 runs (len%4 != 0 or malformed/excess padding via hasTruncatedBasicBase64At and isLikelyBasicCredentialBytes), and non-isRegexpSpace ASCII control separators (raw, \b/\v JSON escapes, and %XX via percentValidControl) in hasAuthSchemeIncompleteOrObfuscated; fold Unicode Cf zero-width/format separators (literal, \uXXXX, and percent-encoded via isFoldedEscapeRune and foldUnicodeSpaces); skip ASCII control separators (r <= 0x20 || r == 0x7f) and Unicode Cf runes in followedByKeyDelimiterWithRedacted and check hasCandidateQuotedSensitiveKeyWithRedacted across stepped/decoded candidates so control- or Cf-separated quoted temp: keys fail closed; read an escaped backtick after Bearer or Basic as a backtick (isIncompleteBacktickAuthValue) and decode it for these checks only (unescapeProseBackslashes, also on each decoding that hasDirectCredentialPattern checks), keeping main's escapes in the scrub and its legacy backstop; and add hasObfuscatedKeyDelimiter, one linear scan that steps back from each ":" or "=", no further than the one before it, over spaces, controls, JSON whitespace escapes, Unicode spaces and format runes, percent escapes, and quotes and backticks with their backslashes (keyDelimiterRunStart; isPercentSepByte rejects backticks as well as quotes, so no percent escape takes a closing backtick), and rejects a sensitive key before that run, which the scanners do not read, when the run holds a quote, a backtick or a percent byte that hides what it stands for (percentRunKinds), whether the key is a text key (findTextKeyStart), a quoted key that the first quote of the run closes (closesQuotedKey, which finds its opening quote however many quotes follow), or a temp: key whose body is empty or made of the run, with or without a percent byte (`password`: SECRET, password "=SECRET, "msg:\npassword "=SECRET, "a, password ": SECRET, \`msg: password \`%ZZ=SECRET, `temp: %`%ZZ=SECRET, `temp:a,b%`%ZZ=SECRET, temp: =SECRET, temp:=SECRET, temp: %ZZ=SECRET, password'%ZZ=SECRET, "client_secret"'%ZZ:SECRET), letting through only a run of quotes, or an empty temp: key, before a whole [REDACTED] placeholder, across SmartTruncate, function-response part_attributes, FormatContentParts, sanitizeRawText, and redactErrorMessage. - Read a stacked bare temp: key (temp:a:b, user:temp:a:b, quoted or not) on the line after a sensitive key as a value that ends in a key name, as main did, so password:\n temp:SECRET123:x: bar becomes password:[REDACTED] rather than keeping SECRET123 as part of a nested key name. - Treat start/newStart before a cursor word, resume as a cursor word, and eot as a tokenizer name in isPageTokenKey, so startPageToken, newStartPageToken, resumeToken and eot_token stay as on main while startToken and resumePageToken stay redacted; document the matching (".", compound names, stacked user:/app: prefixes, exempt cursor and tokenizer names, adk-python exact names) on Config.DisableSensitiveKeyRedaction, and list redactStringValue at maxRedactionPasses. - Raise the 12-level 49k-int array-leaf depth-scaling bound in TestNestedJSONTextDepthScaling from 24x to 64x for non-race timing headroom while still catching per-level exponential blowup, and build the large-text entry points with the subtest's t there and in TestOuterRunOnBudgetIdempotencyAndCandidateRecheck. - Add 357 real f2dc5d3 merge-base parity cases (1,153 cases, 5,765 outputs) in testdata/redaction_base_corpus.json, list the bytes the base removes as the secret of the 26 existing cases that the base changes but that listed none (punctuation-only values, glued pairs, URI query values), fail TestRedactionBaseParity when such a case lists no secret, and add regression, FileData URI, FunctionResponse part_attributes, and anti-ReDoS linear-scaling tests. * fix(agentanalytics): fail closed on escaped control key delimiters and over-budget Basic credentials - Replace percentRunKinds with delimiterRunKinds in redaction.go so hasObfuscatedKeyDelimiter flags any escaped control/whitespace separator (\b, \t, \n, \r, \f, \v with any number of preceding backslashes) or non-ASCII space/format rune inside the run that keyDelimiterRunStart steps over before ":" or "=". - Trim trailing and leading escaped control/whitespace runs in closesQuotedKey (via trimQuotedKeyEdges and trimLeadingQuotedKeyControls) before control-escape folding runs, and refactor unescapeBackslashes with backslashUnescapeMode (backslashControlsLegacy, backslashProseStructural, backslashProseAll) plus controlEscapeByte so unescapeProseStructural / unescapeProseStructuralStep preserves all six control letters (\b, \f, \n, \r, \t, \v) while decoding \/, \", \', \` and collapsing \\+ runs before control folding (unescapeProseBackslashes / unescapeProseCredentialStep) in both hasIncompleteCredentialConstruct and hasSteppedCredentialMarker. This keeps C:\{b,f,n,r,t,v}... prefixes before token, temp:, Bearer, Basic, and {b,f,n,r,t,v}- prefixed sensitive keys (such as t_page_token, bPageToken, t_eos_token, t_next_token, v_page_token, vPageToken, vXToken) intact alongside \u/\x/%/quote/backtick canonicalization while preserving main's escape semantics in scrubErrorText and the legacy backstop (unescapeBackslashControls). - Update hasTruncatedBasicBase64At to scan the full contiguous isBase64Byte run up to maxBasicCredentialBytes+1 in O(1), return true when over budget, and inspect =-separated segments (plus an =-stripped fallback) for in-budget glued or mid-quantum padded Basic credentials. - Update helper assertions in TestHarmlessProseRejectsIncompleteAndObfuscatedCredentials, add scaling cases in TestIncompleteCredentialConstructLinearScaling, and add TestEscapedControlKeyDelimitersAndOversizedBasicFailClosed covering SmartTruncate, FunctionResponse part_attributes, sanitizeRawText, and redactErrorMessage across limits -1 and 4096. * fix(agentanalytics): fail closed on malformed JSON text as main does and redact credential containers whole SmartTruncate, and the function-response part_attributes that go through it, kept a string that starts with "{" or "[" and is no JSON document whenever a list of detectors found no credential in it. Each detector covered the shapes reported against it, so text such as [INFO] Bearer'SECRET or [INFO] password<U+FE0F>=SECRET came back unchanged where main returns [UNPARSEABLE_JSON_BLOB]. Allowances of the same kind read text that came with a placeholder as text that was redacted already, in every entry point: {"a":"[REDACTED_SENSITIVE_URI] Bearer'SECRET"} and "password=[REDACTED]" SECRET kept what main fails closed. The keep rule now goes by where text comes from, not by what it looks like: - Text as it is received fails closed wherever it does on main. No part of it is read as redacted already, and SmartTruncate keeps no malformed JSON text at all. sanitizeRawText and redactErrorMessage keep malformed JSON text that is prose, as main does. - Only the result of an earlier pass of the same call is read as redacted text (redactJSONTextPass), so that the passes of a call still settle on what main returns for a document whose scrub takes a closing quote, as {"log": "x-api-key: SECRET\nrequest id: 42"}. A new call reads redacted text as it reads any other text: redacted text that is JSON-like and no longer parses fails closed, as on main. With the exemption gone, the detectors that guarded it are removed, about 900 lines. That also gives back the text that they flagged with no credential in it, as [INFO] Basic mode=Okta or [INFO] Plan: Basic 'monthly', and the time that they took on large text. Also: - A sensitive key that holds an object or an array no longer fails the whole document closed. appendValueSpans reads the container as the one value that the redaction replaces, so that {"Credentials":{...},"Message":"ok"} is {"Credentials":"[REDACTED]","Message":"ok"} again, as on main. - After a double-quoted key that main read, a value on the next line that only ends in a sensitive key name, as the QZX7193-authorization of "authorization":\nQZX7193-authorization =8, is redacted with the value of that key, as main removed it, instead of being kept as the name of a nested key. - scrubURITokens finds the URIs of a text from each "://" rather than by running an expression from every letter (uriTokenSpans). That expression took most of the time spent on large text without credentials. - The comment of Config.DisableSensitiveKeyRedaction says that the "." and compound-name matching does not apply to URI path segments. Tests: TestSmartTruncateMalformedJSONTextFailsClosed, TestMalformedJSONProseKeptAsOnMain, TestSensitiveKeyContainerValuesKeepDocument, TestSmartTruncateSecondCallOnRedactedText, TestJSONLiteralBeforeTextScrubbedAfterRedaction, TestQuotedKeyPastInspectedPrefixCountsAsMarker, TestURIPathSegmentsMatchKeyNamesOnly, TestURITokenSpansMatchExpression and TestLargeMalformedJSONProseScaling are new. The tests of the removed detectors are removed, and the tests that asserted that a second call returns redacted malformed JSON text unchanged now assert what main returns for it. The parity corpus gains 126 cases recorded from the merge base. * fix(agentanalytics): address JSON container, URI padding, and scanner scaling review feedback * fix(agentanalytics): remove redactJSONValue left unused after merging main The custom-metadata scrub from #2178 no longer calls it, so lint reports it as unused. Point the two doc references at redactJSONValuePass. --------- Co-authored-by: Jan Wojtas <[email protected]> Co-authored-by: wojtasjan <[email protected]>
* chore(agentanalytics): address #2020 post-merge review nits - Clarify the retireAgentLocked and purgeActivationLocked late-context comments to note that canceled and parent are kept while an open span or call still reaches the record, and remain when the last reaching span is an open tool or model call. - Tighten TestRetiredCallerReadsCause to assert exact AGENT_ERROR rows on both call-1 and call-q ends (preventing duplicate rows or wrong-call attribution) and trim the failure message to what the test directly exercises. Follow-up to #2020. * fix(agentanalytics): tighten TestRetiredCallerReadsCause assertion and refine retirement comments * test(agentanalytics): tighten cause identity check and purge comment --------- Co-authored-by: Jan Wojtas <[email protected]>
… skills (#2390) ListFrontmatters of the file-system source fails on the first skill directory whose SKILL.md does not parse or validate, or names the skill otherwise than its directory. One such directory then fails every listing of the source. NewFileSystemSourceWithConfig takes a FileSystemSourceConfig with an optional OnListInvalidSkill callback, the same as gcsskill's. It is called with the directory name and the error for each invalid skill: returning nil skips the skill and continues, returning an error aborts the listing with it. A SKILL.md that cannot be opened is not offered to it and still fails the listing. NewFileSystemSource and its behavior are unchanged.
…igin across redirects (#1986) * fix(mcptoolset): keep the Config.Auth credential on the endpoint's origin across redirects * fix(mcptoolset): judge a caller CheckRedirect's edits against the pre-hook chain authCheckRedirect ran the origin policy and then returned whatever the caller's CheckRedirect returned. net/http sends the request as that hook leaves it, so a hook that rewrote req.URL and returned nil sent the next hop, credential and JSON-RPC body included, to whatever origin it named. The hook also receives via, so re-running the policy on the live chain is not enough. Take copies of the original and previous URLs before the hook runs and judge the hop it leaves against those. Pin the rest of the policy's contract in TestAuthRedirectPolicy: the policy decides before the hook (a caller returning ErrUseLastResponse on a cross-host hop still gets the refusal), the hook's sentinel reaches net/http unwrapped on an allowed hop, and nothing is installed without Config.Auth. Bound TestAuthRedirectCap's redirect loop so a missing cap fails the hop count instead of hanging the package. Move the hop cap constant into credredirect as MaxRedirects, shared by both callers, prefix mcptoolset's cap error like remoteagent's, unexport sameTarget, and fix the TestSameTarget comment that still referred to end-to-end tests "above" from before the move. * fix(mcptoolset): keep a refused stream redirect from failing the session, and hold Host and Opaque through a caller hook On protocol versions before 2026-07-28 go-sdk opens its optional server-to-client stream with a GET after initialize. An error from client.Do on that GET is retried with growing delays and then fails the session, so a server that redirects the GET elsewhere made every Tools() call fail after about 20 seconds, while an answer that is not text/event-stream only means the server offers no stream. A refused hop on a GET chain now hands net/http the 3xx unfollowed instead of an error. The JSON-RPC traffic is POST and keeps the error. Through an HTTP forward proxy the request target comes from req.Host or an opaque URL rather than from req.URL, so a caller CheckRedirect that set either one sent the credential toward another host with the URL check passing. Both now have to stay as they were before the hook ran. In credredirect, compare the names net/http dials, the IDNA ASCII forms, instead of the written hostnames: ß and ẞ, or ς and σ, case-fold equal but map to different names, and a Unicode name and its punycode form map to the same one. Let the http to https upgrade keep a port that one side writes out and the other implies, which the Config.Auth doc already promised. Add the tests the review asked for: a caller hook that allows a hop, the cap under a caller hook, and the previous-hop comparison under a hook. * fix(credredirect): compare every name net/http derives from the host, and hold the wire target through a caller hook net/http derives two names from a URL's host. It dials the IDNA lookup form, which maps characters before encoding, and it writes the Host header and a forward proxy's request target from the punycode form of the name as written. The previous head compared the lookup form only, so a Location spelling the endpoint's name with a soft hyphen, a fullwidth letter, a long s or ẞ for ss passed while the request carried another Host. A redirect is now the same target only when both names agree. ASCII names are taken as written by both, as net/http does, so an empty punycode label is no longer dropped and a Unicode name still equals its punycode form. Check also refuses a request that would address another host on the wire than its URL names: a Host header for another host or port, an opaque URL, or a path without a leading slash, which a forward proxy turns into another target. That closes the path rewrites a caller CheckRedirect could make after the policy had passed the hop, and it accepts a hook that merely pins req.Host to the URL's host, which the previous head refused. State on Config.Auth what a refused redirect does on the SDK's optional server-to-client stream: the first stream request's 3xx reads as no stream unless it is labeled text/event-stream, and a labeled 3xx or one on a reconnect fails the session with the status text. Pin dialName and hostName each on their own, Check's chain and wire-target rules directly, and the GET-chain refusal after a hook. * fix(mcptoolset): keep the server's Location out of a refused redirect's error, and decide the chain's method before the hook runs net/http wraps a CheckRedirect error in a *url.Error whose URL is the raw Location header, so a refused cross-host 307 to an SSO callback put its code and state into what Tools() returned. The refusal is now a typed error, and withRetry, the one place every session error leaves the toolset, replaces the *url.Error around it with the refusal itself, keeping the message of every layer above. The refusal already names both origins. refuseRedirect read via[0].Method off the slice after the caller's hook had run, so a hook that set it to GET on a POST chain turned the refusal into an unfollowed 3xx. The method is taken before the hook, with the URLs. Pin in remoteagent/v2's own table the decisions that change for the A2A path now that the host comparison is shared, check dialName and hostName against what net/http dials and sends as Host rather than against literals, cover the hostName failure branch, and fix the Check comment's order and the paragraph go doc dropped. The Config.Auth doc now says the bound stops at a supplied Transport and qualifies the stream behavior by protocol version and SDK release. * fix(mcptoolset): keep the Location out of Close and the reconnect log, and compare the Host header net/http writes A refused redirect on the DELETE that closes a session, and on the close a reconnect performs, carried the server's Location through Close() and the "failed to close MCP session" log line. Both now go through the same redaction as a call's error. The redaction keeps every error a rebuilt layer wrapped beside the refusal, so errors.As for the SDK's typed error matches as before. addressesOwnHost parsed req.Host as a URL host, which let a respelling of the endpoint's own name through: brackets around it, a port folded into an IPv6 literal, the default port written out. net/http sends the string as given, so the check now compares the exact Host header net/http would write from the URL with the one it would write from req.Host. Say in refuseRedirect's comment and the Config.Auth doc that the SDK also sends a GET to resume a call's event stream, and what a refused redirect there does. * test(credredirect): check the dial name against net/http instead of a literal TestHostNames expected net/http to dial fass.example for faẞ.example. That is what the IDNA tables of Go 1.26 give. Go 1.27 ships Unicode 17 tables, which map ẞ to ß, so the same name is dialed as xn--fa-hia.example and the row failed for anyone running the suite on 1.27, while CI, on the go.mod version, stayed green. dialName follows net/http on both, which TestHostNamesMatchNetHTTP shows by recording what a real client dials. The table keeps only the Host header name, which does not depend on the mapping tables, and the dial name is left to the net/http test. Removing the ASCII fast path, the lookup profile or the fallback from dialName still fails that test on both releases. Reword the comments that named which spellings share a dial address, since that also follows the Go release, and narrow the claim that a Unicode name equals its punycode form to a name already in its mapped form. * refactor(mcptoolset): strip a call's Location in one place, and cover a redirected reconnect withRetry redacted a refused redirect's Location at four return sites, and no test reached the two on the reconnect path: removing either left the suite green. A call's error now leaves through one deferred redaction, so there is no per-site call to forget. The reconnect's own error is formatted into the message rather than wrapped, so it keeps a redaction of its own. TestAuthRedirectLocationStaysOut gains a reconnect that is itself redirected to another host, which fails without that second redaction, and a call on a session that is already up.
…sks (#2407) Bump github.com/a2aproject/a2a-go/v2 from v2.7.0 to v2.8.0. That release changes the order of Task.History for a task that waits for user input: the agent's input-required message is now recorded before the user's reply to it. Until now it was recorded after the reply, so the history ended with a stale agent question. The set of messages in the history is unchanged, only their order is. Clients that read Task.History by position see the difference. Update the two history expectations in the A2A end-to-end tests to the chronological order.
…updates (#2410) Bumps the go-minor-patch group with 9 updates in the / directory: | Package | From | To | | --- | --- | --- | | [cloud.google.com/go/auth](https://github.com/googleapis/google-cloud-go) | `0.24.1` | `0.24.4` | | [cloud.google.com/go/auth/oauth2adapt](https://github.com/googleapis/google-cloud-go) | `0.3.0` | `0.3.1` | | [github.com/openai/openai-go/v3](https://github.com/openai/openai-go) | `3.91.1` | `3.98.0` | | [golang.org/x/oauth2](https://github.com/golang/oauth2) | `0.37.0` | `0.38.0` | | [golang.org/x/sync](https://github.com/golang/sync) | `0.24.0` | `0.25.0` | | [google.golang.org/api](https://github.com/googleapis/google-api-go-client) | `0.310.0` | `0.312.0` | | [cloud.google.com/go/longrunning](https://github.com/googleapis/google-cloud-go) | `1.4.1` | `1.5.0` | | [golang.org/x/net](https://github.com/golang/net) | `0.61.0` | `0.62.0` | | [golang.org/x/text](https://github.com/golang/text) | `0.43.0` | `0.44.0` | Updates `cloud.google.com/go/auth` from 0.24.1 to 0.24.4 - [Release notes](https://github.com/googleapis/google-cloud-go/releases) - [Changelog](https://github.com/googleapis/google-cloud-go/blob/main/CHANGES.md) - [Commits](googleapis/google-cloud-go@auth/v0.24.1...auth/v0.24.4) Updates `cloud.google.com/go/auth/oauth2adapt` from 0.3.0 to 0.3.1 - [Release notes](https://github.com/googleapis/google-cloud-go/releases) - [Changelog](https://github.com/googleapis/google-cloud-go/blob/main/CHANGES.md) - [Commits](googleapis/google-cloud-go@v0.3.0...ai/v0.3.1) Updates `github.com/openai/openai-go/v3` from 3.91.1 to 3.98.0 - [Release notes](https://github.com/openai/openai-go/releases) - [Changelog](https://github.com/openai/openai-go/blob/main/CHANGELOG.md) - [Commits](openai/openai-go@v3.91.1...v3.98.0) Updates `golang.org/x/oauth2` from 0.37.0 to 0.38.0 - [Commits](golang/oauth2@v0.37.0...v0.38.0) Updates `golang.org/x/sync` from 0.24.0 to 0.25.0 - [Commits](golang/sync@v0.24.0...v0.25.0) Updates `google.golang.org/api` from 0.310.0 to 0.312.0 - [Release notes](https://github.com/googleapis/google-api-go-client/releases) - [Changelog](https://github.com/googleapis/google-api-go-client/blob/main/CHANGES.md) - [Commits](googleapis/google-api-go-client@v0.310.0...v0.312.0) Updates `cloud.google.com/go/longrunning` from 1.4.1 to 1.5.0 - [Release notes](https://github.com/googleapis/google-cloud-go/releases) - [Changelog](https://github.com/googleapis/google-cloud-go/blob/main/documentai/CHANGES.md) - [Commits](googleapis/google-cloud-go@tpu/v1.4.1...kms/v1.5.0) Updates `golang.org/x/net` from 0.61.0 to 0.62.0 - [Commits](golang/net@v0.61.0...v0.62.0) Updates `golang.org/x/text` from 0.43.0 to 0.44.0 - [Release notes](https://github.com/golang/text/releases) - [Commits](golang/text@v0.43.0...v0.44.0) --- updated-dependencies: - dependency-name: cloud.google.com/go/auth dependency-version: 0.24.4 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: go-minor-patch - dependency-name: cloud.google.com/go/auth/oauth2adapt dependency-version: 0.3.1 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: go-minor-patch - dependency-name: github.com/openai/openai-go/v3 dependency-version: 3.98.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: go-minor-patch - dependency-name: golang.org/x/oauth2 dependency-version: 0.38.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: go-minor-patch - dependency-name: golang.org/x/sync dependency-version: 0.25.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: go-minor-patch - dependency-name: google.golang.org/api dependency-version: 0.312.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: go-minor-patch - dependency-name: cloud.google.com/go/longrunning dependency-version: 1.5.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: go-minor-patch - dependency-name: golang.org/x/net dependency-version: 0.62.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: go-minor-patch - dependency-name: golang.org/x/text dependency-version: 0.44.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: go-minor-patch ... Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
With GOOGLE_SDK_GO_LOGGING_LEVEL=debug, ServiceAccount with an Audience wrote the signed assertion and the minted ID token to stderr: the auth library behind idtoken.NewTokenSource logs each token request and response through its default logger. The branch now passes a discarding logger. An explicit JSONKey reaches that library by itself. Default credentials reach it when GOOGLE_API_GO_EXPERIMENTAL_ENABLE_NEW_AUTH_LIB is set. The test covers both. Co-authored-by: Jan Wojtas <[email protected]>
…sessions (#1951) * feat: add Gemini context caching via runner.Config.ContextCache Closes #1937 * fix(model/gemini): settle context caches against stored events Address the review on #1951. The model decided which cache to delete when its response left the model, before callbacks, plugins, the flow and the session write decided what gets stored. A callback filling in an empty reply then left the session naming a deleted cache, and a reply that was never stored deleted the cache the session still named while leaking the new one. Under a runner, each model call now records the caches it created or stopped using in a per-invocation ledger. When the invocation ends, the runner keeps every cache that an agent's latest stored record names and deletes every other tracked cache. Also: - Copy CreateHTTPOptions deeply in the runner and the request processor, so requests share no headers, extra body, timeout or retry options with the caller. - Send a request naming a cache the provider no longer holds again once without it. - Apply the client's ExtrasRequestProvider and the go-genai#931 workaround to cache creation. - Carry CacheMetadata onto callback replacements in inheritModelFields, replacing keepCacheMetadata. - Document context caching in the gemini package doc, and correct the adk-python compatibility note on CacheMetadata. - Add tests for every behavior the review found unpinned. * fix(runner): settle context caches against the stored session Address the second review on #1951. Cleanup judged against the invocation's own session object. The database service adds an event to that object before its write and leaves it there when the write fails, so a rejected reply could still decide which caches are deleted. Cleanup now reads the session as the store holds it, as compaction does. It reads only when a cache was created or replaced, gives up after a bound, and deletes nothing when it cannot read. Also copy maps and slices nested in CreateHTTPOptions.ExtraBody, so a callback writing to them no longer changes the caller's config or later requests, and say "latest stored record" where the docs said "stored records". Tests: the database stale-write case on SQLite, an unreadable and a hung store, no extra read on a turn that only reuses a cache, nested ExtraBody writes, a guard that fails when genai adds an HTTPOptions field the copy does not handle, a stream that fails after output, and the cleanup of a missing cache with and without a ledger. * fix(examples): use errors.AsType in the context cache example --------- Co-authored-by: wolo <[email protected]>
…ssion, v_eval_turn) (#2175) * feat(agentanalytics): add pre-built agent evaluation views (v_eval_session, 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. * fix(agentanalytics): enforce EVENT alias parity in eval view validation 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. * fix(agentanalytics): preserve offloaded user prompts and isolate SyncViews failures * fix(agentanalytics): exclude scalar [FORMATTER_FAILED] from eval view 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]". * fix(agentanalytics): keep offloaded user prompts out of eval-ready turns 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. --------- Co-authored-by: wolo <[email protected]>
…1781) * test(parallelagent): escalate should stop siblings * fix(parallelagent): stop sibling branches when a sub-agent escalates ParallelAgent ignored Actions.Escalate, so every sibling ran to completion after a direct sub-agent asked to exit. It now yields the escalate event and stops, cancelling the remaining branches through the existing cleanup. Only escalations authored by a direct sub-agent count, as in adk-python (agents/parallel_agent.py, _asks_this_agent_to_exit). * fix(parallelagent): keep a sibling's error when a sub-agent escalates An escalation could end the run before the funnel reported a sibling that had already failed, so the caller saw a clean run. When a direct sub-agent escalates after a sibling failure, yield that failure instead, as adk-python does by queueing it ahead of the escalation. Tests: the escalate test no longer depends on a 300 ms timer, checks that the sibling is cancelled and that the escalating branch is never resumed. The nested test gates the sibling on the caller seeing the nested escalation. A new test repeats the failure-then-escalate case 50 times. Doc comment on New describes the escalate behavior. Refs #1781 * fix(parallelagent): record a sub-agent's error as soon as it is yielded The escalate path read errgroup's context cause, which is set only after the failing sub-agent's Run has unwound, and it ignored the cause once the caller had cancelled. A sibling error could be lost if an escalation arrived during the sibling's teardown, or after a caller cancel that came after the failure. runSubAgent now records the first yielded error directly, and the escalate path returns it whenever it is set. The doc comment on New no longer says deeper escalations are handled by their parent workflow (a SequentialAgent does not read Escalate) and says an earlier error is returned instead of the escalate event. Refs #1781 * fix(parallelagent): keep a nested agent's error when a sub-agent escalates Each ParallelAgent now puts a reporter for every sub-agent into that sub-agent's context. When an agent nested below yields an error, the closest ParallelAgent records it and passes it up through the reporters of the enclosing ParallelAgents in the same invocation right away, instead of only when its own errgroup returns. An escalation from a direct sub-agent then finds the error however deep it came from and whether or not the agents in between have finished cleanup. Runs without an escalation are unchanged: the recorded error is only read when a direct sub-agent escalates. * fix(parallelagent): count only nested errors that reach this agent A nested ParallelAgent reported every error up at once, including errors from branches it had canceled after its own escalation and errors that a custom or workflow agent in between catches or retries. Seal the error record when a ParallelAgent ends on an escalation, and report an error up only when the agents in between are SequentialAgents or LoopAgents, which yield a sub-agent's error to their caller as soon as it is yielded. The doc comment on New now says which nesting is covered. Two test comments no longer compare the teardown with a remote agent's cleanup, which detaches from cancellation. * test(parallelagent): cover a LoopAgent between two ParallelAgents Add a loop-then-parallel nesting to the nested error test, so dropping the LoopAgent case from passesErrorsUp fails it, and say in the doc comment that a SequentialAgent or LoopAgent sub-agent's passed-up error counts as a direct sub-agent's error. * fix(parallelagent): follow the agents an error runs through passesErrorsUp walked the declared SubAgents tree, so an agent that ran a nested ParallelAgent itself and caught or retried its error still let that error replace a later escalation whenever the nested agent was also declared as a step of a SequentialAgent or LoopAgent. Replace the walk with an error relay in internal/agent. A ParallelAgent binds the relay to each sub-agent it runs. SequentialAgent and LoopAgent rebind it to each sub-agent they run, since they yield a sub-agent's error to their caller at once. Any other agent leaves it bound to itself, so a ParallelAgent it runs cannot report through it. The doc comment on New and the onErr comment now say the error that replaces an escalation is the first one yielded, which errGroup.Wait may not return when nothing escalates. Tests cover the three shapes from the review, a workflow agent that declares the inner agent, a SequentialAgent inside a LoopAgent between two ParallelAgents, and a sibling failing while the caller handles this agent's own escalation, which fails if the seal moves after the yield. * fix(parallelagent): bind the error relay to agent identity, not name A wrapper that kept the name of a ParallelAgent it ran without declaring it, and caught that agent's error, let the error replace a later escalation, because the relay matched agents by name. Bind the relay to the agent's State, which a wrapper such as the one SequentialAgent returns shares with the agent it wraps. Move the relay to internal/utils next to the graph resume helpers, with InvocationContext and agent parameters, which removes the duplicated helper in SequentialAgent and LoopAgent. Tests cover a same-name wrapper on its own and inside a SequentialAgent, a catcher reaching the inner agent through an undeclared SequentialAgent or LoopAgent, and an error on a LoopAgent's second pass. * fix(parallelagent): pin embedded agents and tighten error comments Add a test that an agent embedding a SequentialAgent does not pass the error relay on, and pin the nil State check in TestErrRelay. Reword the New doc comment and the relay comments to say which error is yielded, what counts, and which agents pass the relay. --------- Co-authored-by: wolo <[email protected]>
…ettled retirement (#2375) * fix(agentanalytics): harden Close/afterRun lifecycle and defer late-settled retirement Make plugin shutdown idempotent with sync.OnceValue. Each Close step runs under its own panic recovery, so a step that panics is reported as an error while the remaining steps still run, and repeated or concurrent Close calls share the one result. Make afterRun always end the invocation trace and flush the run-end batch, even when a callback or Config.Logger panics: endInvocationSafe and flushRunEndSafe run as separate deferred steps, recordPanic counts the dropped row before it logs, and forceEndInvocation keeps the completed-run bookkeeping when endInvocation panics. Release traceManager locks with deferred unlocks on the run-end path, unlink a finished invocation before its open calls are handed over to late state, and defer retireLateSettledLocked across the pop*Span methods so that early returns still retire settled late activations, while rejected or no-op pops leave them untouched. * fix(agentanalytics): tighten afterRun fallback ordering, handover, and late retirement - Run endInvocationSafe immediately after the terminal logEvent in afterRun (before flushRunEndSafe) while keeping the deferred fallback for earlier panics, and bind run-end completion/retry to the original invocationTrace (runEndTarget) so a late agent starting during flush enters the late state with its own span and latency, and a resumed run starting under the same invocation ID is never ended by the retry. - Prepare and populate the late trace destination before unlinking the active trace or clearing its call maps in rememberCompletedAtLocked, reusing known trace and root span IDs without calling the UUID generator so a failed allocation leaves open model and tool calls intact. - Publish saved evicted identities directly in forceEndInvocation without allocating a throwaway invocationTrace or calling the UUID generator, deleting the evicted entry cleanly even when ID generation fails. - Format recovered panic types into strings before calling recordPanic at the plugin's callback, afterRun, and Close panic-recovery sites so Logger implementations never receive raw panic values in Printf arguments. - Narrow the Close panic-recovery godoc to panics on the calling goroutine, and keep DropStats.AppendFailureDrops wording and TestHalfEndedInvocation t.Fatalf assertion from inline review notes. - Add a fast linear runDone && contextEnded pre-check in retireLateSettledLocked so unmatched late completions skip map allocations and the full retirement scan when no activation is settled. --------- Co-authored-by: Jan Wojtas <[email protected]>
…ause (#2330) * fix(workflow): do not carry a consumed answer over to a node's next pause A node with RerunOnResume that sits on a loop can pause, get an answer, finish, come around again and pause a second time in the same run. scanHistory kept every answer the node ever got, including the one its earlier, finished visit had already used. With one interrupt resolved and one open, inferNodeState took the partial resume case: - ReconstructRunState reported the node as NodePending with the first answer in ResumedInputs, although it was waiting on the second pause. - Sending the first answer again reran the node and returned no error. Workflow.Resume documents ErrNothingToResume for a duplicate answer. - With one interrupt ID for both pauses, Interrupts came back empty. The scan now marks a node's answered interrupts as consumed when the node finishes a visit. A consumed answer is left out of ResumedInputs, so the next pause is reported as NodeWaiting on its own interrupt and a repeated answer to the earlier pause matches nothing. If a later visit raises a consumed ID again, that pause is treated as open until it gets its own answer. An answer whose visit has not finished is handled as before. That covers a partial resume and a node that asks again under the same ID before it finishes. Fixes #2297 * fix(workflow): use up answers only when the activation completed Address review on the first version, which marked a node's answers as consumed as soon as the node emitted output. - Output is not the end of an activation. A re-entry node can emit output and then pause again or fail, and a rerun after that still needs the answers it had. Both cases lost them. - The scheduler now records in history that an activation which used resume responses completed with output. Rehydration consumes answers on that record or on the existing record of a completion without output, and no longer on an output event. History without the record keeps the behavior it had. - The record has its own metadata key. Readers take workflowNodeCompletedKey to mean a completion without output and set the node's output to nil. - An interrupt ID that is raised again drops its earlier answer and its answer count, completed or not. adk-python does the same. - Add table cases for output followed by a second pause, output followed by a failure, a first visit that completed without output and an ID raised again before completion. Add runner tests for the first two. * fix(workflow): keep the completion record when a node loops to itself Address the second review round. - completionEvent read the node's NodeState after its successors were scheduled. A node that routes back to itself is started again or queued by then, so the record of the run that just completed was lost and a used answer carried over to the node's next pause. Under a concurrency cap the queued node was even recorded as failed. handleCompletion now saves the node's state on its nodeRun before it schedules successors, and completionEvent reads that. - collectNodeOutputs forgets an answer when its interrupt ID is raised again, as scanHistory does, so the first answer to the new pause also clears output the node emitted before it. - Narrow the Resume doc on repeated answers, say that the record stands in for per-visit run IDs, and update the analytics plugin comments that said a run with output never gets a completion record. - Add tests for the self loop, the concurrency cap, the record being written only for resumed runs, and the cleared output. --------- Co-authored-by: Jan Wojtas <[email protected]>
…texts (#2401) InjectSessionState accepted only the context ADK passes to an InstructionProvider and returned "unexpected context type" for the agent.Context that callbacks, plugin callbacks and tools receive. Instruction templating now resolves placeholders against a source that provides the state and the artifacts. An invocation provides them through its session, as before, and an agent.Context through ReadonlyState and Artifacts. Both are still read only when a placeholder needs them, and a context without state gets an error for a state placeholder instead of a nil pointer dereference. Fixes #2399 Co-authored-by: Jan Wojtas <[email protected]>
* fix(sequentialagent): complete live-session shutdown * test(sequentialagent): cover close during a sub-agent's RunLive a Close that lands while a sub-agent's RunLive is still running finds no session to close, so setActiveSession has to refuse the session RunLive returns afterwards. the test releases RunLive after Close through the runner and fails if the sequence reads that session's events or leaves it open. --------- Signed-off-by: ZenAlexa <[email protected]> Signed-off-by: Ziming Wang <[email protected]> Co-authored-by: wolo <[email protected]>
* refactor: cleanup codebase * fix issues in plugin analytics --------- Co-authored-by: Jan Wojtas <[email protected]>
* fix(memory): split mixed-script search queries like stored text The in-memory memory service split stored text into Latin and non-Latin runs but not the query, so a Latin word inside Japanese or Chinese query text, such as Python in Pythonについて教えて, never matched. It also lowercased a token before splitting it, so İ, which lowercases to i plus U+0307, left the words i and stanbul for İstanbul. The query now goes through the same word rules as stored text, and only a whole non-ASCII query word may match as a substring. Tokens are split into runs before they are lowercased. This matches adk-python's fix in google/adk-python@e9f9790. Fixes #2398 * test(memory): drop duplicate partial word case --------- Co-authored-by: Jan Wojtas <[email protected]>
…1769) * fix: tolerate nil parts that REST requests write to a session * fix(adkrest): drop null parts when decoding requests * test(adkrest): check that the event graph highlights the tool * fix: log None when every part is nil and test function call args * test(loggingplugin): cover content with no parts --------- Co-authored-by: wolo <[email protected]>
* fix(telemetry): export OTLP metrics on explicit shutdown Let built-in OTLP readers perform the SDK's final export while retaining Google Cloud shutdown suppression and empty-collection filtering. Cover both endpoint forms and mixed exporters with decoded metric payloads, and verify cancellation during the final export. Fixes #2167 * test(telemetry): cover rejected shutdown exports Clarify the configured endpoint assumption and name the reader helper after its shutdown behavior. --------- Co-authored-by: wolo <[email protected]> Co-authored-by: Jan Wojtas <[email protected]>
wojtas000
approved these changes
Nov 19, 2026
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Rebase V3 onto main