Skip to content

feat!: add borrowed normalized codec content views across Rust and language bindings APIs - #1730

Closed
bbednarski9 wants to merge 41 commits into
NVIDIA:mainfrom
bbednarski9:bbednarski/codec-content-views
Closed

bbednarski9 wants to merge 41 commits into
NVIDIA:mainfrom
bbednarski9:bbednarski/codec-content-views

Conversation

@bbednarski9

@bbednarski9 bbednarski9 commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Warning

Breaking changes in v1.0.0. Rust’s system_prompt(), last_user_message(), and response_text() now return Option<Cow<'_, str>>. Keep the result alive and call .as_deref() to borrow its text, or use .map(Cow::into_owned) to keep an owned string. Exhaustive matches on BlockContentType must handle StructuredInput and Opaque.

The text helpers now join all eligible text and refusal parts in the selected item. OpenAI Chat and Responses annotations containing a refusal expose typed parts at /message. Consumers that assumed a string must handle that shape. Text helper migration · OpenAI redaction policy migration

Overview

This is the first PR in the v1.0.0 codec refactor. Rust provides borrowed views of normalized request history and response output. Python, Node.js, C, and Go expose owned snapshots with the same selection and text extraction rules. Rust and standalone Python workers can request a snapshot from the host through the new InspectLlmContent RPC.

The shared traversal lets observability, PII redaction, and adaptive prompt analysis distinguish text and refusals from tool payloads, media, and provider-native content. Provider decoders and stream aggregators now retain content these consumers previously lost. The daemon validates stream completion before publishing an observation.

  • 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

1. Shared normalized content API — crates/types

content.rs introduces MessageView, ContentEntry, ContentKind, borrowed tool views, PayloadRef, and normalized source locations.

Entry point Selection
AnnotatedLlmRequest::last_message() Exactly the final supplied request item; instructions remain separate
AnnotatedLlmResponse::output() Current normalized message plus separate response tool calls
Message::content_view() Any selected history item
MessageContent::content_view() Standalone content, including instructions

Each view offers parts(), text_parts(), and text():

  • Typed traversal distinguishes text, refusals, tool calls/results, images, audio, files, and opaque provider-native content. Tool payloads retain string versus parsed JSON representations without parsing or serializing during traversal.
  • Content-array order is preserved. Separate assistant/response tool calls follow content and retain their field identity; this does not reconstruct provider-wire order.
  • Default text includes text/refusals and supported shallow native fallbacks. It excludes tool payloads, reasoning, media, and arbitrary nested metadata. Recognized native request messages, including OpenAI Responses message content, expose their known content rather than disappearing from extraction.
  • No eligible text returns None; an explicit empty string remains present. Whitespace and empty parts survive newline joining. Selection never searches backward for another item with text.
  • Forward-only iterators advance through the selection once. Traversal borrows the source without cloning payloads or building a parts vector. text() borrows one string and allocates only to join multiple strings. Locations identify current normalized fields/indices, not stable edit handles.
flowchart TD
    R["Provider request payload"] --> D["Request codec"]
    B["Buffered provider response"] --> E["Response codec"]
    S["Provider SSE events"] --> V["Completion validation"]
    V --> A["Provider streaming aggregation"]
    A --> E
    D --> N["Normalized request / response"]
    E --> N
    N --> M["Borrowed MessageView"]
    M --> P["Typed parts + source locations"]
    M --> T["Default text extraction: text + refusals"]
    T --> H["Rust text helpers"]
    M --> F["Owned snapshots for Python, Node.js, C, and Go"]
    M --> W["Host-generated snapshots for worker plugins"]
    T --> O["ATIF / OpenInference display policies"]
    P --> X["PII projection: explicit sanitized text/refusals only"]
    P --> C["Adaptive analysis: typed structured values + media fingerprints"]
    C --> K["Stability and cache planning"]
    K --> G["Require supplied token counts across opaque/media blocks"]
Loading

The diagram shows the shared read surface, not a new retained conversation context. Request views see supplied history; response views see current normalized output. Consumers keep their own display, privacy, and analysis policies.

2. Preserve content before extraction — crates/codecs and daemon worker observation

  • OpenAI Chat: normalize message.refusal as typed refusal content and accumulate streamed refusal deltas, including explicit empty strings. Preserve streamed system_fingerprint, service_tier, and per-choice text/refusal logprob entries.
  • OpenAI Responses: retain typed refusal blocks and their order alongside ordinary text. Text-only responses retain their existing string representation. Streaming aggregation retains provisional text, refusals, and function arguments for supplied output items. Completed fields/parts/items replace provisional data; a nonempty terminal output is authoritative, preventing duplication.
  • Gemini: retain streamed promptFeedback and avoid inventing a candidate when a blocked prompt produced none.
  • Daemon worker: apply the streaming codec's completion validator during observation, use its borrowed collector when available, and close the validation stream. A missing terminal event invalidates the observation aggregate. Preserve cancellation/body-error outcomes when EOF races delivery completion. Validation runs off the application delivery path.

A finalizer can expose partial Responses output, but partial aggregation does not establish successful completion. The worker omits invalid/truncated aggregates; forwarded response bytes are unchanged.

3. Adopt shared traversal in production consumers

Module Resulting behavior
crates/observability/src/atif.rs Join annotated response text/refusals. Textless annotations remain empty instead of recovering raw tool text. Keep existing raw rendering for media/opaque responses and separate tool/usage projections.
crates/observability/src/openinference.rs Share extraction for normalized instructions, history content, and output; trim display text and omit empty attributes. JSON-looking normalized text stays literal. Tool messages/calls retain separate projections.
crates/pii-redaction/src/trajectory_projection.rs Project only explicit sanitized text/refusal kinds. Native fallback text is deliberately excluded. Preserve empty versus absent text and avoid interpreting strings as JSON.
crates/pii-redaction/src/overlay.rs Preserve sanitized OpenAI Chat refusal fields and OpenAI Responses refusal blocks instead of flattening them into ordinary text.

Chat projections join text and refusals within their separate fields; Responses projections preserve ordered text/refusal blocks. Other provider projections retain their existing newline-joined rendering. Existing string redaction actions targeting /message also sanitize text and refusal fields in multipart OpenAI responses. If removing parts prevents the sanitizer from preserving their positions, it omits the response payload.

4. Correct adaptive prompt identity and cache planning — crates/adaptive

The profile and prompt IR builders share borrowed traversal while keeping distinct fingerprinting/rendering policies.

  • Canonical structured input preserves meaningful string whitespace: "New York" and "New York" remain different. Tool arguments, structured tool results, and schema strings retain their structured identity.
  • Media and provider-native input contribute typed fingerprints. Changing an image therefore changes analyzed identity instead of appearing to be the same text-only prompt. Opaque fingerprints are excluded from variable extraction.
  • Stability scoring, prefix comparison, and diagnostic exemplar hashes use typed block identity, distinguishing identical bytes with different content kinds.
  • Existing message/block boundaries and span IDs remain aligned with provider hint application. Analysis representations are not sent to providers; the full source-request reuse guard remains in place.
  • Economics stops considering prefixes at the first opaque/media block without supplied token metadata. Anthropic translation declines breakpoints spanning those blocks rather than estimating tokens from fingerprint characters. Supplied counts remain supported.
  • Learning observations and aggregate/bootstrap state use the ::acg-ir=2 namespace. Old state remains stored but is not loaded or mixed with the new representation.

5. Expose owned snapshots across bindings and worker plugins

Surface How callers inspect content
Python nemo_relay.codecs.MessageView owns the selection. Entries and iterators can outlive the annotation.
Node.js and TypeScript The published nemo-relay-node metapackage exports the codecs namespace with typed selection helpers, entries, and payloads.
C and Go (experimental) C callers inspect normalized JSON with nemo_relay_inspect_llm_content_json and release the result with nemo_relay_string_free. Go’s InspectLLMContent returns a typed, Go-owned snapshot that can outlive the codec callback.
Rust and standalone Python workers One authenticated InspectLlmContent RPC per selection returns explicit absence or a complete owned snapshot. Subsequent reads are local. Older hosts return UNIMPLEMENTED.

The worker protocol adds typed protobuf mappings for selections, locations, and snapshots in src/conversions/content.rs. Existing v1 methods and protocol identity are preserved. Binding examples · Worker protocol contract

Compatibility and migration

  • Rust source change: system_prompt(), last_user_message(), and response_text() now return Option<Cow<'_, str>> instead of Option<&str>. Use .as_deref() for borrowed use or Cow::into_owned when ownership is required.
  • Selection behavior: system_prompt() selects top-level instructions, otherwise the first system/developer item; last_user_message() selects the last user item; response_text() selects current output. All collect eligible text/refusal parts, without skipping a selected textless item.
  • Python: existing text helpers continue to return str | None and inherit the multipart selection behavior.
  • Rust adaptive enum: exhaustive matches on BlockContentType must handle the new StructuredInput and Opaque variants.
  • Adaptive persistence: upgraded agents warm up from fresh samples under the versioned namespace.
  • Normalized type schemas/serialization contracts and codec traits are unchanged; decoded values now retain the refusal content described above. Existing provider normalization can still combine text blocks, including Anthropic, and the views expose the representation available today.

Live streaming extraction APIs, general mutable/redaction APIs, broader binding APIs, comprehensive decoder fidelity changes, and allocation benchmark targets remain outside this PR.

Validation

  • After merging main at PR revision 6bd64dc9c, just test-rust passed 6,771 tests with 4 skipped. All 71 focused managed-worker tests also passed.
  • The local Go suite passed after the C and Go bindings landed. Earlier local Python, Node.js, and documentation suites passed. CI results for the current revision
  • At documentation revision d6afa9016, the staged documentation checks passed. The dependency audit flagged the existing wcmatch 11.0 lockfile entry. GHSA-53pm-wgxf-c6qf

Regression coverage includes all built-in provider fixtures, borrowed versus owned text, normalized locations and serialization, native request fallbacks, multipart/refusal ordering, tool-only/textless selections, buffered/streamed refusal parity, stream completion/cancellation races, consumer-specific projection policies, typed adaptive identity, unknown media token costs, persistence isolation, and cache hints applied to unchanged original provider content.

Where should the reviewer start?

  1. Shared content API and content-view tests: selection, borrowing, typed payloads, and extraction boundaries.
  2. Provider fixture coverage, refusal regressions, then the three changed provider implementations and worker observation.
  3. Consumer adoption in ATIF, OpenInference, and PII projection: check their intentionally different display/privacy policies.
  4. Adaptive IR builder, its tests, token estimation, and persisted-state versioning.
  5. Codec migration documentation and the adaptive/observability/PII documentation for externally visible behavior.
  6. Owned snapshot and shared selection, worker wire conversions, and Go binding tests for the cross-language contract.

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

  • Relates to: Support "text" extraction APIs — implemented for buffered normalized content and existing delegated helpers. No issue number was supplied, so no automatic closing reference is added.
  • Relates to: PII redaction from codec traits + APIs — groundwork and existing projection fixes only; the general redaction/editing API remains open.

Summary by CodeRabbit

  • New Features

    • Added borrowed Rust views and content snapshots for Python, Node.js, C, and Go. Worker plugins can also inspect normalized content. Inspect text, refusals, tool calls and results, media, provider-native content, and source locations.
    • Added consistent helpers for selecting messages, instructions, and response output, and extracting eligible text. Worker plugins can request host-generated content snapshots.
    • Improved provider response handling to preserve refusal content and streaming metadata, and to retain eligible partial output from interrupted streams.
    • Adaptive cache analysis now distinguishes structured and opaque content and uses supplied token counts for media-aware planning.
  • Documentation

    • Added guides for content inspection, text extraction, and provider response behavior.

Expose consistent typed traversal and text extraction for normalized request items and response output.

BREAKING CHANGE: normalized text helpers return Option<Cow<str>>, join all text/refusal parts, and retain textless selection boundaries.

Signed-off-by: Bryan Bednarski <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The pull request adds typed normalized-content views and host-backed inspection across Rust, Python, Node.js, and worker APIs. It also updates adaptive prompt analysis, provider response decoding and streaming, observability and redaction projections, and daemon stream validation.

Changes

Typed Content Views

