Skip to content

fix: preserve Anthropic usage across stream events - #996

Merged
rapids-bot[bot] merged 2 commits into
NVIDIA:mainfrom
mnajafian-nv:fix/preserve-anthropic-stream-usage
Sep 4, 2026
Merged

rapids-bot[bot] merged 2 commits into
NVIDIA:mainfrom
mnajafian-nv:fix/preserve-anthropic-stream-usage

Conversation

@mnajafian-nv

@mnajafian-nv mnajafian-nv commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Preserve Anthropic input and cache token usage when later streaming events contain only partial usage updates.

  • I confirm this contribution is my own work, or I have the right to submit it under this project's license.
  • I searched existing issues and open pull requests, and this does not duplicate existing work.

Details

  • Merge usage fields across Anthropic message_start and message_delta events instead of replacing the complete usage object.
  • Preserve fields omitted from later events while allowing newer cumulative values to replace earlier values.
  • Add regression coverage for prompt, completion, total, cache-read, and cache-write token counts.
  • No public API or configuration changes.

Validation:

  • cargo test -p nemo-relay anthropic_streaming_codec_preserves_usage_across_partial_updates -- --nocapture
  • just test-rust
  • just test-python
  • just test-node
  • just test-go
  • cargo clippy --workspace --all-targets -- -D warnings
  • uv run pre-commit run --all-files

Where should the reviewer start?

Start with AnthropicMessagesStreamingState::observe_usage in crates/core/src/codec/anthropic.rs, followed by anthropic_streaming_codec_preserves_usage_across_partial_updates in crates/core/tests/unit/codec/anthropic_tests.rs.

Related Issues: (use one of the action keywords Closes / Fixes / Resolves / Relates to)

Summary by CodeRabbit

  • Bug Fixes

    • Improved streaming Anthropic usage tracking so usage details from earlier updates are retained when later updates provide only partial information.
    • Ensured prompt, completion, total, and cache token counts remain accurate after streaming responses finish.
  • Tests

    • Added coverage for preserving usage fields across successive streaming updates.

@mnajafian-nv mnajafian-nv self-assigned this Sep 4, 2026
@mnajafian-nv
mnajafian-nv requested a review from a team as a code owner September 4, 2026 22:13
@github-actions github-actions Bot added size:S PR is small Bug issue describes bug; PR fixes bug lang:rust PR changes/introduces Rust code labels Sep 4, 2026
@coderabbitai

coderabbitai Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Enterprise

Run ID: e8fe2240-981d-471f-a0ef-c6e33d89ea57

📥 Commits

Reviewing files that changed from the base of the PR and between 705a35c and 6d523e5.

📒 Files selected for processing (2)
  • crates/core/src/codec/anthropic.rs
  • crates/core/tests/unit/codec/anthropic_tests.rs

Included review availability: Your plan provides up to 12 included reviews per hour; 11 remain after this review.

📜 Recent review details
⏰ Context from checks skipped due to timeout. (44)
  • GitHub Check: Node.js / Package (windows-amd64)
  • GitHub Check: Node.js / Package (linux-musl-amd64)
  • GitHub Check: Node.js / Package (linux-arm64)
  • GitHub Check: Node.js / Package (macos-arm64)
  • GitHub Check: Node.js / Package (linux-amd64)
  • GitHub Check: Node.js / Test (windows-amd64)
  • GitHub Check: Node.js / Package (linux-musl-arm64)
  • GitHub Check: Python / Package (linux-arm64)
  • GitHub Check: Node.js / Package (windows-arm64)
  • GitHub Check: Node.js / Test (linux-arm64)
  • GitHub Check: Rust / Package (windows-amd64)
  • GitHub Check: Rust / Package (windows-arm64)
  • GitHub Check: Node.js / Test (linux-amd64)
  • GitHub Check: Node.js / Test (macos-arm64)
  • GitHub Check: Node.js / Test (windows-arm64)
  • GitHub Check: Rust / Package (linux-musl-arm64)
  • GitHub Check: Rust / Package (linux-musl-amd64)
  • GitHub Check: Rust / Package (linux-arm64)
  • GitHub Check: Rust / Package (linux-amd64)
  • GitHub Check: Python / Package (linux-amd64)
  • GitHub Check: Rust / Test (windows-amd64)
  • GitHub Check: Rust / Test (windows-arm64)
  • GitHub Check: Python / Package (windows-amd64)
  • GitHub Check: Rust / Package (macos-arm64)
  • GitHub Check: Rust / Test (linux-amd64)
  • GitHub Check: Python / Package (linux-musl-arm64)
  • GitHub Check: Python / Package (macos-arm64)
  • GitHub Check: Python / Package (linux-musl-amd64)
  • GitHub Check: Python / Package (windows-arm64)
  • GitHub Check: Rust / Test (macos-arm64)
  • GitHub Check: Python / Test (linux-arm64)
  • GitHub Check: Go / Test (windows-amd64)
  • GitHub Check: Go / Test (linux-amd64)
  • GitHub Check: Rust / Test (linux-arm64)
  • GitHub Check: Go / Test (linux-arm64)
  • GitHub Check: Python / Test (macos-arm64)
  • GitHub Check: Python / Test (linux-amd64)
  • GitHub Check: Check / Run
  • GitHub Check: Python / Test (windows-arm64)
  • GitHub Check: Go / Test (macos-arm64)
  • GitHub Check: Node.js / Package OpenClaw plugin
  • GitHub Check: Go / Test (windows-arm64)
  • GitHub Check: Python / Test (windows-amd64)
  • GitHub Check: Preview docs
🧰 Additional context used
📓 Path-based instructions (29)
Tests should cover the behavior promised by the changed API surface, including error paths and cross-request isolation where relevant.

⚙️ CodeRabbit configuration file

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
Review the Rust runtime for async correctness, scope isolation, middleware ordering, and event lifecycle regressions.

⚙️ CodeRabbit configuration file

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
For changes affecting `crates/core`, `crates/adaptive`, or shared Rust runtime semantics, expand validation to the full binding matrix with `validate-change`.

📄 CodeRabbit inference engine (.agents/skills/test-rust-core/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
If a language surface changed, always run that language's test target even when Rust core did not change.

📄 CodeRabbit inference engine (.agents/skills/validate-change/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
Keep async behavior on the existing tokio-based model.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
[ ] Do all bindings expose the same logical knobs and semantics?

📄 CodeRabbit inference engine (.agents/skills/maintain-observability/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
If any Rust code changed, always run `just test-rust`.

📄 CodeRabbit inference engine (.agents/skills/validate-change/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
**Formatting**: `cargo fmt` (rustfmt defaults) **Linting**: `cargo clippy -- -D warnings` -- all warnings are treated as errors

📄 CodeRabbit inference engine (CONTRIBUTING.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
If any Rust code changed, also run `cargo fmt --all`.

📄 CodeRabbit inference engine (.agents/skills/validate-change/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
Use `Json = serde_json::Value` in Rust-facing runtime APIs where the existing code expects JSON payloads.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
[ ] Branch scope is coherent and reviewable [ ] Relevant tests passed under `validate-change` [ ] Docs and examples updated for any public behavior changes [ ] Pull request title follows Conventional Commit style and uses the correct type U...

📄 CodeRabbit inference engine (.agents/skills/prepare-pr/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
Format changed files with the language-native formatter before the final lint/test pass.

📄 CodeRabbit inference engine (.agents/skills/validate-change/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
Keep NeMo Relay optional Use stable, documented framework or plugin APIs Wrap tool and LLM paths at the correct framework boundary Preserve the framework's original behavior when NeMo Relay is absent Integration uses public framework or plu...

📄 CodeRabbit inference engine (.agents/skills/contribute-integration/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
Tool execution callbacks and each execution-intercept `next` continuation return the canonical `ToolExecutionResult { result, annotation }`.

📄 CodeRabbit inference engine (.agents/skills/add-middleware/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
For changes in the Rust core, adaptive, dynamic plugin, worker, worker-proto, or types crates, run `cargo fmt --all`, `just test-rust`, and `cargo clippy --workspace --all-targets -- -D warnings` as the default validation sequence.

📄 CodeRabbit inference engine (.agents/skills/test-rust-core/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
[ ] `crates/core` or `crates/adaptive` changes ran the full language matrix

📄 CodeRabbit inference engine (.agents/skills/prepare-pr/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
For shared-semantics or broad runtime changes in the core or adaptive crates, run `just ci=true test-rust`.

📄 CodeRabbit inference engine (.agents/skills/test-rust-core/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
**Core Rust** Implement the behavior first in `crates/core/src/api/` and related core modules such as `crates/core/src/api/runtime/`, `crates/core/src/codec/`, or `crates/core/src/json.rs`.

📄 CodeRabbit inference engine (.agents/skills/add-binding-feature/SKILL.md)

Files:

  • crates/core/src/codec/anthropic.rs
Keep SPDX headers on source, docs, scripts, and configuration files.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
**Validation** Run the validation matrix from the `validate-change` skill for the affected surfaces.

📄 CodeRabbit inference engine (.agents/skills/add-binding-feature/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
Use `test-ffi-surface`.

📄 CodeRabbit inference engine (.agents/skills/validate-change/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
[ ] Any Rust change ran `just test-rust` [ ] Any Rust change ran `cargo fmt --all` [ ] Any Rust change ran `cargo clippy --workspace --all-targets -- -D warnings`

📄 CodeRabbit inference engine (.agents/skills/prepare-pr/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
Follow binding naming conventions: Rust and Python `snake_case`, C FFI exports prefixed `nemo_relay_`, Go `PascalCase` for public APIs, Node.js `camelCase`.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
[ ] SPDX license header on any new files

📄 CodeRabbit inference engine (.agents/skills/add-binding-feature/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
Update docs and examples in the same branch.

📄 CodeRabbit inference engine (.agents/skills/maintain-observability/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
If the change touched `crates/core` or shared runtime semantics, also use `validate-change` for broader validation

📄 CodeRabbit inference engine (.agents/skills/test-go-binding/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
Run `cargo fmt --all` for all FFI work since it is Rust work Run `just test-rust` to validate FFI changes Run `cargo clippy --workspace --all-targets -- -D warnings` to enforce strict linting on FFI work

📄 CodeRabbit inference engine (.agents/skills/test-ffi-surface/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
Run `cargo fmt --all` when Rust files are changed as part of Node work Run `cargo clippy --workspace --all-targets -- -D warnings` when Rust files are changed as part of Node work Run `just test-rust` when Rust files are changed as part of...

📄 CodeRabbit inference engine (.agents/skills/test-node-binding/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
When Rust files changed as part of Go work, also run `cargo fmt --all`, `just test-rust`, and `cargo clippy --workspace --all-targets -- -D warnings`

📄 CodeRabbit inference engine (.agents/skills/test-go-binding/SKILL.md)

Files:

  • crates/core/tests/unit/codec/anthropic_tests.rs
  • crates/core/src/codec/anthropic.rs
🔇 Additional comments (2)
crates/core/src/codec/anthropic.rs (1)

1191-1192: LGTM!

Also applies to: 1248-1248, 1321-1328

crates/core/tests/unit/codec/anthropic_tests.rs (1)

1435-1475: LGTM!


Walkthrough

Anthropic streaming usage accumulation now merges successive usage updates. Initial input and cache fields remain available when later deltas provide only output usage. A unit test validates the finalized aggregate token mapping.

Changes

Anthropic usage accumulation

Layer / File(s) Summary
Merge streaming usage updates
crates/core/src/codec/anthropic.rs, crates/core/tests/unit/codec/anthropic_tests.rs
Streaming message_start and message_delta events use shared usage accumulation. Later object fields merge into existing usage data. The test verifies prompt, completion, total, cache-read, and cache-write token mappings.

Estimated code review effort: 2 (Simple) | ~10 minutes

Merge Risk: ⚪ Minimal · up to c5279

Anthropic streaming responses now retain previously reported usage fields when later events provide partial cumulative usage updates. The change is covered for prompt, completion, total, cache-read, and cache-write token counts, with no remaining current-head merge risk identified.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title uses valid Conventional Commits syntax with the lowercase type "fix". It concisely describes the usage-preservation change, stays under 72 characters, and has no trailing period.
Description check ✅ Passed The description includes the required Overview, Details, reviewer-start, and Related Issues sections. It explains the change, identifies regression coverage, records validation commands, and uses the …
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@willkill07 willkill07 added this to the 0.9 milestone Sep 4, 2026
@github-actions

github-actions Bot commented Sep 4, 2026

Copy link
Copy Markdown

@mnajafian-nv

Copy link
Copy Markdown
Contributor Author

/merge

@rapids-bot
rapids-bot Bot merged commit a3a920e into NVIDIA:main Sep 4, 2026
97 checks passed
sara-tadayon-nv pushed a commit to sara-tadayon-nv/NeMo-Relay that referenced this pull request Sep 9, 2026
#### Overview

Preserve Anthropic input and cache token usage when later streaming events contain only partial usage updates.

- [x] I confirm this contribution is my own work, or I have the right to submit it under this project's license.
- [x] I searched existing issues and open pull requests, and this does not duplicate existing work.

#### Details

- Merge usage fields across Anthropic `message_start` and `message_delta` events instead of replacing the complete usage object.
- Preserve fields omitted from later events while allowing newer cumulative values to replace earlier values.
- Add regression coverage for prompt, completion, total, cache-read, and cache-write token counts.
- No public API or configuration changes.

Validation:

- `cargo test -p nemo-relay anthropic_streaming_codec_preserves_usage_across_partial_updates -- --nocapture`
- `just test-rust`
- `just test-python`
- `just test-node`
- `just test-go`
- `cargo clippy --workspace --all-targets -- -D warnings`
- `uv run pre-commit run --all-files`

#### Where should the reviewer start?

Start with `AnthropicMessagesStreamingState::observe_usage` in `crates/core/src/codec/anthropic.rs`, followed by `anthropic_streaming_codec_preserves_usage_across_partial_updates` in `crates/core/tests/unit/codec/anthropic_tests.rs`.

#### Related Issues: (use one of the action keywords Closes / Fixes / Resolves / Relates to)

- Relates to NousResearch/hermes-agent#103104




## Summary by CodeRabbit

- **Bug Fixes**
  - Improved streaming Anthropic usage tracking so usage details from earlier updates are retained when later updates provide only partial information.
  - Ensured prompt, completion, total, and cache token counts remain accurate after streaming responses finish.

- **Tests**
  - Added coverage for preserving usage fields across successive streaming updates.

Authors:
  - Maryam Najafian (https://github.com/mnajafian-nv)

Approvers:
  - Will Killian (https://github.com/willkill07)

URL: NVIDIA#996
greysonlalonde pushed a commit that referenced this pull request Nov 20, 2026
…ull (#1778)

#### Overview

Skips `null` values when merging Anthropic `message_delta` usage into
the `message_start` usage, so a streamed call keeps its input and cache
token counts when the terminal delta reports them as `null`.

- [x] I confirm this contribution is my own work, or I have the right to
submit it under this project's license.
- [x] I searched existing issues and open pull requests, and this does
not duplicate existing work.

#### Details

- `crates/core/src/codec/anthropic.rs`: `observe_usage` skips `null`
values when extending the accumulated usage; non-null values, including
`0`, still replace earlier ones.
- `crates/core/tests/unit/codec/anthropic_tests.rs`: add
`anthropic_streaming_codec_keeps_message_start_usage_when_delta_reports_null`.
- Matches Anthropic's SDK accumulator, which copies these counters from
`message_delta` only when they are not `None`.
- Fields omitted from `message_delta` keep the behavior from #996.
- No breaking changes.

Tested on macOS, on `release/0.11` at `cf0712e5`:
- The new test fails without the fix (`left: Null`, `right: Number(10)`)
and passes with it.
- `cargo nextest run -p nemo-relay -E 'test(~anthropic)'`: 89 passed.
- `just test-rust`: 6733 passed, 4 skipped (with `ulimit -n 4096`, since
#1736 is on `main` only). One unrelated ATOF timing test,
`unanswered_http_post_requests_record_flush_and_close_timeouts`, was
flaky and passed on retry and when run alone.
- `cargo fmt --all -- --check` and `cargo clippy -p nemo-relay
--all-targets -- -D warnings` pass.
- Pre-commit hooks pass, except `npm audit` and `uv audit`, which I
skipped; this change touches no lockfiles.

Not tested on Linux or Windows; CI covers those.

#### Where should the reviewer start?

`observe_usage` in `crates/core/src/codec/anthropic.rs`.

#### Related Issues: (use one of the action keywords Closes / Fixes /
Resolves / Relates to)

Closes #1775

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Streaming usage totals now retain previously reported values when
later updates provide `null`, while still applying non-null updates.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Sakshi Tapkir <[email protected]>

This branch was previously deployed

1 inactive deployment
fern — c52792fc Deployed Sep 4, 2026 by rapids-bot[bot] via Clean up docs preview #4450
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Bug issue describes bug; PR fixes bug lang:rust PR changes/introduces Rust code size:S PR is small

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants