You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
perf(codecs): reduce memory use during normalization and redaction - #1804
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
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.
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.
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.
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.
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: 4
Check name
Status
Explanation
Title check
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
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
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
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
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.
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.
❌ 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).
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Improvementimprovement to existing functionalitylang:rustPR changes/introduces Rust codesize:LPR is large
2 participants
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.
Details
Memory measurements. Compared parent
ea504ac50withe4e8bb0bdon 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.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 -lover 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
url2.5.8. The standalone fix in #1803 passes the hosted audit. Rust test matrix · Patched dependency checksWhere should the reviewer start?
Run
cargo run --release --locked -p nemo-relay-pii-redaction --example codec_memory. For process RSS, time the compiledtarget/release/examples/codec_memory --concurrentexecutable. To reproduce the baseline, copy the same example directory into a clean checkout ofea504ac50and use a separate Cargo target directory. Benchmark and fixtures · Allocation countersReview 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
nullvalues as edits.