Skip to content

perf(codecs): reduce memory use during normalization and redaction - #1804

Merged
bbednarski9 merged 5 commits into
feat/bbednarski/codec-pii-part-provenancefrom
feat/bbednarski/codec-memory
Nov 23, 2026
Merged

bbednarski9 merged 5 commits into
feat/bbednarski/codec-pii-part-provenancefrom
feat/bbednarski/codec-memory

Conversation

@bbednarski9

@bbednarski9 bbednarski9 commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

Overview

Reduce temporary allocations when the Rust codecs project requests, decode Gemini content, and redact responses. This is the third layer of the codec stack, based on #1801. The largest measured reduction in peak live heap was 32.6% for an OpenAI Chat request with 128 messages.

  • 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

  • Borrow the sanitized request during clean projection. OCI takes an owned copy when its envelope needs a serving-mode edit.
  • Use one collection of Gemini content parts. OpenAI Responses and Gemini share the conversion that joins plain text and preserves metadata-bearing or mixed parts.
  • Reuse one provider decode inside the pricing adapter and borrow the sanitized annotation unless the runtime-only cost requires an adjustment. Baseline validation and final provider verification still run.
  • Visit the owned PII wire payload in place, skip branches a selector cannot match, and track actual changes. Removed object keys and array null slots retain their distinct meanings.

Memory measurements. Compared parent ea504ac50 with e4e8bb0bd on macOS arm64 using Rust 1.96.1 and the repository release profile. Both checkouts ran identical benchmark source with separate first-party artifacts. The table reports medians over seven operations after warm-up. Allocated bytes count requested Rust heap allocations, including reallocations at their new size. Peak extra live bytes measure growth above the prebuilt input. Each output is checked outside the measurement window.

Fixture Allocated MiB, before → after Reduction Peak extra live MiB, before → after Reduction
OpenAI Chat history projection 4.23 → 3.21 24.0% 3.12 → 2.10 32.6%
Gemini plain text 4.12 → 3.11 24.4% 4.10 → 3.09 24.7%
Gemini metadata-bearing text 3.12 → 2.12 32.2% 3.10 → 2.09 32.4%
Pricing with provider-reported cost 21.19 → 17.15 19.0% 13.08 → 11.07 15.4%
Pricing with estimated cost 21.19 → 19.17 9.5% 13.08 → 13.08 0.0%
Targeted PII, no selector match 12.10 → 11.09 8.4% 9.06 → 8.05 11.1%
Targeted PII, one removed field 18.15 → 17.13 5.6% 13.08 → 12.08 7.7%

The projection fixture uses 128 messages of 8 KiB each. The Gemini fixtures use 128 text parts of 8 KiB each, with a signature on the final part for the metadata case. The response-edit fixtures carry approximately 1 MiB of tool arguments. The pricing cases cover provider-reported and deterministic estimated cost. The PII cases use the provider codec directly to isolate the walker.

The process-level check ran two targeted PII policies through the priced codec, each with eight simultaneous callers handling eight responses apiece. Measured with macOS /usr/bin/time -l over seven fresh processes per revision, alternating order. Median maximum RSS was 182.92 → 170.70 MiB (6.7% lower). The seven-run ranges overlap (168.36–221.77 MiB before and 155.91–197.73 MiB after). The estimated-cost path reduced allocation volume while retaining the same peak live heap.

Validation. All 1,218 tests in the affected codec, runtime, and PII crates passed locally. The full local Rust build stopped at the 4 GiB disk reserve. All five hosted Rust test jobs passed across Linux x64 and ARM64, macOS ARM64, and Windows x64 and ARM64. The staged formatting, Clippy, and Cargo checks passed. The hosted dependency audit fails on the parent branch’s url 2.5.8. The standalone fix in #1803 passes the hosted audit. Rust test matrix · Patched dependency checks

Where should the reviewer start?

Run cargo run --release --locked -p nemo-relay-pii-redaction --example codec_memory. For process RSS, time the compiled target/release/examples/codec_memory --concurrent executable. To reproduce the baseline, copy the same example directory into a clean checkout of ea504ac50 and use a separate Cargo target directory. Benchmark and fixtures · Allocation counters