Layer / File(s) Summary
Rust content views and selection
crates/types/src/codec/*, crates/types/tests/content_views.rs, crates/types/src/codec/request.rs, crates/types/src/codec/response.rs
Rust adds typed borrowed views, content locations, text extraction, request and response selection, and owned snapshots. Text and refusal parts are joined with newlines; tool payloads, media, and excluded native content are not included in extracted text.
Inspection protocol and host RPC
crates/worker-proto/proto/.../content.proto, crates/worker-proto/proto/.../relay_host_runtime_service.proto, crates/worker-proto/src/conversions/*, crates/plugin-host/src/dynamic/worker.rs, crates/worker/src/lib.rs, crates/plugin/src/lib.rs, crates/worker-proto/tests/*, crates/plugin-host/tests/*, crates/worker/tests/*
The protocol adds InspectLlmContent and typed snapshot messages. The host authenticates and validates requests, then returns a snapshot or no selection. The Rust worker API sends the request and returns the host result without local extraction fallback.
Rust-backed Python content views
crates/python/src/py_types/*, python/nemo_relay/_native.pyi, python/nemo_relay/codecs.*, crates/python/tests/coverage/py_types_coverage_tests.py, python/tests/test_content_views.py, docs/integrate-into-frameworks/provider-codecs.mdx
The native Python API exposes read-only views and request/response selectors. The helper methods return owned strings where needed, and tests cover selection, text extraction, payload types, and snapshot independence.
Node.js and TypeScript content views
crates/node/src/content.rs, crates/node/ts/*, crates/node/tests/*content*, crates/node/tests/types_tests.mjs, scripts/docs/generate_node_library_reference.py, scripts/tests/test_node_library_reference.py, crates/node/README.md
The codecs namespace adds typed views, selection helpers, and snapshot-backed value access. Tests and type fixtures cover the public API, and the reference generator resolves namespace exports to qualified names.
Standalone Python worker content views
python/plugin/src/nemo_relay_plugin/*, python/plugin/tests/*, python/tests/plugin/test_worker_content_views.py, docs/build-plugins/workers/python.mdx, python/plugin/README.md
The standalone worker SDK adds asynchronous host-backed selectors and immutable typed views. It maps host errors to SDK errors and does not fall back to Python-local extraction.

Adaptive Prompt IR and State

Layer / File(s) Summary
Typed prompt representation and block construction
crates/adaptive/src/acg/canonicalize.rs, crates/adaptive/src/acg/prompt_ir.rs, crates/adaptive/src/acg/ir_builder.rs, crates/adaptive/src/acg_profile.rs, crates/adaptive/tests/unit/acg/ir_builder_tests.rs, crates/adaptive/tests/unit/acg_profile_tests.rs
Prompt blocks distinguish structured input and opaque content. Builders preserve text/refusal boundaries, canonicalize structured values, and fingerprint opaque media and provider-native values.
Block identity and token planning
crates/adaptive/src/acg/stability.rs, crates/adaptive/src/cache_diagnostics.rs, crates/adaptive/src/acg/economics.rs, crates/adaptive/src/acg/translation/anthropic.rs, crates/adaptive/src/acg/variable_extractor.rs, crates/adaptive/tests/unit/acg/*tests.rs, docs/configure-plugins/adaptive/acg.mdx
Stability and diagnostic hashes use serialized block identities. Token planning stops at blocks without available token estimates; variable extraction skips opaque and image blocks. The guide describes these representations and planning rules.
Versioned ACG state
crates/adaptive/src/acg_profile.rs, crates/adaptive/src/acg_component.rs, crates/adaptive/src/acg_learner.rs, crates/adaptive/tests/integration/*, crates/adaptive/tests/unit/acg_component_tests.rs, crates/adaptive/tests/unit/acg_learner_tests.rs, crates/adaptive/tests/unit/runtime_tests.rs
Aggregate learning keys and persisted observations and stability use the acg-ir=2 namespace. Tests cover legacy-state isolation, rehydration, and versioned keys.

Provider Response Decoding and Streaming

Layer / File(s) Summary
Typed refusal response decoding
crates/codecs/src/openai_chat.rs, crates/codecs/src/openai_responses.rs, crates/codecs/tests/refusal_content.rs, crates/codecs/tests/content_views.rs, crates/node/tests/codec_tests.mjs, python/tests/test_builtin_codecs.py
OpenAI Chat and Responses decoding preserve refusal content as typed parts alongside text. Tests cover mixed and empty refusal values, ordering, and extracted response text.
Provider streaming aggregation
crates/codecs/src/openai_chat.rs, crates/codecs/src/openai_responses.rs, crates/codecs/src/gemini_generate_content.rs, crates/codecs/tests/unit/*tests.rs, docs/integrate-into-frameworks/provider-response-codecs.mdx
OpenAI stream collectors retain refusal, function-argument, and metadata updates. Responses items merge provisional and completed data by index. Gemini streaming retains prompt feedback and emits no candidate when no candidate index was observed.

Observability and Redaction Projections

Layer / File(s) Summary
Observability content projection
crates/observability/src/atif.rs, crates/observability/src/openinference.rs, crates/observability/tests/unit/*projection_tests.rs, docs/configure-plugins/observability/*
ATIF and OpenInference project eligible normalized text and refusals. ATIF uses raw response extraction for media or opaque parts; OpenInference trims extracted text and omits empty content attributes.
Redaction overlays and trajectory output
crates/pii-redaction/src/overlay.rs, crates/pii-redaction/src/trajectory_projection.rs, crates/pii-redaction/tests/coverage/overlay_tests.rs, crates/pii-redaction/tests/unit/*tests.rs, docs/configure-plugins/pii-redaction/redaction-behavior.mdx
OpenAI overlays keep text and refusal fields distinct. Trajectory output preserves provider-specific text and refusal structures. Tests cover redaction, field order, and excluded payloads.

Daemon Stream Observation

Layer / File(s) Summary
Validated stream collection
crates/cli/src/daemon/worker/managed.rs, crates/cli/tests/coverage/daemon/worker_managed_tests.rs, docs/integrate-into-frameworks/provider-response-codecs.mdx
The daemon validates collected streams through the provider codec before finalizing observations. Invalid collection marks observations truncated, except where cancellation or body failure determines the terminal state. Tests cover terminal events and delivery outcomes.

Estimated code review effort: 5 (Critical) | ~120 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant PythonPlugin as Python plugin SDK
  participant PluginRuntime
  participant WorkerHostRuntimeService
  participant ContentSelection
  PythonPlugin->>PluginRuntime: inspect_llm_content(source, selection)
  PluginRuntime->>WorkerHostRuntimeService: Send authenticated inspection request
  WorkerHostRuntimeService->>ContentSelection: Select normalized content
  ContentSelection-->>WorkerHostRuntimeService: Return snapshot or no selection
  WorkerHostRuntimeService-->>PluginRuntime: Return inspection response
  PluginRuntime-->>PythonPlugin: Return snapshot or None
Loading
Merge Risk: Low · previous review de0e1

The typed content-view feature looks sound overall. Five minor, localized issues remain open: possible false cache-stability matches for tool results, redaction text shifting across a removed refusal, a stream-observation status that can be misreported, slow text iteration on very large multipart content, and dropped overloads in the generated Node docs. These are good follow-ups but do not block merge; owner awareness is enough.

Security architecture risk: Minimal · up to de0e1

The inspected changes preserve authentication and limit inspection to caller-supplied content. No material weakening of data access, failure containment, or rollback guarantees was established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • observed — An authenticated worker can submit normalized content for host-side validation and copying. The handler projects that supplied source; it performs no host scope, project, invocation, or retained-snapshot lookup and does not execute tool payloads. No additional cross-activation data-read authority is evident in this method.

Trust Boundaries and Controls

  • observed — The new RPC uses the existing activation-ID and token equality check and rejects calls during activation shutdown. Validation checks message shape and JSON syntax but does not itself establish identity or capability ownership. No codec capability is consumed because inspection operates on content supplied by the caller.

Resilience and Maintainability Implications

  • observed — Observation and stability records remain sequential writes, with hot-cache publication after persistence. This partial-failure window already exists at the PR base; the PR changes their namespace, not their atomicity or retry behavior. Reuse still declines when the stored fingerprint is missing, unavailable, or different from the live profile fingerprint.

Important

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

Failed Failed checks: 1 error

Check name Status Explanation Resolution
Title check Error The title uses the type "feat!" with the required "!" suffix for a breaking change. It has no scope, and the summary is in lowercase imperative form. It is 89 characters, which exceeds the 72-characte… Shorten the title to 72 characters or fewer, and keep the "feat!:" prefix. For example: "feat!: add borrowed normalized codec content views" (50 characters).
Passed Passed checks: 3 passed

Check name Status Explanation
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.
Description check Passed The description follows the template. It has an Overview with both required checkboxes marked, a Details section, a Where should the reviewer start section, and a Related Issues section. It is detaile…
Full details: Description check

Explanation

The description follows the template. It has an Overview with both required checkboxes marked, a Details section, a Where should the reviewer start section, and a Related Issues section. It is detailed and specific. The Related Issues entry uses 'Relates to' without an issue number, and the author states that no issue number was supplied. The Related Issues section is complete as written.

Full details: Title check

Explanation

The title uses the type "feat!" with the required "!" suffix for a breaking change. It has no scope, and the summary is in lowercase imperative form. It is 89 characters, which exceeds the 72-character limit. The summary also matches the changeset, which adds borrowed normalized content views across the Rust core, bindings, and worker protocol.

Resolution

Shorten the title to 72 characters or fewer, and keep the "feat!:" prefix. For example: "feat!: add borrowed normalized codec content views" (50 characters).

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@github-actions github-actions Bot added size:XL PR is extra large Feature a new feature breaking PR introduces a breaking change lang:python PR changes/introduces Python code lang:rust PR changes/introduces Rust code labels Nov 12, 2026
@github-actions

Copy link
Copy Markdown

Recognize Chat, Responses, and Anthropic message roles consistently when extension fields keep requests provider-native. Preserve payloads and textless selection boundaries, and exclude tool envelopes and metadata from text projection.

Signed-off-by: Bryan Bednarski <[email protected]>
Normalize OpenAI Chat and Responses refusals as typed content, accumulate Chat refusal deltas, and preserve refusal fields through PII overlays.

Signed-off-by: Bryan Bednarski <[email protected]>
@github-actions github-actions Bot added the lang:js PR changes/introduces Javascript/Typescript code label Nov 12, 2026
Preserve multipart text and refusals without falling back to raw provider payloads. Keep empty annotations authoritative and retain existing media, opaque content, tool-call, and usage projections.

Signed-off-by: Bryan Bednarski <[email protected]>
Share text and refusal traversal for normalized instructions, history content, and response output. Keep trim and empty-content display rules, preserve JSON text literally, and exclude native reasoning, media, and tool payloads from default message text.

Signed-off-by: Bryan Bednarski <[email protected]>
Traverse normalized output through the borrowed view while retaining the explicit text/refusal allowlist. Reuse joined strings when building fresh provider projections and keep native values, media, and tool payloads excluded.

Signed-off-by: Bryan Bednarski <[email protected]>
Render OpenAI Chat content and refusal fields separately and preserve ordered text/refusal blocks in Responses. Retain empty values, fresh allowlisted payloads, and safe tool and usage projections; cover both response and event sanitizer paths.

Signed-off-by: Bryan Bednarski <[email protected]>
Keep profile and prompt IR rendering policies distinct while sharing normalized part traversal. Preserve existing fingerprints, empty-part behavior, and structured payload rendering without allocating an intermediate string vector.

Signed-off-by: Bryan Bednarski <[email protected]>
Retain media fingerprints and canonical structured values in prompt analysis, preserve block mapping and source-request reuse guards, and decline token-based hints when opaque costs are unknown.

BREAKING CHANGE: BlockContentType adds StructuredInput and Opaque. ACG learning and bootstrap state uses the ::acg-ir=2 namespace and warms up independently of older records.

Signed-off-by: Bryan Bednarski <[email protected]>
@bbednarski9
bbednarski9 marked this pull request as ready for review November 13, 2026 03:40
@github-actions github-actions Bot added the lang:go PR changes/introduces Go code label Nov 20, 2026
@willkill07 willkill07 added this to the 1.0 milestone Nov 20, 2026
@bbednarski9 bbednarski9 changed the title feat!: add borrowed normalized codec content views feat!: add borrowed normalized codec content views across Rust and language bindings APIs Nov 20, 2026

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.

Can we please update this list to include content.rs? This PR adds it, so there are now four files instead of three.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added content.rs to the conversion table and removed the hard-coded file count in d6afa90. The table now lists all four modules.

@mnajafian-nv mnajafian-nv 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 plus a minor suggestion above :)

bbednarski9 added a commit that referenced this pull request Nov 23, 2026
…t and language bindings APIs (#1800)

> [!WARNING]
> **Breaking changes in v1.0.0.** Rust’s `system_prompt()`,
`last_user_message()`, and `response_text()` now return `Option<Cow<'_,
str>>`. Keep the result alive and call `.as_deref()` to borrow its text,
or use `.map(Cow::into_owned)` to keep an owned string. Exhaustive
matches on `BlockContentType` must handle `StructuredInput` and
`Opaque`.
>
> The text helpers now join all eligible text and refusal parts in the
selected item. OpenAI Chat and Responses annotations containing a
refusal expose typed parts at `/message`. Consumers that assumed a
string must handle that shape. [Text helper
migration](https://github.com/NVIDIA/NeMo-Relay/blob/09117da4decd987bd01f4ae371f1d6e1d494baed/docs/integrate-into-frameworks/provider-codecs.mdx#migrate-existing-text-helpers)
· [OpenAI redaction policy
migration](https://github.com/NVIDIA/NeMo-Relay/blob/09117da4decd987bd01f4ae371f1d6e1d494baed/docs/reference/migration-guides.mdx#update-openai-response-redaction-policies)

First layer of the codec refactor. The original review discussion and
approvals are in #1730.

#### Overview

This is the first PR in the v1.0.0 codec refactor. Rust provides
borrowed views of normalized request history and response output.
Python, Node.js, C, and Go expose owned snapshots with the same
selection and text extraction rules. Rust and standalone Python workers
can request a snapshot from the host through the new `InspectLlmContent`
RPC.

The shared traversal lets observability, PII redaction, and adaptive
prompt analysis distinguish text and refusals from tool payloads, media,
and provider-native content. Provider decoders and stream aggregators
now retain content these consumers previously lost. The daemon validates
stream completion before publishing an observation.

- [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

**1. Shared normalized content API — `crates/types`**


[content.rs](https://github.com/NVIDIA/NeMo-Relay/blob/09117da4decd987bd01f4ae371f1d6e1d494baed/crates/types/src/codec/content.rs)
introduces `MessageView`, `ContentEntry`, `ContentKind`, borrowed tool
views, `PayloadRef`, and normalized source locations.

| Entry point | Selection |
| --- | --- |
| `AnnotatedLlmRequest::last_message()` | Exactly the final supplied
request item; instructions remain separate |
| `AnnotatedLlmResponse::output()` | Current normalized message plus
separate response tool calls |
| `Message::content_view()` | Any selected history item |
| `MessageContent::content_view()` | Standalone content, including
instructions |

Each view offers `parts()`, `text_parts()`, and `text()`:

- Typed traversal distinguishes text, refusals, tool calls/results,
images, audio, files, and opaque provider-native content. Tool payloads
retain string versus parsed JSON representations without parsing or
serializing during traversal.
- Content-array order is preserved. Separate assistant/response tool
calls follow content and retain their field identity; this does not
reconstruct provider-wire order.
- Default text includes text/refusals and supported shallow native
fallbacks. It excludes tool payloads, reasoning, media, and arbitrary
nested metadata. Recognized native request messages, including OpenAI
Responses message content, expose their known content rather than
disappearing from extraction.
- No eligible text returns `None`; an explicit empty string remains
present. Whitespace and empty parts survive newline joining. Selection
never searches backward for another item with text.
- Forward-only iterators advance through the selection once. Traversal
borrows the source without cloning payloads or building a parts vector.
`text()` borrows one string and allocates only to join multiple strings.
Locations identify current normalized fields/indices, not stable edit
handles.

```mermaid
flowchart TD
    R["Provider request payload"] --> D["Request codec"]
    B["Buffered provider response"] --> E["Response codec"]
    S["Provider SSE events"] --> V["Completion validation"]
    V --> A["Provider streaming aggregation"]
    A --> E
    D --> N["Normalized request / response"]
    E --> N
    N --> M["Borrowed MessageView"]
    M --> P["Typed parts + source locations"]
    M --> T["Default text extraction: text + refusals"]
    T --> H["Rust text helpers"]
    M --> F["Owned snapshots for Python, Node.js, C, and Go"]
    M --> W["Host-generated snapshots for worker plugins"]
    T --> O["ATIF / OpenInference display policies"]
    P --> X["PII projection: explicit sanitized text/refusals only"]
    P --> C["Adaptive analysis: typed structured values + media fingerprints"]
    C --> K["Stability and cache planning"]
    K --> G["Require supplied token counts across opaque/media blocks"]
```

The diagram shows the shared read surface, not a new retained
conversation context. Request views see supplied history; response views
see current normalized output. Consumers keep their own display,
privacy, and analysis policies.

**2. Preserve content before extraction — `crates/codecs` and daemon
worker observation**

- **OpenAI Chat:** normalize `message.refusal` as typed refusal content
and accumulate streamed refusal deltas, including explicit empty
strings. Preserve streamed `system_fingerprint`, `service_tier`, and
per-choice text/refusal logprob entries.
- **OpenAI Responses:** retain typed refusal blocks and their order
alongside ordinary text. Text-only responses retain their existing
string representation. Streaming aggregation retains provisional text,
refusals, and function arguments for supplied output items. Completed
fields/parts/items replace provisional data; a nonempty terminal output
is authoritative, preventing duplication.
- **Gemini:** retain streamed `promptFeedback` and avoid inventing a
candidate when a blocked prompt produced none.
- **Daemon worker:** apply the streaming codec's completion validator
during observation, use its borrowed collector when available, and close
the validation stream. A missing terminal event invalidates the
observation aggregate. Preserve cancellation/body-error outcomes when
EOF races delivery completion. Validation runs off the application
delivery path.

A finalizer can expose partial Responses output, but partial aggregation
does not establish successful completion. The worker omits
invalid/truncated aggregates; forwarded response bytes are unchanged.

**3. Adopt shared traversal in production consumers**

| Module | Resulting behavior |
| --- | --- |
| `crates/observability/src/atif.rs` | Join annotated response
text/refusals. Textless annotations remain empty instead of recovering
raw tool text. Keep existing raw rendering for media/opaque responses
and separate tool/usage projections. |
| `crates/observability/src/openinference.rs` | Share extraction for
normalized instructions, history content, and output; trim display text
and omit empty attributes. JSON-looking normalized text stays literal.
Tool messages/calls retain separate projections. |
| `crates/pii-redaction/src/trajectory_projection.rs` | Project only
explicit sanitized text/refusal kinds. Native fallback text is
deliberately excluded. Preserve empty versus absent text and avoid
interpreting strings as JSON. |
| `crates/pii-redaction/src/overlay.rs` | Preserve sanitized OpenAI Chat
refusal fields and OpenAI Responses refusal blocks instead of flattening
them into ordinary text. |

Chat projections join text and refusals within their separate fields;
Responses projections preserve ordered text/refusal blocks. Other
provider projections retain their existing newline-joined rendering.
Existing string redaction actions targeting `/message` also sanitize
text and refusal fields in multipart OpenAI responses. If removing parts
prevents the sanitizer from preserving their positions, it omits the
response payload.

**4. Correct adaptive prompt identity and cache planning —
`crates/adaptive`**

The profile and prompt IR builders share borrowed traversal while
keeping distinct fingerprinting/rendering policies.

- Canonical structured input preserves meaningful string whitespace:
`"New York"` and `"New York"` remain different. Tool arguments,
structured tool results, and schema strings retain their structured
identity.
- Media and provider-native input contribute typed fingerprints.
Changing an image therefore changes analyzed identity instead of
appearing to be the same text-only prompt. Opaque fingerprints are
excluded from variable extraction.
- Stability scoring, prefix comparison, and diagnostic exemplar hashes
use typed block identity, distinguishing identical bytes with different
content kinds.
- Existing message/block boundaries and span IDs remain aligned with
provider hint application. Analysis representations are not sent to
providers; the full source-request reuse guard remains in place.
- Economics stops considering prefixes at the first opaque/media block
without supplied token metadata. Anthropic translation declines
breakpoints spanning those blocks rather than estimating tokens from
fingerprint characters. Supplied counts remain supported.
- Learning observations and aggregate/bootstrap state use the
`::acg-ir=2` namespace. Old state remains stored but is not loaded or
mixed with the new representation.

**5. Expose owned snapshots across bindings and worker plugins**

| Surface | How callers inspect content |
| --- | --- |
| Python | `nemo_relay.codecs.MessageView` owns the selection. Entries
and iterators can outlive the annotation. |
| Node.js and TypeScript | The published `nemo-relay-node` metapackage
exports the `codecs` namespace with typed selection helpers, entries,
and payloads. |
| C and Go (experimental) | C callers inspect normalized JSON with
`nemo_relay_inspect_llm_content_json` and release the result with
`nemo_relay_string_free`. Go’s `InspectLLMContent` returns a typed,
Go-owned snapshot that can outlive the codec callback. |
| Rust and standalone Python workers | One authenticated
`InspectLlmContent` RPC per selection returns explicit absence or a
complete owned snapshot. Subsequent reads are local. Older hosts return
`UNIMPLEMENTED`. |

The worker protocol adds typed protobuf mappings for selections,
locations, and snapshots in `src/conversions/content.rs`. Existing v1
methods and protocol identity are preserved. [Binding
examples](https://github.com/NVIDIA/NeMo-Relay/blob/09117da4decd987bd01f4ae371f1d6e1d494baed/docs/integrate-into-frameworks/provider-codecs.mdx#python-content-snapshots)
· [Worker protocol
contract](https://github.com/NVIDIA/NeMo-Relay/blob/09117da4decd987bd01f4ae371f1d6e1d494baed/crates/worker-proto/CONTRACT.md#normalized-content-inspection)

**Compatibility and migration**

- **Rust source change:** `system_prompt()`, `last_user_message()`, and
`response_text()` now return `Option<Cow<'_, str>>` instead of
`Option<&str>`. Use `.as_deref()` for borrowed use or `Cow::into_owned`
when ownership is required.
- **Selection behavior:** `system_prompt()` selects top-level
instructions, otherwise the first system/developer item;
`last_user_message()` selects the last user item; `response_text()`
selects current output. All collect eligible text/refusal parts, without
skipping a selected textless item.
- **Python:** existing text helpers continue to return `str | None` and
inherit the multipart selection behavior.
- **Rust adaptive enum:** exhaustive matches on `BlockContentType` must
handle the new `StructuredInput` and `Opaque` variants.
- **Adaptive persistence:** upgraded agents warm up from fresh samples
under the versioned namespace.
- Normalized type schemas/serialization contracts and codec traits are
unchanged; decoded values now retain the refusal content described
above. Existing provider normalization can still combine text blocks,
including Anthropic, and the views expose the representation available
today.

Live streaming extraction APIs, general mutable/redaction APIs, broader
binding APIs, comprehensive decoder fidelity changes, and allocation
benchmark targets remain outside this PR.

**Validation**

- After merging `main` at PR revision `6bd64dc9c`, `just test-rust`
passed 6,771 tests with 4 skipped. All 71 focused managed-worker tests
also passed.
- The local Go suite passed after the C and Go bindings landed. Earlier
local Python, Node.js, and documentation suites passed. [CI results on
the original PR at this
revision](https://github.com/NVIDIA/NeMo-Relay/pull/1730/checks)
- At documentation revision `d6afa9016`, the staged documentation checks
passed. The dependency audit flagged the existing `wcmatch` 11.0
lockfile entry.
[GHSA-53pm-wgxf-c6qf](GHSA-53pm-wgxf-c6qf)

Regression coverage includes all built-in provider fixtures, borrowed
versus owned text, normalized locations and serialization, native
request fallbacks, multipart/refusal ordering, tool-only/textless
selections, buffered/streamed refusal parity, stream
completion/cancellation races, consumer-specific projection policies,
typed adaptive identity, unknown media token costs, persistence
isolation, and cache hints applied to unchanged original provider
content.

#### Where should the reviewer start?

1. [Shared content
API](https://github.com/NVIDIA/NeMo-Relay/blob/09117da4decd987bd01f4ae371f1d6e1d494baed/crates/types/src/codec/content.rs)
and [content-view
tests](https://github.com/NVIDIA/NeMo-Relay/blob/09117da4decd987bd01f4ae371f1d6e1d494baed/crates/types/tests/content_views.rs):
selection, borrowing, typed payloads, and extraction boundaries.
2. [Provider fixture
coverage](https://github.com/NVIDIA/NeMo-Relay/blob/09117da4decd987bd01f4ae371f1d6e1d494baed/crates/codecs/tests/content_views.rs),
[refusal
regressions](https://github.com/NVIDIA/NeMo-Relay/blob/09117da4decd987bd01f4ae371f1d6e1d494baed/crates/codecs/tests/refusal_content.rs),
then the three changed provider implementations and worker observation.
3. Consumer adoption in ATIF, OpenInference, and PII projection: check
their intentionally different display/privacy policies.
4. [Adaptive IR
builder](https://github.com/NVIDIA/NeMo-Relay/blob/09117da4decd987bd01f4ae371f1d6e1d494baed/crates/adaptive/src/acg/ir_builder.rs),
its tests, token estimation, and persisted-state versioning.
5. [Codec migration
documentation](https://github.com/NVIDIA/NeMo-Relay/blob/09117da4decd987bd01f4ae371f1d6e1d494baed/docs/integrate-into-frameworks/provider-codecs.mdx)
and the adaptive/observability/PII documentation for externally visible
behavior.
6. [Owned snapshot and shared
selection](https://github.com/NVIDIA/NeMo-Relay/blob/09117da4decd987bd01f4ae371f1d6e1d494baed/crates/types/src/codec/content_snapshot.rs),
[worker wire
conversions](https://github.com/NVIDIA/NeMo-Relay/blob/09117da4decd987bd01f4ae371f1d6e1d494baed/crates/worker-proto/src/conversions/content.rs),
and [Go binding
tests](https://github.com/NVIDIA/NeMo-Relay/blob/09117da4decd987bd01f4ae371f1d6e1d494baed/go/nemo_relay/content_test.go)
for the cross-language contract.

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

- Relates to: Support "text" extraction APIs — implemented for buffered
normalized content and existing delegated helpers. No issue number was
supplied, so no automatic closing reference is added.
- Relates to: PII redaction from codec traits + APIs — groundwork and
existing projection fixes only; the general redaction/editing API
remains open.


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

## Summary by CodeRabbit

* **New Features**
* Added normalized content views across Rust, Python,
Node.js/TypeScript, C, and Go, with typed parts, selection helpers, and
owned snapshots.
* Added host-backed content inspection for worker plugins, including
Python worker helpers.
* **Bug Fixes**
* Cache planning now stops when token counts are unavailable for media
or opaque content.
* Improved preservation of OpenAI refusal content, response metadata,
and partial streaming output; invalid or incomplete streams are reported
more accurately.
* Redaction and observability better preserve text/refusal boundaries,
and adaptive state now uses a versioned namespace.
* **Documentation**
* Added guides for normalized content access, worker inspection, and
codec behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Bryan Bednarski <[email protected]>

This branch was previously deployed

1 inactive deployment
fern — 09117da4 Deployed Nov 22, 2026 by copy-pr-bot[bot] via Preview docs #7531
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking PR introduces a breaking change Feature a new feature lang:go PR changes/introduces Go code lang:js PR changes/introduces Javascript/Typescript code lang:python PR changes/introduces Python code lang:rust PR changes/introduces Rust code size:XXL PR is very large

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants