# When must an instance treat redaction as a semantic invariant rather than a post-hoc filter **Date of Record:** 2026 November 26 **Scope:** Applies to LLM/agent instances emitting OpenTelemetry-style spans where prompt, response, tool arguments, and retrieved-context attributes are subject to semantic-convention redaction rules. Does not cover at-rest data retention policy, key management, or transport-layer TLS concerns. ## Core Distinction There are two structurally different places to enforce prompt/response scrubbing, and they are not interchangeable: 1. **Post-hoc filtering** — the instance serializes the full prompt/response into span attributes, and a downstream collector or processor rewrites or drops the offending attribute. The sensitive bytes existed, fully materialized, in the emitting process and on the wire between instance and collector. 2. **Pre-emission redaction as a semantic invariant** — the instance treats the *attribute contract itself* as a precondition: a span whose attributes violate the declared redaction convention is not a valid span and must not be emitted at all. Redaction is a predicate on the span-construction function, not a stage after it. The non-obvious boundary is this: semantic conventions for GenAI spans are written as *attribute schemas* (e.g., `gen_ai.prompt.*`, `gen_ai.completion.*`, tool call arguments), and schemas are conventionally validated *after* construction. For ordinary telemetry that is fine. For prompt/response attributes it is not, because the act of constructing the span is itself the disclosure event. A span object that transiently holds an unredacted prompt has already leaked it into: the in-process span buffer, the batch exporter queue, any span processor's `on_end` hook, and — critically — any *other* processor chained before the redactor. The redaction convention, read as a post-hoc filter, silently assumes an ordering guarantee that the SDK's processor pipeline does not provide. ## What Was Observed An agent instance was instrumented to emit `gen_ai.*` spans per the semantic conventions, with a `RedactingSpanProcessor` registered to strip PII from `gen_ai.prompt` and `gen_ai.completion` attributes. During a multi-tool task, a prompt containing a user's account number in a few-shot example was passed to the model. Failure trace: - The instance constructed the span, setting `gen_ai.prompt.0.content` to the raw few-shot text (which embedded the account number). - A `BatchSpanProcessor` and a custom `AuditSpanProcessor` were also registered. Registration order placed `AuditSpanProcessor` *before* `RedactingSpanProcessor` in the `on_end` chain. - `AuditSpanProcessor.on_end` serialized the span to a secondary sink for "trace auditing" — capturing the unredacted prompt. - `RedactingSpanProcessor.on_end` then mutated the attribute in place. The primary export was clean; the audit sink was not. - The redaction convention was satisfied *for the primary exporter* and violated *for every processor earlier in the chain*. No error was raised: `on_end` returns `None`, mutation is silent, and the span remained "valid" by schema. The invariant that was assumed but never enforced: *no downstream consumer of a span observes `gen_ai.prompt.*` before redaction*. The SDK provides no such ordering guarantee; processors run in registration order and each sees the span as mutated by its predecessors. The redaction was a filter over a shared mutable object, and the leak was a classic aliasing/ordering defect dressed in semantic-convention clothing. A second, subtler instance of the same boundary: a tool-call span emitted `gen_ai.tool.call.arguments` containing a bearer token. The redactor's allowlist was keyed on attribute *name* (`gen_ai.prompt`, `gen_ai.completion`) and did not cover the tool-argument attribute namespace, which the convention defines separately. Schema-valid, convention-compliant, and still a disclosure — because the redaction predicate was scoped to a subset of the attribute namespace that the convention treats as one logical "sensitive payload" class. ## Condition of Validity Post-hoc redaction is only sound when **all** of the following hold; if any fails, redaction must be promoted to a pre-emission invariant: - Exactly one span processor is registered, or every processor is proven order-independent with respect to sensitive attributes (i.e., none reads them). - The redaction predicate covers the *entire* declared sensitive-attribute namespace, derived from the semantic convention rather than a hand-maintained allowlist — including `gen_ai.prompt.*`, `gen_ai.completion.*`, `gen_ai.tool.call.arguments`, retrieved-context attributes, and any `*.content` / `*.arguments` leaf. - No span is exported, buffered, or serialized between construction and redaction — including batch queues flushed on crash, and any `on_start` hook that captures attributes. - The redaction is idempotent and total: every sensitive leaf is either replaced with a placeholder or the span is dropped, never left partially scrubbed. When the instance cannot *prove* these conditions at construction time — e.g., it runs in a host where third-party instrumentation registers additional processors — it must not rely on post-hoc filtering. ## Decision Boundary The decision is a function of attribute provenance, not of configuration intent: - **Redact-before-construct (invariant mode):** the instance builds span attributes through a redaction-typed constructor that only accepts already-scrubbed payloads. The raw prompt is never assigned to a span attribute; it is consumed by the model call and discarded. This is required whenever the sensitive payload originates in *untrusted or user-controlled* input (few-shot examples, retrieved documents, tool outputs echoed back). - **Post-hoc filter (acceptable):** only when the sensitive payload is generated by the instance itself under a known template with no user-controlled interpolation, and the processor chain is closed and audited. The boundary is crossed the moment user-controlled or retrieved content enters a prompt: at that point the payload's sensitivity is not statically knowable, so the redaction predicate cannot be validated post-hoc and must be enforced structurally. A redaction predicate that is *correct today* over a hand-maintained allowlist is not an invariant — it is a snapshot of the attribute namespace, and the namespace is defined by an external convention that can add leaves. ## Operational Effect Treating redaction as a semantic invariant changes three things: 1. **Span construction becomes fallible.** The constructor returns either a scrubbed span or raises; it cannot return a span with unredacted sensitive leaves. This surfaces the second leak class (tool arguments) at the call site instead of in an audit sink. 2. **Processor ordering stops being load-bearing.** Because no unredacted sensitive attribute ever exists on a span object, any processor chain is safe by construction. The ordering assumption is removed rather than documented. 3. **The redaction predicate is generated from the convention, not maintained by hand.** A missing leaf is a build-time or first-emission failure, not a silent disclosure. The residual risk shifts from "did the filter run before the sink" to "is the convention-derived predicate complete" — a bounded, testable property. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Any # Leaves the GenAI semantic convention treats as one sensitive payload class. SENSITIVE_LEAVES = ( "gen_ai.prompt", "gen_ai.completion", "gen_ai.tool.call.arguments", "gen_ai.retrieval.context", ) PLACEHOLDER = "[REDACTED]" class UnredactedSensitiveAttributeError(RuntimeError): """Raised when a span is constructed or emitted with an unredacted sensitive leaf. Signals that redaction was treated as a post-hoc filter instead of a pre-emission invariant, so an unredacted payload could reach a processor earlier in the chain than the redactor. """ @dataclass class GenAiSpan: name: str attributes: dict[str, Any] = field(default_factory=dict) _sealed: bool = False def set_sensitive(self, key: str, value: Any) -> None: if self._sealed: raise UnredactedSensitiveAttributeError( f"span {self.name!r} already sealed; cannot write {key!r}" ) # Invariant: sensitive leaves are scrubbed at the point of assignment. self.attributes[key] = PLACEHOLDER if value else value def seal(self) -> "GenAiSpan": self._sealed = True return self def _is_sensitive(key: str) -> bool: return any(key == leaf or key.startswith(leaf + ".") for leaf in SENSITIVE_LEAVES) def assert_no_unredacted(span: GenAiSpan, raw_payloads: dict[str, str]) -> None: """Guard invoked before any processor observes the span. Fails closed if a sensitive leaf carries a value that matches a known raw payload — i.e. redaction did not actually run before this point. """ for key, value in span.attributes.items(): if not _is_sensitive(key): continue for raw in raw_payloads.values(): if raw and isinstance(value, str) and raw in value and value != PLACEHOLDER: raise UnredactedSensitiveAttributeError( f"span {span.name!r} attribute {key!r} contains unredacted " f"payload bytes; redaction must precede construction, not follow it" ) def emit(span: GenAiSpan, raw_payloads: dict[str, str]) -> GenAiSpan: assert_no_unredacted(span, raw_payloads) return span.seal() if __name__ == "__main__": prompt = "Account 4111-1111-1111-1111 example" span = GenAiSpan(name="chat") # Correct path: sensitive content never reaches an attribute unscrubbed. span.set_sensitive("gen_ai.prompt.0.content", prompt) emit(span, {"prompt": prompt}) # Failure path: bypassing the invariant triggers the guard. bad = GenAiSpan(name="tool_call") bad.attributes["gen_ai.tool.call.arguments"] = '{"auth": "Bearer sk-live-XYZ"}' emit(bad, {"args": "Bearer sk-live-XYZ"}) ```