Review change tracking and null-slot preservation alongside pricing baseline verification. PII walker · Pricing adapter

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

Summary by CodeRabbit

  • Bug Fixes
    • PII redaction now handles removed values in arrays and object fields correctly, without treating unchanged null values as edits.
    • Response text edits preserve independently changed text, and redaction avoids passing runtime-only cost data to providers.
  • Improvements
    • Text-only response parts are presented together as readable text, while parts containing metadata or non-text content remain intact.
    • Estimated cost information is retained more consistently when responses are redacted.

@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

Run configuration

Commits

Reviewing files that changed from the base of the PR and between a165405 and 996151f.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The PR centralizes response content conversion and updates request projection, JSON sanitization, and runtime response pricing. It adds a memory example that measures codec and redaction paths, validates fixture outputs, and supports concurrent PII runs.

Changes

Codec and Redaction

Layer / File(s) Summary
Shared response content conversion
crates/codecs/src/response.rs, crates/codecs/src/gemini_generate_content.rs, crates/codecs/src/openai_responses.rs, crates/pii-redaction/examples/codec_memory/main.rs
A shared helper joins metadata-free text parts with newlines and preserves parts when content is mixed or includes metadata. Gemini and OpenAI Responses use the helper. The example checks text-only and metadata-bearing Gemini responses.
Borrowed request projection
crates/codecs/src/redaction/projection.rs, crates/pii-redaction/examples/codec_memory/main.rs
Request projection uses Cow to borrow the request unless OCI envelope construction needs to mutate it. The selected codec handles encoding and validation. The example measures projection on a large OpenAI Chat request.
Change-aware JSON sanitization
crates/pii-redaction/src/builtin.rs, crates/pii-redaction/tests/unit/builtin_tests.rs, crates/pii-redaction/examples/codec_memory/main.rs
JSON sanitization reports unchanged, replaced, and removed values while mutating values in place. Array removals become null; object removals delete the member. Tests distinguish an unchanged null from a changed value, and the example measures targeted PII cases.
Runtime pricing during response edits
crates/runtime/src/codec.rs, crates/pii-redaction/examples/codec_memory/main.rs
Response decoding applies estimated pricing through a helper. Response editing compares the provider-decoded baseline with the priced response and restores provider cost only when needed. The example measures edits with provider-reported and estimated costs.
Codec memory measurement example
crates/pii-redaction/examples/codec_memory/*
The example adds a global allocator that tracks requested, live, and peak bytes. It validates a warm-up and seven measured outputs, reports median measurements, and supports concurrent PII runs.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Refactor

Merge Risk: Minimal · previous review e3a87

This change reduces temporary memory use in codec request projection, Gemini decoding, pricing and PII redaction while preserving output semantics. No concrete regression was identified in the reviewed changes, and the author reports passing tests. It looks safe to merge after normal checks.

Security architecture risk: Minimal · up to e3a87

The reviewed changes preserve the existing redaction checks. When targeted redaction cannot produce a valid result, the original response is still omitted from observability rather than used as a fallback.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • observed — The inspected exposure is provider response data processed by the existing response sanitizer chain for end-of-call observability. The changed redaction path runs within that chain rather than exposing a new route.

Trust Boundaries and Controls

  • observed — If targeted redaction returns no sanitized response, the runtime chain preserves that omission. The end-of-call payload builder then omits both response data and its annotation rather than restoring the original.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title uses the type perf with scope codecs, which matches the Conventional Commits format. It is lowercase, has no trailing period, and is 66 characters, under the 72-character limit. The summary …
Description check Passed The description follows the repository template. It includes the Overview with both checked confirmation boxes, the Details section, the 'Where should the reviewer start?' section, and the Related Iss…
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: Title check

Explanation

The title uses the type perf with scope codecs, which matches the Conventional Commits format. It is lowercase, has no trailing period, and is 66 characters, under the 72-character limit. The summary 'reduce memory use during normalization and redaction' fits the changeset, which reduces temporary allocations in codec projection, Gemini decoding, pricing, and PII redaction.

Full details: Description check

Explanation

The description follows the repository template. It includes the Overview with both checked confirmation boxes, the Details section, the 'Where should the reviewer start?' section, and the Related Issues section. The Details section describes the changes clearly. The Related Issues section uses 'Relates to #1800 and #1801' instead of the 'Closes #' form, which fits because the PR is a layer built on prerequisites and does not close an issue. The Details section also includes benchmark and validation evidence beyond the template.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 2174078 and e3a87f0.

Files selected for processing: 2

  • crates/codecs/src/redaction/projection.rs
  • crates/pii-redaction/src/builtin.rs

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 9 remain after this review.

Recent review details

Context from checks skipped due to timeout: 45

  • GitHub Check: CodeRabbit
  • GitHub Check: Python / Package (linux-musl-arm64)
  • GitHub Check: Node.js / Test (linux-amd64)
  • GitHub Check: Rust / Package (macos-arm64)
  • GitHub Check: Node.js / Package (linux-amd64)
  • GitHub Check: Python / Package (linux-arm64)
  • GitHub Check: Python / Package (linux-musl-amd64)
  • GitHub Check: Python / Package (windows-arm64)
  • GitHub Check: Rust / Package (linux-arm64)
  • GitHub Check: Rust / Package (windows-arm64)
  • GitHub Check: Rust / Package (linux-musl-amd64)
  • GitHub Check: Rust / Package (windows-amd64)
  • GitHub Check: Python / Package (linux-amd64)
  • GitHub Check: Python / Package (windows-amd64)
  • GitHub Check: Node.js / Package (linux-musl-amd64)
  • GitHub Check: Node.js / Test (linux-arm64)
  • GitHub Check: Node.js / Package (linux-musl-arm64)
  • GitHub Check: Rust / Test (linux-arm64)
  • GitHub Check: Rust / Package (linux-musl-arm64)
  • GitHub Check: Python / Test (macos-arm64)
  • GitHub Check: Rust / Package (linux-amd64)
  • GitHub Check: Rust / Test (windows-arm64)
  • GitHub Check: Rust / Test (windows-amd64)
  • GitHub Check: Python / Package (macos-arm64)
  • GitHub Check: Python / Test (linux-amd64)
  • GitHub Check: Node.js / Package (macos-arm64)
  • GitHub Check: Rust / Test (macos-arm64)
  • GitHub Check: Node.js / Package (linux-arm64)
  • GitHub Check: Node.js / Package (windows-amd64)
  • GitHub Check: Node.js / Package (windows-arm64)
  • GitHub Check: Python / Test (windows-arm64)
  • GitHub Check: Go / Test (macos-arm64)
  • GitHub Check: Rust / Test (linux-amd64)
  • GitHub Check: Python / Test (windows-amd64)
  • GitHub Check: Python / Test (linux-arm64)
  • GitHub Check: Go / Test (windows-amd64)
  • GitHub Check: Node.js / Test (windows-arm64)
  • GitHub Check: Node.js / Test (macos-arm64)
  • GitHub Check: Node.js / Test (windows-amd64)
  • GitHub Check: Go / Test (windows-arm64)
  • GitHub Check: Go / Test (linux-amd64)
  • GitHub Check: Go / Test (linux-arm64)
  • GitHub Check: Check / Run
  • GitHub Check: Node.js / Package OpenClaw plugin
  • GitHub Check: Preview docs
Additional comments: 1

crates/pii-redaction/src/builtin.rs: 1

946-947: Data Integrity & Integration

The claimed false negative does not occur. For each container, changed is true exactly when the walk changes a key, a slot, or a string value. Deleting a nested object member, removing a non-null array element, and combining them all report a change. A null array element that is removed reports no change, which matches the unchanged structure. No inspected path leaves the flag false while the wire payload differs from the input. The response branch therefore does not receive an outdated baseline because of this composition.

@bbednarski9
bbednarski9 added this pull request to stack #1802 November 22, 2026 18:56
@github-actions github-actions Bot added size:L PR is large Improvement improvement to existing functionality lang:rust PR changes/introduces Rust code labels Nov 22, 2026
@github-actions

Copy link
Copy Markdown

@willkill07 willkill07 added this to the 1.0 milestone Nov 22, 2026
@codecov

codecov Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.92308% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.13%. Comparing base (a0f2924) to head (996151f).

Files with missing lines Patch % Lines
crates/pii-redaction/src/builtin.rs 97.47% 2 Missing ⚠️
crates/codecs/src/response.rs 94.44% 1 Missing ⚠️
crates/runtime/src/codec.rs 95.00% 1 Missing ⚠️
Additional details and impacted files
@@                              Coverage Diff                              @@
##           feat/bbednarski/codec-pii-part-provenance    #1804      +/-   ##
=============================================================================
- Coverage                                      94.14%   94.13%   -0.00%     
=============================================================================
  Files                                            543      543              
  Lines                                         171491   171509      +18     
  Branches                                         235      235              
=============================================================================
+ Hits                                          161435   161444       +9     
- Misses                                         10055    10064       +9     
  Partials                                           1        1              
Components Coverage Δ
Rust Runtime 96.11% <96.08%> (-0.01%) ⬇️
Shared DTO Types 97.85% <ø> (ø)
CLI 91.56% <ø> (-<0.01%) ⬇️
Go Binding 94.26% <ø> (ø)
Python Binding 95.28% <ø> (ø)
Node Binding 99.24% <ø> (ø)
Dynamic Plugin SDKs 94.52% <ø> (-<0.01%) ⬇️
Files with missing lines Coverage Δ
crates/codecs/src/gemini_generate_content.rs 97.65% <100.00%> (-0.01%) ⬇️
crates/codecs/src/openai_responses.rs 96.99% <100.00%> (+0.03%) ⬆️
crates/codecs/src/redaction/projection.rs 94.53% <100.00%> (+0.06%) ⬆️
crates/codecs/src/response.rs 97.44% <94.44%> (-0.90%) ⬇️
crates/runtime/src/codec.rs 82.52% <95.00%> (+1.88%) ⬆️
crates/pii-redaction/src/builtin.rs 95.56% <97.47%> (-0.03%) ⬇️

... and 8 files with indirect coverage changes


Continue to review full report in Codecov by Harness.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update a0f2924...996151f. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@bbednarski9
bbednarski9 marked this pull request as ready for review November 22, 2026 19:31
@bbednarski9
bbednarski9 requested a review from a team as a code owner November 22, 2026 19:31
@bbednarski9

Copy link
Copy Markdown
Collaborator Author

Codec memory benchmark results

All seven fixtures allocated fewer bytes. The largest drop in peak live heap was 32.6% for a clean OpenAI Chat request with 128 messages. Gemini text with metadata showed a similar reduction at 32.4%. On the estimated-cost path, allocation volume fell 9.5% and peak live heap stayed at 13.08 MiB.

Fixture Total allocated MiB, before → after Peak extra live MiB, before → after
OpenAI Chat history projection 4.23 → 3.21 3.12 → 2.10
Gemini plain text 4.12 → 3.11 4.10 → 3.09
Gemini text with metadata 3.12 → 2.12 3.10 → 2.09
Pricing with provider-reported cost 21.19 → 17.15 13.08 → 11.07
Pricing with estimated cost 21.19 → 19.17 13.08 → 13.08
Targeted PII, no selector match 12.10 → 11.09 9.06 → 8.05
Targeted PII, one field removed 18.15 → 17.13 13.08 → 12.08

For the combined pricing and PII workload, median maximum resident set size (RSS) fell from 182.92 to 170.70 MiB (6.7%). Each of two policies ran with eight concurrent callers processing eight responses apiece. We alternated seven fresh processes per revision. The ranges overlapped (168.36–221.77 MiB before and 155.91–197.73 MiB after), so the size of the process-level improvement is less certain.

The table compares parent ea504ac50 with PR head e4e8bb0bd using identical fixtures and separate release builds on macOS ARM64 with Rust 1.96.1. Each value is the median of seven operations after warm-up. Total allocated bytes include reallocations at their new size. Peak extra live bytes measure heap growth above the prebuilt input. Benchmark fixtures · Allocation counters

@bbednarski9
bbednarski9 merged commit 179c468 into main Nov 23, 2026
174 of 177 checks passed
@willkill07
willkill07 deleted the feat/bbednarski/codec-memory branch November 24, 2026 15:25

This branch was previously deployed

1 inactive deployment
fern — 996151fe Deployed Nov 23, 2026 by bbednarski9 via Clean up docs preview #7713
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:L PR is large

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants