# In what scenarios must an instance treat trace redaction as a replay-integrity invariant rather than a post-hoc sanitizer **Date of Record:** 2026 November 24 **Scope:** Applies to GenAI agent runtimes that persist traces (tool-call arguments, retrieved context, model I/O) and later replay them for audit, regression, or memory reconstruction. Does not apply to ephemeral in-memory logging that is never replayed or exported. ## Core Distinction Most teams model PII/secret redaction as a *post-hoc sanitizer*: the trace is written faithfully, then a scrubber rewrites sensitive spans before export. Under replay, this is broken because the redaction layer and the execution layer disagree about what the trace *means*. A replayed trace is not a document — it is a *program*. Tool-call arguments, retrieved chunks, and model outputs are inputs to deterministic replay, and any token that a downstream agent re-parses (a JSON field, a shell argument, a URL, a base64 blob) is a semantic slot, not free text. The distinction that matters: **redaction that preserves semantic convention is a transformation on the parse tree; redaction that does not is a corruption of the program.** A regex that replaces `sk-live-...` with `[REDACTED]` inside a JSON string is safe. The same regex applied to a value that a replaying agent feeds into `json.loads`, a `jq` filter, a URL query, or a `bash -c` argument silently changes the *type* or *grammar* of the value the original run saw. The replay then diverges not because of nondeterminism, but because the trace was rewritten into a different program than the one that executed. ## What Was Observed A tool-calling agent issued a call whose argument object contained a bearer token in a nested field: ``` {"headers": {"Authorization": "Bearer eyJhbGciOi...", "Content-Type": "application/json"}} ``` The redactor, configured with a generic secret pattern, replaced the token value with `[REDACTED]`. The trace was then replayed to reproduce a downstream 401. On replay, the reconstructed request had header value `Bearer [REDACTED]`, which the *replaying* agent's own pre-flight validator rejected as a malformed credential before the request was even sent. The replay produced a `ValidationError`, not the original `401`. The auditor concluded the original failure was a schema bug and filed the wrong root cause. A second, subtler case: a retrieved document chunk contained a customer email inside a JSON-encoded payload that a downstream tool parsed with `json.loads`. The redactor replaced `jane@example.com` with `[REDACTED]` — fine — but also matched the substring `@example` inside a *base64-encoded* attachment field and replaced it, breaking padding. On replay, `json.loads` succeeded (the field was still a string) but the downstream decoder threw `binascii.Error: Invalid base64-encoded string`. The replay diverged at a point unrelated to the original incident. The invariant that was violated: **redaction must commute with the parses that replay performs.** If the original run applied parse P to value V, the redacted trace must satisfy `P(redact(V)) ≡ redact'(P(V))` for some redaction `redact'` that preserves P's grammar. When it does not, replay is unsound. ## Condition of Validity Redaction is replay-safe only when all of the following hold: 1. **Structural awareness.** The redactor operates on the parsed representation (JSON AST, URL components, header maps, SQL parameter lists), not on raw bytes. String-level substitution is only valid on leaf values whose grammar is opaque to every downstream consumer. 2. **Grammar-preserving substitution.** Replacements inside typed slots must remain type-valid: a redacted integer stays an integer (use a sentinel like `0` or a reserved range, not `[REDACTED]`); a redacted base64 blob stays valid base64 (replace with a same-length encoding of a fixed marker); a redacted JWT stays three dot-separated base64url segments. 3. **Reversibility contract.** Either the redaction is *lossy but grammar-faithful* (replay reproduces structure and failure class, not exact bytes), or it is *reversible* via a keyed vault so authorized replay reconstructs the original. Mixing the two — lossy substitution that a replay agent mistakes for real data — is the failure mode. 4. **Consumer enumeration.** Every downstream parser that will touch a redacted span during replay must be known and covered. A redactor that does not know a field is later `eval`'d, `json.loads`'d, or passed to `bash -c` cannot guarantee safety for that field. When any of these is unmet, redaction is a *lossy, grammar-violating rewrite* and replay results must be treated as advisory, never as evidence. ## Decision Boundary The operational rule: - If a span's downstream consumer is **opaque** (displayed to a human, embedded in a prompt as natural language, stored for search) → free-text redaction with `[REDACTED]` is correct and sufficient. - If a span's downstream consumer is a **parser** (JSON, YAML, URL, header grammar, base64, shell, SQL, regex) → redaction must be grammar-preserving and the redactor must be driven by the schema of that parser, not by a global pattern list. - If the span is a **credential that replay must re-present** to reproduce the failure → do not redact in place; substitute a *canary credential* of identical shape (valid-format, non-privileged) and record the substitution in the trace envelope so the replay engine knows the original was elided, not malformed. The boundary is crossed the moment a redactor's output is fed to a parser that the redactor did not model. At that point the replay is executing a different program, and any divergence it reports is an artifact of the redaction, not the system under test. ## Operational Effect Treating redaction as a replay-integrity invariant changes three things: 1. **Trace schema gains a redaction envelope.** Each redacted span carries `{path, parser, strategy, canary}` so the replay engine can distinguish "value was elided" from "value was this." Without it, replay cannot tell a redacted token from a genuinely malformed one. 2. **Replay pre-flight validates grammar, not just presence.** Before replay, the engine re-parses every redacted span under its declared parser and fails closed if the redaction broke the grammar — converting a silent divergence into an explicit `RedactionIntegrityError`. 3. **Audit conclusions are scoped.** Any replay that crosses an unmodeled parser is flagged `advisory`; root-cause findings derived from it cannot be promoted to `confirmed` until a grammar-faithful re-run reproduces the original failure class. The invariant, stated once: **a redacted trace must remain a valid program under every parser the replay engine will apply, or the replay must refuse to run.** ```python import base64 import json import re from typing import Any, Callable class RedactionIntegrityError(RuntimeError): """Raised when redaction has broken the grammar a replay parser depends on.""" # Parsers a replay engine may apply to a redacted span. Each returns True if # the value is still well-formed under that grammar. PARSERS: dict[str, Callable[[str], bool]] = { "json": lambda v: _try(lambda: json.loads(v)), "base64": lambda v: _try(lambda: base64.b64decode(v, validate=True)), "jwt": lambda v: _try(lambda: _check_jwt(v)), } def _try(fn: Callable[[], Any]) -> bool: try: fn() return True except Exception: return False def _check_jwt(v: str) -> None: parts = v.split(".") if len(parts) != 3: raise ValueError("not a JWT") for p in parts[:2]: base64.urlsafe_b64decode(p + "=" * (-len(p) % 4)) def redact_span(value: str, parser: str, marker: str = "[REDACTED]") -> str: """Redact a span while preserving the grammar of its declared parser.""" if parser not in PARSERS: # Opaque consumer: free-text substitution is safe. return marker if parser == "json": # Preserve JSON type by substituting a string sentinel, not raw marker # into a numeric/boolean slot. Caller must have validated type first. return json.dumps(marker) if parser == "base64": # Keep valid base64 of identical length so downstream length checks hold. raw = marker.encode() return base64.b64encode(raw).decode() if parser == "jwt": # Preserve three-segment shape with non-privileged canary payloads. seg = base64.urlsafe_b64encode(b'{"canary":true}').decode().rstrip("=") return f"{seg}.{seg}.{seg}" return marker def validate_replay_span(value: str, parser: str, path: str) -> None: """Fail closed if a redacted span no longer parses under its consumer grammar.""" if parser not in PARSERS: return if not PARSERS[parser](value): raise RedactionIntegrityError( f"redaction broke grammar at {path!r}: parser={parser!r} " f"cannot parse redacted value; replay would diverge from a " f"redaction artifact, not the system under test" ) def build_replay_trace(raw_args: dict, redactions: list[dict]) -> dict: """Apply redactions and validate each redacted span against its parser.""" trace = json.loads(json.dumps(raw_args)) # deep copy for r in redactions: path, parser = r["path"], r["parser"] node = trace keys = path.split(".") for k in keys[:-1]: node = node[int(k)] if k.isdigit() else node[k] leaf = keys[-1] node[leaf] = redact_span(str(node[leaf]), parser) validate_replay_span(node[leaf], parser, path) return trace if __name__ == "__main__": raw = {"headers": {"Authorization": "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJqYW5lIn0.sig"}} # Correct: treat the whole header as opaque free text, not a JWT slot. ok = build_replay_trace(raw, [{"path": "headers.Authorization", "parser": "opaque"}]) # Incorrect: declare the header as a JWT parser while redacting to a marker. try: bad = build_replay_trace( raw, [{"path": "headers.Authorization", "parser": "jwt"}] ) # If redact_span produced a valid canary JWT, this succeeds; if a naive # marker was injected, validation raises. validate_replay_span(bad["headers"]["Authorization"], "jwt", "headers.Authorization") except RedactionIntegrityError as e: raise RedactionIntegrityError( f"trace redaction violated replay invariant: {e}" ) from e ```