Tracing and Observability for AI Systems › Privacy-Aware Retention and Structured Redaction

Michael BrenndoerferDecember 2, 20266 min read
Language AI HandbookAll chapters
Part 64 of 67Compound AI System Design
Chapter 488Tracing and Observability for AI Systems › Privacy-Aware Retention and Structured Redaction
Reading section 7 of 10 · Privacy-Aware Retention and Structured Redaction · 6 minSection 7 of 10 · 6 min

Section 7 of 10 · 6 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Traces are a privacy hazard by construction. A single prompt payload can contain the user's question, retrieved documents (which may include personal data), and system instructions. Tool payloads can contain credentials and customer records. Yet the same payloads are what make traces useful for debugging. The resolution is not to choose between utility and privacy but to classify fields and apply per-field policy: redact with structure rather than dumping raw text.

The approach has three parts. First, schema-first tracing: declare which fields are safe attributes and which are sensitive payloads, so redaction is not an afterthought applied to opaque strings but a policy over typed fields. Second, structured redaction: replace sensitive values with typed placeholders keyed by category (for example <EMAIL:hmac-3f2a>), preserving a type label and, when needed, a scoped equality tag so the trace remains useful for debugging (you can see that an email was present and that it was the same email across two spans, without seeing it). Third, retention tiers: raw payloads expire quickly (hours to days) while aggregates, IDs, and redacted traces persist longer. This is the trace-level analog of the PII removal strategies from PII Removal.

Schema-first tracing is the part most often skipped and the part that matters most. If payloads are opaque strings, redaction becomes a best-effort scan over free text, and any pattern the scanner misses leaks in full. If instead the schema says "this field is a document body, this field is a tool argument named email, this field is a model name," redaction becomes a policy that can be exhaustive and auditable per field. The schema also makes access control enforceable: you can grant a support engineer access to attributes and redacted payloads without granting access to raw payloads at all.

Detecting and redacting sensitive fields

The next cell illustrates string replacement on wholly fictional text. It recognizes particular email and phone formats and an invented secret marker. A match is a pattern hit. The demonstration does not establish that other sensitive strings will be caught.

PythonIn [27]
CollapseExpand
import hmac
import re

REDACTION_KEY = (
    b"trace-redaction-key-demo"  # in production: from a secrets manager
)

PATTERNS = {
    "EMAIL": re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+"),
    "PHONE": re.compile(r"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b"),
    "APIKEY": re.compile(r"\bfixture-key-[A-Za-z0-9]{8,}\b"),
}


def _hmac_tag(value: str) -> str:
    return hmac.new(
        REDACTION_KEY, value.encode("utf-8"), hashlib.sha256
    ).hexdigest()[:24]


def redact_text(text: str) -> tuple[str, dict[str, int]]:
    counts: dict[str, int] = {}
    for label, pat in PATTERNS.items():

        def repl(m: re.Match, _label=label) -> str:
            counts[_label] = counts.get(_label, 0) + 1
            if _label == "APIKEY":
                return "<SECRET>"
            return f"<{_label}:{_hmac_tag(m.group(0))}>"

        text = pat.sub(repl, text)
    return text, counts
ConsoleOut [28]
CollapseExpand
Original : Contact jane.doe@example.com or 555-123-4567; key fixture-key-9f8e7d6c.
Redacted : Contact <EMAIL:ba8a6cb4f04f91aec4bde5ab> or <PHONE:897923b2c3da46c19da560cf>; key <SECRET>.
Counts   : {'EMAIL': 1, 'PHONE': 1, 'APIKEY': 1}

The same exact email string produces the same keyed tag under one key. Different strings can collide because the tag is truncated, and equal tags let a reader link records. The fictional secret marker uses a constant placeholder because it needs no linking tag.

Applying structured redaction to the trace payloads

A routine export can use a whitelist of typed fields and discard everything else before handing the record to a storage or transport queue. The following example opts into one approved field containing a structured balance class. It also illustrates pattern substitution on a fictional preview, which we keep outside the routine export.

PythonIn [29]
CollapseExpand
def export_tool_span(span: Span) -> dict[str, Any]:
    """Export only approved status and balance classes from this fixture."""
    record = {"schema_version": 1, "operation": "get_balance"}
    status = span.attributes.get("status_code")
    if type(status) is int and status in {200, 403, 503}:
        record["status_code"] = status
    balance_class = span.payload.get("balance_class")
    if type(balance_class) is str and balance_class in {
        "positive",
        "zero",
        "negative",
    }:
        record["balance_class"] = balance_class
    return record
ConsoleOut [30]
CollapseExpand
Approved tool fields: {'schema_version': 1, 'operation': 'get_balance', 'status_code': 200, 'balance_class': 'positive'}

The nested account entry and the original payload are absent from the export. The allowlist applies to values as well as keys. A new field or value needs an explicit schema decision.

Retention tiers

Redaction reduces but does not eliminate risk: a redacted trace still contains structural information, and placeholders leak whether a value was present. Combine redaction with time-based retention tiers. The following configuration describes what to keep and for how long. Selected attributes can be retained for analysis under policy; redacted payloads are kept for a short debugging window; raw payloads are never persisted at all.

Attributes can link records to people or tenants. Apply retention and access controls to approved fields, including identifiers, and review what those fields expose when joined with other records. Redacted payloads retain structure and can still support linkage. The example discards raw payloads at ingest and gives redacted payloads a 72-hour limit. Set an investigative window using how long it takes to detect and respond to incidents, and check which evidence will remain accessible at that point.

PythonIn [31]
CollapseExpand
RETENTION_POLICY = {
    "raw_payload": {
        "ttl_hours": 0,
        "note": "never persisted; redacted at ingest",
    },
    "redacted_payload": {"ttl_hours": 72, "note": "debugging window"},
    "attributes": {"ttl_hours": 24 * 90, "note": "aggregate analysis"},
    "aggregates": {"ttl_hours": 24 * 365, "note": "dashboards and trends"},
}


def should_keep(field_class: str, age_hours: float) -> bool:
    ttl = RETENTION_POLICY[field_class]["ttl_hours"]
    return 0 <= age_hours < ttl
ConsoleOut [32]
CollapseExpand
raw_payload        keep@1h=False keep@30d=False
redacted_payload   keep@1h=True  keep@30d=False
attributes         keep@1h=True  keep@30d=True
aggregates         keep@1h=True  keep@30d=True

The fixture retains redacted payloads after one hour and expires them at 72 hours. After that, the selected attributes and aggregates each remain until their own expiry, at 90 and 365 days respectively. If you rely on stored IDs for a controlled replay, check that the historical input and component versions still exist and that investigators are authorized to retrieve them.

Redaction is not anonymization

A keyed HMAC placeholder can retain equality within the tag’s scope. A service with the key can test a guessed value, and repeated tags can reveal frequencies even when the original value stays hidden. Review that linkage when deciding whether to retain tags. Differential Privacy discusses an approach to protecting released aggregate statistics.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy