Skip to content

perf: reuse owned payloads in built-in request codecs - #1493

Merged
willkill07 merged 1 commit into
NVIDIA:mainfrom
willkill07:codex/reduce-codec-payload-copies
Oct 25, 2026
Merged

willkill07 merged 1 commit into
NVIDIA:mainfrom
willkill07:codex/reduce-codec-payload-copies

Conversation

@willkill07

@willkill07 willkill07 commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Overview

Reduce payload copying when managed LLM execution encodes requests containing large images or other unchanged content. All five built-in request codecs now use the existing owned-encoding hook to patch the request they already own, while borrowed encoding continues to preserve its input.

  • 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

  • Implement encode_owned_with_baseline for OpenAI Chat, OpenAI Responses, Anthropic Messages, Gemini GenerateContent, and OCI GenAI. Delegate borrowed baseline-aware encoding through an explicit request clone so both paths retain the same merge and validation behavior.
  • Patch OCI's bare or enveloped chatRequest directly, removing its additional full body copy.
  • Let the OpenAI Responses message patcher read the input representation from the mutable body instead of requiring a second reference to the original request.
  • Add allocation-address checks proving unchanged image/payload buffers survive no-op and parameter-only edits, including OCI GENERIC, COHERE, and COHEREV2 in bare and wrapped forms. Preserve headers and provider representations.

The managed unary and streaming paths already call this hook through run_request_intercepts_with_codec_and_recorder; Python's managed bridge extracts the underlying Rust codecs for built-in codec objects. Standalone borrowed codec.encode(annotated, original) still preserves its input, and custom codec adapters retain their existing behavior. No public API or breaking changes.

Measured memory impact

Compared unmodified main at 8109e75036c1c97c26fab532fcf6a83f2152babe with this change on macOS 27.0, ARM64, with a 44 MiB synthetic image payload (11 strings of 4 MiB each). The probe calls public llm_call_execute with a deterministic provider continuation and flushes subscriber work after each call. An auditing wrapper verified one owned-encoder invocation per call and preservation of the original image buffer through to the provider continuation in the changed build.

Approximate medians in MiB with one non-retaining subscriber and the default allocator cache policy:

Codec group Request intercept Allocated per call, before → after Peak live memory, before → after
OpenAI Chat, OpenAI Responses, Anthropic, Gemini None 132 → 88 MiB 132 → 132 MiB
OpenAI Chat, OpenAI Responses, Anthropic, Gemini Temperature edit 220 → 176 MiB 176 → 176 MiB
OCI, bare or wrapped None 176 → 88 MiB 176 → 132 MiB
OCI, bare or wrapped Temperature edit 264 → 176 MiB 220 → 176 MiB

Allocated per call is cumulative requested allocation volume, not simultaneous residency. Peak live memory tracks outstanding Rust allocation sizes through a GlobalAlloc wrapper forwarding to System; it excludes allocator overhead and cached freed blocks. For OCI, process maximum RSS also fell by about 44 MiB: approximately 186 → 142 MiB without an intercept and 230 → 186 MiB with a temperature edit.

The complete matrix covered 288 measured calls: baseline/candidate × six request shapes × intercept/no intercept × subscriber/no subscriber × default/disabled large cache × three measured repetitions after process warm-up. The subscriber runs delivered two events per measured call. Disabling MallocLargeCache preserved the qualitative result. MallocNanoZone=0 was inherited in both runs. Both builds used the same instrumented development profile; no timing claim is made. Measurements cover the Rust managed unary path; Python and streaming routing were verified by source inspection.

For OpenAI, Anthropic, and Gemini, this removes one payload copy per call but does not demonstrate lower whole-call peak memory or RSS in this workload. Later observability-body and middleware annotation copies still determine the peak. OCI removes two copies and also lowers the peak. This is a copy-reduction improvement related to #1492, not a claim to repair a proven cumulative native allocation leak.

Validation

  • cargo test -p nemo-relay --lib codec:: --locked: 654 passed.
  • cargo fmt -p nemo-relay -- --check and git diff --check: passed.
  • uv run pre-commit run: Rust formatting, workspace Clippy/check, copyright/file hygiene, and Cargo/uv/npm audits passed. The documentation link check failed on the unchanged Hermes URL https://hermes-agent.nousresearch.com/docs/developer-guide/relay-shared-metrics returning HTTP 503; a focused retry failed identically.
  • Before/after memory probe: 288 measured managed calls, with owned-call counts, provider buffer identity checks, and subscriber delivery barriers.
  • just test-rust: 6,514 passed, 4 skipped.
  • Binding suites were not rerun: no binding APIs or conversion code changed; the implementation is internal to Rust's built-in codecs.

Where should the reviewer start?

Start with OpenAIChatCodec::encode_owned_with_baseline in crates/core/src/codec/openai_chat.rs and owned_encoding_reuses_payloads_across_provider_codecs in crates/core/tests/unit/codec/parity_tests.rs. Then review OCI's direct nested-body mutation in crates/core/src/codec/oci_genai.rs and the existing managed dispatch in crates/core/src/api/shared.rs.

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

Summary by CodeRabbit

  • Performance
    • Improved encoding efficiency for large image and other request payloads across supported AI providers, reducing unnecessary data copying.
  • Compatibility
    • Preserved request headers and existing input formats during encoding, including string-form input and enveloped request bodies.
  • Tests
    • Added coverage confirming encoded requests remain consistent across provider formats and retain large payload data.

@willkill07
willkill07 requested a review from a team as a code owner October 24, 2026 13:33
@github-actions github-actions Bot added size:M PR is medium Improvement improvement to existing functionality lang:rust PR changes/introduces Rust code labels Oct 24, 2026
@coderabbitai

coderabbitai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 8109e75 and e046a3b.

Files selected for processing: 7
  • crates/core/src/codec/anthropic.rs
  • crates/core/src/codec/gemini_generate_content.rs
  • crates/core/src/codec/oci_genai.rs
  • crates/core/src/codec/openai_chat.rs
  • crates/core/src/codec/openai_responses.rs
  • crates/core/tests/unit/codec/openai_chat_tests.rs
  • crates/core/tests/unit/codec/parity_tests.rs

Included review availability: This review used your included allowance. 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: 2
  • GitHub Check: Preview docs
  • GitHub Check: Changes / Detect
Additional context used
Path-based instructions: 2
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/openai_chat_tests.rs
  • crates/core/tests/unit/codec/parity_tests.rs
Review the Rust runtime for async correctness, scope isolation, middleware ordering, and event lifecycle regressions.

CodeRabbit configuration file

Files:

  • crates/core/src/codec/gemini_generate_content.rs
  • crates/core/tests/unit/codec/openai_chat_tests.rs
  • crates/core/tests/unit/codec/parity_tests.rs
  • crates/core/src/codec/anthropic.rs
  • crates/core/src/codec/openai_responses.rs
  • crates/core/src/codec/openai_chat.rs
  • crates/core/src/codec/oci_genai.rs
Additional comments: 7
crates/core/src/codec/anthropic.rs: 1

1221-1221: LGTM!

Also applies to: 1224-1231, 1242-1242

crates/core/src/codec/gemini_generate_content.rs: 1

1474-1475: LGTM!

Also applies to: 1478-1482, 1485-1486, 1515-1515

crates/core/src/codec/oci_genai.rs: 1

1107-1107: LGTM!

Also applies to: 1110-1117, 1121-1128, 1130-1130, 1136-1136, 1139-1139, 1148-1148, 1171-1171, 1179-1179, 1182-1182, 1184-1189

crates/core/src/codec/openai_chat.rs: 1

1410-1410: LGTM!

Also applies to: 1413-1420, 1430-1430

crates/core/src/codec/openai_responses.rs: 1

1025-1025: LGTM!

Also applies to: 1044-1044, 1481-1481, 1484-1488, 1490-1491, 1494-1494, 1501-1501

crates/core/tests/unit/codec/openai_chat_tests.rs: 1

26-65: LGTM!

crates/core/tests/unit/codec/parity_tests.rs: 1

75-189: LGTM!

Walkthrough

The provider codecs now patch owned request content in place and return the modified request. Tests compare owned encoding with baseline encoding and check payload pointer reuse.

Changes

Owned request encoding

Layer / File(s) Summary
In-place codec encoding
crates/core/src/codec/anthropic.rs, crates/core/src/codec/gemini_generate_content.rs, crates/core/src/codec/oci_genai.rs, crates/core/src/codec/openai_chat.rs, crates/core/src/codec/openai_responses.rs, crates/core/tests/unit/codec/openai_chat_tests.rs, crates/core/tests/unit/codec/parity_tests.rs
The codecs patch owned request content and return the modified request. OpenAI Responses reads input from the mutable content when preserving string-form input. Tests check parity, header preservation, and reuse of large payload allocations.

Priority: Low

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Possibly related issues

  • NVIDIA/NeMo-Relay issue 1492: This change addresses codec payload copying, but does not address post-release memory retention or a request-size cap.
Merge Risk: Minimal · up to e046a

No merge-blocking issue was identified in the owned codec encoding changes; the PR is ready for normal merge checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 5.88% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title follows Conventional Commits format with the allowed lowercase type perf, uses a concise imperative summary, stays under 72 characters, and has no trailing period.
Description check Passed The description includes all required template sections, completed checklist items, detailed implementation notes, reviewer guidance, related issue information, and validation results. It also clearly…
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.
Full details: Description check

Explanation

The description includes all required template sections, completed checklist items, detailed implementation notes, reviewer guidance, related issue information, and validation results. It also clearly documents the unchanged Hermes link-check failure.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@willkill07 willkill07 self-assigned this Oct 24, 2026
@willkill07 willkill07 added this to the 0.11 milestone Oct 24, 2026
@github-actions

Copy link
Copy Markdown

@greysonlalonde greysonlalonde 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

@willkill07
willkill07 merged commit 5d5edbe into NVIDIA:main Oct 25, 2026
97 checks passed
@willkill07
willkill07 deleted the codex/reduce-codec-payload-copies branch October 30, 2026 14:46

This branch was previously deployed

1 inactive deployment
fern — e046a3b9 Deployed Oct 25, 2026 by willkill07 via Clean up docs preview #6526
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Improvement improvement to existing functionality lang:rust PR changes/introduces Rust code size:M PR is medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants