Repository navigation
fix(agentanalytics): align checkpoint gating, MCP isError tool results, and empty error messages (#2047) - #2178
Conversation
…s, and empty error messages (google#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 google#2014 Closes google#2047
c709542 to
0b6dce1
Compare
…ve checkpoint metadata truncation
|
Addressed in d3f36b6:
|
…pletion 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.
|
Addressed Review
Verified on a clean |
There was a problem hiding this comment.
Earlier review of a previous revision; the latest notes are in #2178 (review).
|
Updated the PR description linkage from |
wojtas000
left a comment
There was a problem hiding this comment.
One thing needs to change before this merges: logToolError still calls err.Error() without a guard, and on the new isError path that now costs the tool call its only terminal row.
Here is the run that shows it. A function tool returns a typed-nil pointer whose Error() has a value receiver (var e *myErr; return nil, e). A plugin registered after analytics answers the error from OnToolErrorCallback with {"isError": true}. onToolError pops the span and marks the call closed, then err.Error() panics inside writeEvent, which recovers and drops TOOL_ERROR. afterTool then sees closedByError on the isError map and returns without writing anything. On main the same run writes TOOL_COMPLETED. With this PR it writes TOOL_STARTING and nothing after it.
adk-python v2.13.0 guards this exact case in on_tool_error_callback: a message that cannot be read records the type name. Changing line 1300 to cmp.Or(orZero(err.Error), fmt.Sprintf("%T", err)) fixes it. I ran that against the test below and got one TOOL_ERROR row, and the rest of the package's tests stayed green.
Test that reproduces it (run with go test -run TestPanickingErrorWithIsErrorRecovery ./plugin/agentanalytics/)
type valueErr struct{ msg string }
func (e valueErr) Error() string { return e.msg }
func TestPanickingErrorWithIsErrorRecovery(t *testing.T) {
type toolArgs struct {
Query string `json:"query"`
}
p, requests, _ := setupTestPluginWithConfig(t, nil)
recovery, err := baseplugin.New(baseplugin.Config{
Name: "mcp_error_recovery",
OnToolErrorCallback: func(agent.Context, tool.Tool, map[string]any, error) (map[string]any, error) {
return map[string]any{"isError": true}, nil
},
})
if err != nil {
t.Fatal(err)
}
fnTool, err := functiontool.New(
functiontool.Config{Name: "lookup", Description: "fails with a typed-nil error"},
func(agent.Context, toolArgs) (map[string]any, error) {
var e *valueErr
return nil, e
},
)
if err != nil {
t.Fatal(err)
}
bot, err := llmagent.New(llmagent.Config{
Name: "bot",
Tools: []tool.Tool{fnTool},
Model: &scriptedLLM{responses: []*model.LLMResponse{
{Content: &genai.Content{Role: "model", Parts: []*genai.Part{{FunctionCall: &genai.FunctionCall{ID: "c1", Name: "lookup", Args: map[string]any{"query": "x"}}}}}},
{Content: textContent("model", "done"), TurnComplete: true},
}},
})
if err != nil {
t.Fatal(err)
}
for _, runErr := range newTestRunner(t, bot, p, recovery).Run(t.Context(), "u1", "s1", textContent("user", "go"), agent.RunConfig{}) {
if runErr != nil {
t.Fatalf("runner.Run error: %v", runErr)
}
}
rows := collectRows(t, requests, untilInvocationEnd)
if got := len(rowsOfType(rows, EventToolError)) + len(rowsOfType(rows, EventToolCompleted)); got != 1 {
t.Fatalf("got %d terminal tool rows, want 1; events: %v", got, eventTypes(rows))
}
}Must change before merge:
- Guard
err.Error()inlogToolErrorso anError()that panics falls back to the type name, and add a test for that path.
Separately, and not for this PR: ADK Go's own MCP toolset turns CallToolResult.IsError into a Go error that carries the tool's output text. So the new isError rule never fires for mcptoolset tools, and their error_message holds that output. That predates this change and probably deserves its own issue.
…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: google#2047
…ty-matches # Conflicts: # plugin/agentanalytics/bigquery_agent_analytics_plugin.go # plugin/agentanalytics/events.go
… 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: google#2047
|
Thanks for the careful review and the repro. Everything is addressed on the branch, which now ends at
Must-change:
Inline threads
Thanks also for the Verification on the merged head, with a workspace like the one CI uses:
|
There was a problem hiding this comment.
Earlier review of a previous revision; the latest notes are in #2178 (review).
…s, and preserve finish_task attribution
|
Thanks for the thorough review, @caohy1988! Addressed all four items:
|
caohy1988
left a comment
There was a problem hiding this comment.
Thanks for the follow-up. The three stated changes behave as described: checkpoint rows no longer need the allowlist while attributes.custom_metadata still does, only a top-level boolean true is classified as a tool error, and an empty or panicking Error() falls back to the bare type name. Suite, -race, vet, gofmt and tidy are all clean at this head. A few regressions against main still need fixing before this goes in, though, mostly from the switch to sanitizeValue for every retained metadata value in the last commit.
Typed A2A responses skip the app's formatter suppression. events.go:983 now turns a typed a2a:response into a JSON map before ContentFormatter sees it. A formatter that suppresses *genai.Content and passes everything else through now lets the original text reach the content column, and the typed renderer that produced content.text_summary / content_parts is bypassed. Please keep the typed response for formatting and part collection, and use a separately sanitized copy only for the metadata attributes. A test with a formatter that drops *genai.Content and an a2a:response holding typed content passes on main and fails here.
Compaction summaries from typed adk_compaction metadata are lost. extractEventCompaction now reads from the scrubbed map, so it always gets a map[string]any. A non-UTF-8 ThoughtSignature (or inline data) becomes [BINARY_DATA], the genai.Content unmarshal in genaiContentFromMap fails, and compacted_content ends up empty. A struct with its own json tags no longer produces an EVENT_COMPACTION row at all. On main all three cases record text: 'compacted summary'. compactioninternal/summary_event.go copies prose parts whole, so signatures on summary parts can happen in practice. Either keep main's redactJSONValue pass for the shared map and apply sanitizeValue only to the checkpoint state, or use the allowlist just as a gate and format the original value, the way the EventActions.Compaction path already does. Nothing in the suite currently fails if the old loop is restored, so this needs a test either way.
Terminal task rows can land on the wrong activation. Call ownership is only recorded when the plugin already sees the completion sentinel (bigquery_agent_analytics_plugin.go:1265). An agent-level after-tool callback that runs later can add the sentinel or flip the error flag. With two buffered responses using distinct call IDs, the fallback in trace_manager.go:2508 then closes the newer activation, so the completion span IDs get swapped, or AGENT_ERROR goes to the run that succeeded. Main pairs these correctly in the same delivery order. A related problem is that line 943 passes every response ID in the batch, including unrelated sibling tools, which can produce false matches. I'd keep the owning activation for each finish_task attempt until its final response arrives, match only the finish_task response that actually ends the task, and treat unresolved ownership as ambiguous rather than defaulting to the newest run. Reused IDs like call-0 were already ambiguous on main, but this PR now writes a visible AGENT_ERROR on the wrong span in that case. Changing the ID in the existing buffered subtest at bigquery_agent_analytics_plugin_test.go:6081 to a fixed "call-0" shows it.
Worth checking: a retried finish_task closing as failed. If a callback returns the sentinel plus isError for a call with omitted arguments, the runner's pending-call check (llm_agent_wrapper.go:715) doesn't end the task, but analytics records AGENT_ERROR and then drops the later successful completion. The early retirement already exists on main, but the error row is new. It would be good to apply the same pending-call condition before closing the span.
Smaller things:
- A request-only
A2A_INTERACTIONrow no longer setsis_truncatedwhen itsa2a:requestwas scrubbed or replaced with a placeholder.addContentreturns early on nil content before it readscontentTruncated. Restoring main's first pass fixes this, or carry the flag explicitly when content is nil. - The result-based TOOL_ERROR rule, which skips the
FinalResponseToolNamespromotion, and the AGENT_ERROR row for a failedfinish_taskaren't documented indoc.go,config.goor onEventToolError. There's also no way to opt out, unlike the classifier hook upstream. - The
ContentFormatterdocs still describe the payload as the raw value. For checkpoints it's now a scrubbed JSON-shaped copy. - The description still says the fallback is
%T. The code records the bare type name.
Every item in this review is fixed on the current head.
wojtas000
left a comment
There was a problem hiding this comment.
Approving. The logToolError fix holds: a panicking or empty Error() now writes one TOOL_ERROR row.
A few optional notes on the new custom-metadata scrub, none blocking:
is_truncatednow follows scrub loss anywhere in the event. A request-only A2A_INTERACTION whosea2a:requestholds a Bearer string getsfalsewhere main writestrue, and a compaction event (the summary that replaces older history) with an unrelateda2a:credential getstrue. Tying it to what each row writes would be more accurate.- An allowlisted legacy
adk_compactionsummary with an InlineData or ThoughtSignature part is written as an empty string. ADK's own compaction doesn't produce that shape. - Nothing tests the scrub switch: going back to the per-key scrub leaves the package green. A case showing that
ContentFormattergets redacted values would pin it. - The description still names
fmt.Sprintf("%T", err)as the fallback.
… main The custom-metadata scrub from google#2178 no longer calls it, so lint reports it as unused. Point the two doc references at redactJSONValuePass.
#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]>
* ci: run the Go workflow on pushes to the v3 branch (#2363) * fix(llminternal): answer unknown tool calls the way adk-python does (#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. * chore(main): release 2.8.0 (#2138) * fix(live): send tracking headers on live connections (#2369) 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]> * fix(agentanalytics): preserve retired late parent cancel cause and custom 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 (#2305) * 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]> * fix(loggingplugin): truncate text by character, not byte (#2342) 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]> * fix(runner): skip nil parts in response events and input blob extraction (#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]> * fix(llminternal): accept Unicode identifier characters in instruction 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]> * fix(telemetry): leave no span processor running when New fails (#2318) 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]> * fix(agentanalytics): redact and bound code part labels in summaries (#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 (#2324) * 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]> * feat(tool/skilltoolset/skill/gcsskill): add Cloud Storage skill source (#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. * fix(agentanalytics): match an error-ended tool call to its own attempt (#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 (#2378) * 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. * fix(agentanalytics): isolate BigQuery RowErrors and track RowErrorDrops (#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]> * fix(agentanalytics): align checkpoint gating, MCP isError tool results, 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]> * fix(agentanalytics): scope lookalike parent resolution to active goroutine (#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]> * fix(agentanalytics): redact compound and state-prefixed sensitive keys (#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, concatenat…
Linked issue
Summary
Implements three
adk-python v2.13.0parity match items tracked in #2047 (and #2014):AGENT_STATE_CHECKPOINTEmission WithoutCustomMetadataAllowlist:AGENT_STATE_CHECKPOINTwheneverEvent.CustomMetadatacarriesadk_agent_state/agent_stateorend_of_agent/adk_end_of_agent, independent of whetherConfig.CustomMetadataAllowlistis set, while continuing to gateattributes.custom_metadataprojection onCustomMetadataAllowlist.AGENT_STATE_CHECKPOINTrows on theis_truncatedrule that fix(agentanalytics): preserve retired late parent cancel cause and custom metadata truncation flag #2020 landed onmainfor every session-event row:is_truncated=trueonly when an entry of the projected, allowlistedcustom_metadatalost data during scrubbing, not for unallowlisted keys or keys kept only for theira2a:prefix.isError/is_errorTool Result Classification:result["isError"] == trueandresult["is_error"] == trueinafterTool(requiring strict booleantrue) and classifies matching tool responses asEventToolError(status = "ERROR",error_message = "Tool returned an MCP result with isError=true."), honoringclosedByErrorto avoid duplicateTOOL_ERRORrows when an error-recovery callback returns an MCP error map.TOOL_COMPLETEDandFinalResponseToolNamesAGENT_RESPONSEpromotion. Afinish_taskresult that fails without the completion sentinel (anisErrormap, or a validation error) does not end the task and is not recorded as a task completion."result": "Task completed."sentinel alone, so afinish_taskresult that carries the sentinel together withisError/is_errorstill ends the activation. That activation now gets anAGENT_ERRORrow (error_message = "finish_task ended the task with a tool result error: Tool returned an MCP result with isError=true.") instead ofAGENT_COMPLETED, so it keeps a terminal row. Failed and completedfinish_taskcalls are tracked separately, so two runs of the same task agent that reuse a call ID each end their own activation.error_messageFallback for Tool Errors:cmp.Or(orZero(err.Error), fmt.Sprintf("%T", err))inlogToolError, so a GoerrorwhoseError()returns""or panics (such as a typed nil pointer to a type with a value-receiverError()) records its type name, andTOOL_ERRORrows never record aNULL/ emptyerror_messageor get dropped. adk-python records the type name for an exception message it cannot read in the same way.Behavior change
adk_agent_state/agent_stateorend_of_agent/adk_end_of_agentinCustomMetadatanow emitAGENT_STATE_CHECKPOINTby default without listing those keys inCustomMetadataAllowlist(callers can opt out viaEventDenylist: []string{agentanalytics.EventAgentStateCheckpoint}).isError: trueoris_error: truenow logTOOL_ERROR("Tool returned an MCP result with isError=true.") instead ofTOOL_COMPLETED. When such a map is afinish_taskresult that also carries"result": "Task completed.", the task activation that ADK ends on it getsAGENT_ERRORinstead ofAGENT_COMPLETED.Error()returns""or panics now record their Go type name (fmt.Sprintf("%T", err)) inerror_messageinstead ofNULL, or instead of losing theTOOL_ERRORrow.Testing Plan
-racetests pass locally (go test -race -count=1 ./plugin/agentanalytics/...and.github/scripts/apidiff.sh origin/main).custom_metadatatruncation reporting:TestSessionEvents_EmitRichLifecycleTypes,TestCustomMetadataAllowlist_GatingOnLifecycleEvents, andTestAgentStateCheckpoint_RetainedCustomMetadataTruncation(alongsideTestCustomMetadataScrubLossSetsIsTruncatedfrom fix(agentanalytics): preserve retired late parent cancel cause and custom metadata truncation flag #2020)isError/is_errorclassification,finish_taskerror precedence,AGENT_ERRORfor a task ended by a failedfinish_task, validation-errorfinish_taskresults not recorded as completions, &closedByErrorrecovery deduplication:TestPlugin_ToolResultIsErrorandTestMCPRecoverySingleToolErrorerr.Error()type-name fallback:TestPlugin_ToolErrorEmptyMessageandTestPanickingErrorWithIsErrorRecovery