Skip to content

fix(loggingplugin): truncate text by character, not byte - #2342

Merged
wojtas000 merged 4 commits into
google:mainfrom
1AbdullahButt:fix/2341-loggingplugin-utf8
Nov 17, 2026
Merged

wojtas000 merged 4 commits into
google:mainfrom
1AbdullahButt:fix/2341-loggingplugin-utf8

Conversation

@1AbdullahButt

Copy link
Copy Markdown
Contributor

Linked issue

Problem:
loggingplugin shortens text, tool args and the system instruction with byte slices, so a cut inside a multi-byte UTF-8 character logs invalid UTF-8 (text: '日\xe6...').

Solution:
A small truncate helper cuts at a rune count, matching adk-python's text[:max_length] on a str. Used at all three truncation sites.

Behavior change

Logged text that contains non-ASCII characters is now cut after maxLength characters instead of maxLength bytes, so it can be longer in bytes than before and is always valid UTF-8. ASCII output is unchanged.

Testing Plan

Unit Tests:

  • go test -race -count=1 ./plugin/loggingplugin/ passes (golang:1.27.3).

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

TestFormatContentTruncatesByCharacter/multi-byte, .../multi-byte_fits and TestFormatArgsTruncatesByCharacter fail, e.g. formatContent("日本語のテキスト", 4) = "text: '日\xe6...'", want "text: '日本語の...'".

Manual End-to-End (E2E) Tests:

N/A, the plugin only formats log lines; the unit tests call the formatting functions directly. gofmt -l is clean; I did not get a full golangci-lint run to finish locally.

Additional context

This change was written with Claude Code (AI-assisted); I reviewed it before opening.

🤖 Generated with Claude Code

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 google#2341
@wojtas000 wojtas000 self-assigned this Nov 16, 2026

@wojtas000 wojtas000 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving with nits. The new truncate cuts at the same character that adk-python's text[:max_length] cuts at, for text parts, for tool args (which add ...}) and for the 200-character system instruction. ASCII log lines come out exactly as before. A limit of 0 still prints ..., and text that is exactly the limit long gets no marker.

The main gap is the system instruction in beforeModel. It is one of the three places the PR changes, and no test reaches it. If it went back to sysInstruction[:200], every test would still pass. A system instruction of 201 '日' characters would then log 66 whole characters plus stray bytes, where it should log 200 characters plus .... Please add a test with a multi-byte instruction over 200 characters and one exactly 200 characters long. You can capture stdout, or move the formatting into a small helper that returns the string.

The remaining test nits are inline. Since the PR has no description, please add one line saying that only non-ASCII text changes: such lines now hold up to the limit in characters rather than in bytes.

Comment thread plugin/loggingplugin/logging_plugin.go Resolved
@wojtas000
wojtas000 merged commit b388580 into google:main Nov 17, 2026
15 checks passed
jjsasha63 added a commit that referenced this pull request Nov 19, 2026
* 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…
1AbdullahButt added a commit to 1AbdullahButt/personal-site that referenced this pull request Nov 28, 2026
Warm paper background with a serif display face, a real diff from
google/adk-go#2342 in the hero, a dated fix log, and project
screenshots served as resized WebP. Light for everyone; the OG image
and favicon match the new look. Only the serif font is downloaded,
which keeps mobile Lighthouse at 100.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

loggingplugin: truncation splits multi-byte UTF-8 characters

2 participants