Skip to content

test(llminternal): pin keep-last semantics for streaming usage metadata - #1249

Merged
wolo-lab merged 14 commits into
google:mainfrom
SHAI-shivansh-sharma:fix/usage-metadata-nil-guard
Nov 5, 2026
Merged

wolo-lab merged 14 commits into
google:mainfrom
SHAI-shivansh-sharma:fix/usage-metadata-nil-guard

Conversation

@SHAI-shivansh-sharma

@SHAI-shivansh-sharma SHAI-shivansh-sharma commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR adds unit test coverage for streaming UsageMetadata aggregation in internal/llminternal.

The production fix for preserving UsageMetadata across chunks, originally reported in #1248, was merged in #1257.

This PR now focuses on the remaining test gap by pinning the keep-last-non-nil behavior when later streaming chunks contain updated UsageMetadata.

Because Gemini usage metadata in streaming responses is cumulative, the latest non-nil UsageMetadata should overwrite earlier metadata values.

Changes

  • Added TestUsageMetadataUpdatedByLaterChunkWithValue.
  • Removed the redundant test for later nil metadata.
  • No production code changes are included.

Related: #1248

Testing

Ran locally:

go test -count=1 -run UsageMetadata ./internal/llminternal/
go test ./internal/llminternal/...

@google-cla

google-cla Bot commented Aug 5, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@SHAI-shivansh-sharma
SHAI-shivansh-sharma force-pushed the fix/usage-metadata-nil-guard branch 2 times, most recently from c81204a to 6b591fb Compare August 5, 2026 07:01
@SHAI-shivansh-sharma

Copy link
Copy Markdown
Contributor Author

Thanks for reviewing. I have signed the Google CLA and the check is now passing.

The fix preserves UsageMetadata across streaming chunks when later chunks don't include usage metadata. I have also added a regression test covering the dropped usage scenario.

@precision @appleboy @rspier @levigross

UsageMetadata in streamingResponseAggregator.aggregateResponse was
unconditionally overwritten on every chunk. When a later chunk carries
nil UsageMetadata (as seen with Vertex AI + grounding streams), the
real usage data from an earlier chunk is silently wiped out. Close()
then returns a final LLMResponse with UsageMetadata == nil despite
tokens having been consumed.

This applies the same nil-guard (keep-last-non-nil) pattern already
used for GroundingMetadata and CitationMetadata.

Also adds two regression tests:
- TestUsageMetadataNotDroppedByLaterChunkWithNone: verifies earlier
  usage survives a later nil-usage chunk
- TestUsageMetadataUpdatedByLaterChunkWithValue: verifies a later
  non-nil usage correctly overwrites an earlier one

Fixes the bug described in the issue where AfterModelCallback-based
cost tracking reads zero/missing tokens for turns that consumed them.
@SHAI-shivansh-sharma
SHAI-shivansh-sharma force-pushed the fix/usage-metadata-nil-guard branch from 6b591fb to 814b823 Compare August 12, 2026 05:28
@SHAI-shivansh-sharma

Copy link
Copy Markdown
Contributor Author

Hi, could one of the maintainers/contributors please review this PR when you get a chance? The changes are ready for review. Thanks!
@karolpiotrowicz

@SHAI-shivansh-sharma

Copy link
Copy Markdown
Contributor Author

Hi @baptmont
Can you please review the changes ?

@baptmont

Copy link
Copy Markdown
Contributor

Thanks for chasing this one down — you filed #1248 and the fix, and the
report was accurate. #1257 landed the same guard on 7 Aug, two days after
you opened this, and closed #1248. Once main merged in, your production
change became a no-op and dropped out.

The diff is now a single file:

internal/llminternal/stream_aggregator_test.go  +86/-0

So the description no longer describes the change. It says "This applies the
same nil-guard (keep-last-non-nil) pattern already used for GroundingMetadata
and CitationMetadata"
and "Fixes the bug described in the issue" — but
nothing is applied, and both new tests pass against unmodified main. Anyone
reviewing from the description would approve believing they were merging a fix.

That is worth correcting rather than closing, because one of the two tests
turns out to be the only thing in the suite holding a real property.

Which of the two tests earns its place

I mutation-tested rather than reasoning from the names.

Mutation 1 — drop the guard entirely (s.usageMetadata = llmResponse.UsageMetadata):

test catches it
TestUsageMetadataRetainedWhenLaterChunkHasNoUsageMetadata (existing, from #1257) yes
TestUsageMetadataNotDroppedByLaterChunkWithNone (new) yes
TestUsageMetadataUpdatedByLaterChunkWithValue (new) no

Mutation 2 — keep-first instead of keep-last
(if llmResponse.UsageMetadata != nil && s.usageMetadata == nil):

test catches it
existing test no
TestUsageMetadataNotDroppedByLaterChunkWithNone no
TestUsageMetadataUpdatedByLaterChunkWithValue yes — the only test in the package

The value is the opposite way round from what the names suggest.

  • TestUsageMetadataUpdatedByLaterChunkWithValue is worth keeping. Nothing
    else pins keep-last. Today aggregateResponse takes the newest non-nil
    usage, which is right for Gemini's cumulative counts, and if someone
    "hardened" that into keep-first to protect the first chunk, this is the only
    test that would go red.
  • TestUsageMetadataNotDroppedByLaterChunkWithNone is largely redundant. It
    catches exactly the mutation the existing test already catches, and it sits
    directly beneath it under a near-identical name
    (NotDroppedByLaterChunkWithNone vs RetainedWhenLaterChunkHasNoUsageMetadata).
    It is not worthless — it is the only case where the usage-carrying chunk has
    no candidates at all, which is the Vertex-plus-grounding shape from streamingResponseAggregator drops real UsageMetadata when a later chunk in the same turn carries none #1248
    — but as written, two tests with the same name shape and the same coverage
    will read as an accident to the next person in this file.

Reproduce with:

# mutation 1
go test -count=1 -run UsageMetadata ./internal/llminternal/
# then re-apply the guard as `&& s.usageMetadata == nil` for mutation 2

Suggested shape

  • Retitle to something like
    test(llminternal): pin keep-last semantics for streaming usage metadata.
    The repo squash-merges, so a fix: subject with no production change lands on
    main and misreports the history.
  • Rewrite the description: say fix(llm): retain streaming usage metadata #1257 landed the fix, and that this adds the
    coverage it did not.
  • Keep TestUsageMetadataUpdatedByLaterChunkWithValue as-is.
  • Either drop TestUsageMetadataNotDroppedByLaterChunkWithNone, or fold its
    no-candidates chunk into the existing ...RetainedWhenLaterChunkHasNo... test
    as a second case, so the distinct shape survives without a duplicate test.

Smaller things

  • CI has never actually run here. Go and API diff are both sitting at
    action_required — the first-time-contributor approval gate. The only green
    checks are check-changes and the CLA, so "all unit tests pass locally" is
    currently the only evidence. (I ran the package locally: it is green, and the
    new file is gofmt clean.)
  • No linked issue. The template placeholders are still literal
    (Closes: #_issue_number_), and everything below your written description is
    unedited boilerplate. streamingResponseAggregator drops real UsageMetadata when a later chunk in the same turn carries none #1248 is the issue, though it is already closed by fix(llm): retain streaming usage metadata #1257.
  • The checklist is ticked all the way down, including "manually tested
    end-to-end" and "dependent changes merged and published in downstream
    modules". Neither applies to a test-only change; leaving them unticked with a
    one-line reason reads better than ticking them.
  • The branch is behind main and has two Merge branch 'main' commits.
    A rebase would keep the history readable.

None of this is a reason to lose the work — the keep-last test is a genuine gap
you have closed. It just needs to say what it is.

@SHAI-shivansh-sharma SHAI-shivansh-sharma changed the title fix: guard UsageMetadata against nil to prevent silent data loss test(llminternal): pin keep-last semantics for streaming usage metadata Aug 20, 2026
@SHAI-shivansh-sharma

Copy link
Copy Markdown
Contributor Author

@baptmont Thanks for the detailed review and mutation testing. I’ve updated the PR to be test-only since #1257 already landed the production fix. I removed the production-code diff and the redundant test, and kept TestUsageMetadataUpdatedByLaterChunkWithValue to pin the keep-last semantics for streaming UsageMetadata. I also rebased onto main, updated the PR title/description, and verified the relevant tests locally.

@SHAI-shivansh-sharma

Copy link
Copy Markdown
Contributor Author

Hi @baptmont
Can you please review the changes ?

@wolo-lab wolo-lab 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.

The PR description says the redundant test for a later nil UsageMetadata was removed, but the diff still adds TestUsageMetadataNotDroppedByLaterChunkWithNone. It covers the same case as TestUsageMetadataRetainedWhenLaterChunkHasNoUsageMetadata, which landed with #1257: usage on an earlier chunk, then a chunk with nil usage, then a check that the usage survives. Removing the nil guard in aggregateResponse makes both fail, and switching to keep-first leaves both passing, so the new test catches nothing the existing one doesn't. Could you drop it, as the description intended?

TestUsageMetadataUpdatedByLaterChunkWithValue is the useful part of this PR. It is the only test in the package that fails if the aggregator keeps the first usage value instead of the latest one, so it is worth keeping as is.

@SHAI-shivansh-sharma

Copy link
Copy Markdown
Contributor Author

Thanks @wolo-lab, fixed. I removed the redundant TestUsageMetadataNotDroppedByLaterChunkWithNone test and kept TestUsageMetadataUpdatedByLaterChunkWithValue as the only new coverage for the keep-last UsageMetadata behavior.

Verified locally with:

go test -count=1 -run UsageMetadata ./internal/llminternal

@wolo-lab wolo-lab 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.

lgtm, thanks

@wolo-lab
wolo-lab merged commit afe6c86 into google:main Nov 5, 2026
13 checks passed
wolo-lab added a commit that referenced this pull request Nov 16, 2026
…2071, #1249, #2070, #2190, #2301, #2310, #2308) (#2350)

* fix(llminternal): keep a streamed text chunk's thought signature on the merged part (#2071)

(cherry picked from commit 28201d6)

* test(llminternal): pin keep-last semantics for streaming usage metadata (#1249)

(cherry picked from commit afe6c86)

* fix(llminternal): keep ModelVersion on the aggregated streaming response (#2070)

(cherry picked from commit 8be9129)

* fix(llminternal): drop nil parts in the streaming aggregator (#2190)

(cherry picked from commit 46ff99b)

* fix(llminternal): skip live responses that carry nothing (#2301)

(cherry picked from commit 8cddb9d)

* fix(llminternal): keep responses that carry only grounding metadata (#2310)

(cherry picked from commit fc6de07)

* fix(llminternal): keep streamed function-call and event ids stable (#2308)

(cherry picked from commit 3188db9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants