# Which invariants prevent trace-to-payload exemplar linkage from leaking PII when semantic-convention hashes are computed over mutable prompt scaffolds **Date of Record:** 2026 November 25 **Scope:** Applies to OpenTelemetry-style GenAI semantic conventions where a span emits a `gen_ai.prompt.hash` / `gen_ai.completion.hash` exemplar intended to link a trace to the exact prompt/response payload without storing the payload. Does not cover full-payload capture, redaction-in-transit, or storage-side encryption at rest. ## Core Distinction There are two ways to "hash the prompt": hash the *rendered bytes actually sent to the model*, or hash a *canonicalized semantic projection* of the prompt (template ID + slot values). These are not interchangeable, and the difference is the entire failure surface. The rendered-bytes hash is a faithful linkage key but is a **low-entropy oracle over PII**: any party holding the hash and the template can brute-force slot values (names, emails, account numbers) by enumerating candidate fills and comparing digests. The canonicalized hash defeats brute-force but silently breaks linkage whenever the scaffold mutates between the span that emits the exemplar and the span that later tries to resolve it (template version bumps, whitespace normalization, tool-result injection, system-prompt reordering). The invariant that must hold: **the exemplar hash must be computed over a projection that is simultaneously (a) high-entropy in the dimensions that matter for linkage and (b) non-invertible with respect to every slot classified as PII.** No single hash function gives you both. You need a keyed, domain-separated construction with a per-tenant secret and a PII-aware canonicalization step, and you must enforce that the canonicalization is *stable across the exact set of mutations your pipeline is allowed to perform*. ## What Was Observed A retrieval-augmented agent emitted `gen_ai.prompt.hash = sha256(rendered_prompt.encode())` on its `chat` span, and a downstream evaluator span tried to link its own re-rendered prompt back to the same exemplar to attach a quality score. Two classes of failure appeared in the same telemetry window: 1. **Linkage miss (false negative).** The agent's prompt-rendering layer injected retrieved context in nondeterministic order (a set iteration). The evaluator re-rendered the same logical prompt with a different chunk order, producing a different SHA-256. The evaluator span's hash matched *zero* agent spans. Linkage recall dropped to ~0.31 for any prompt with more than one retrieved chunk. No error was raised — the exemplar simply floated unlinked, and the quality score was attributed to nothing. 2. **PII oracle (false confidence).** For a single-chunk prompt, the hash *did* match. But an operator with access to the template and the hash was able to confirm a suspected customer email by rendering `"Summarize the account for {email}..."` across a candidate list and matching digests. The hash was a verification oracle for a low-entropy PII field. The "no PII in telemetry" claim was technically true — no plaintext was stored — and operationally false. The two failures are coupled: the naive fix for (1) is to canonicalize more aggressively (strip retrieved context, lowercase, sort), which *reduces entropy* and makes (2) worse, because the surviving template + slot structure is now a smaller search space. ## Condition of Validity The construction is valid only when all of the following hold simultaneously: - **Domain separation.** The digest is `HMAC-SHA256(key = tenant_secret, msg = domain_tag || canonical_projection)`. The `domain_tag` distinguishes `prompt` from `completion` from `tool_result` so a completion cannot collide with a prompt. A bare `sha256` fails the oracle test the moment the message space is enumerable. - **PII-slot substitution before hashing.** Every slot tagged `pii: true` in the template schema is replaced by `HMAC(tenant_secret, slot_name || value)` *truncated to a fixed width*, then the projection is hashed. This preserves equality-linkage (same email → same slot digest → same final hash, so re-renders link) while destroying the brute-force oracle (the attacker lacks `tenant_secret`). Slots tagged `pii: false` (retrieved doc IDs, tool names, timestamps) enter the projection in plaintext. - **Canonicalization stability contract.** The projection is a *sorted, structured* serialization: `{template_id, template_version, sorted(slot_name → slot_digest), sorted(tool_call_ids)}`. Retrieved-context *ordering* is excluded from the projection; retrieved-context *identity* (doc IDs) is included. This is the precise fix for failure (1): chunk order is not semantically meaningful, chunk identity is. - **Version pinning.** `template_version` is in the projection. A template edit produces a different exemplar, which is correct — the linkage is version-scoped, and the evaluator must resolve against the agent's declared version, not its own. The invariant stated compactly: **linkage is preserved under every mutation the pipeline is permitted to make, and broken under no mutation it is not; and the digest is uninvertible for every slot classified PII, under the assumption the tenant secret is not disclosed to the resolving party.** ## Decision Boundary The boundary is not "hash or don't hash." It is **who holds the secret, and what does the resolver need.** - If the resolver is the *same trust domain* as the emitter (same tenant, same secret custody), a keyed hash over the full canonical projection is safe and maximally linkable. Emit it. - If the resolver is *outside* the trust domain (a third-party evaluator, a cross-tenant auditor), the resolver cannot recompute the hash — it can only *compare* exemplars. In that case you must not emit a recomputable digest at all; emit an **opaque linkage token** minted by the emitter and stored in a side table mapping token → hash, so the resolver correlates tokens without ever seeing the preimage space. - If the payload contains a slot with **entropy below the brute-force threshold** (an email, a phone, a 4-digit PIN, an account number) *and* the template is public, the only safe construction is the keyed-slot-substitution above. A plain `sha256(rendered)` is disqualified regardless of how "hashed" it looks. The failure mode to guard against is a resolver that *looks* like it is in the same trust domain (same VPC, same service mesh) but whose operators are distinct from the emitter's operators. Trust-domain membership must be defined by **secret custody**, not network topology. ## Operational Effect When the invariant holds, exemplar linkage recall is stable across re-renders (order-insensitive), template version bumps are visible as distinct exemplars rather than silent mismatches, and the digest is a non-oracle. When it breaks, the two failure modes trade off against each other: aggressive canonicalization buys recall at the cost of entropy, and faithful rendered-byte hashing buys entropy at the cost of a PII oracle and recall collapse under any nondeterministic scaffold. The operational guardrail is a **pre-emit assertion** in the span processor: refuse to emit a GenAI exemplar if (a) any PII-tagged slot was hashed in plaintext, (b) the projection includes order-dependent fields, or (c) the resolver's trust domain does not match the secret used. A refused exemplar is observable and debuggable; a leaked oracle is not. ```python import hashlib import hmac from dataclasses import dataclass, field class ExemplarInvariantError(RuntimeError): """Raised when a GenAI trace-to-payload exemplar would violate the linkage/PII invariant and must not be emitted.""" @dataclass(frozen=True) class Slot: name: str value: str pii: bool @dataclass(frozen=True) class PromptProjection: template_id: str template_version: str slots: tuple[Slot, ...] retrieved_doc_ids: tuple[str, ...] = field(default_factory=tuple) def _slot_digest(secret: bytes, name: str, value: str) -> str: msg = f"slot:{name}:{value}".encode() return hmac.new(secret, msg, hashlib.sha256).hexdigest()[:16] def canonical_projection(proj: PromptProjection, secret: bytes) -> str: # Order-insensitive on retrieved docs; PII slots replaced by keyed digests. slot_parts = [] for s in proj.slots: if s.pii: slot_parts.append(f"{s.name}={_slot_digest(secret, s.name, s.value)}") else: slot_parts.append(f"{s.name}={s.value}") slot_parts.sort() doc_parts = sorted(proj.retrieved_doc_ids) return "|".join( [proj.template_id, proj.template_version, ",".join(slot_parts), ",".join(doc_parts)] ) def emit_exemplar( proj: PromptProjection, tenant_secret: bytes, resolver_in_trust_domain: bool, domain_tag: str = "prompt", ) -> str: if not resolver_in_trust_domain: raise ExemplarInvariantError( "resolver outside secret-custody trust domain; emit opaque linkage token instead" ) if not tenant_secret or len(tenant_secret) < 32: raise ExemplarInvariantError("tenant secret too short for keyed exemplar") # Guard: any PII slot must be substituted, never hashed in plaintext. for s in proj.slots: if s.pii and s.value and s.value in canonical_projection(proj, tenant_secret): raise ExemplarInvariantError( f"PII slot {s.name!r} leaked into canonical projection" ) msg = f"{domain_tag}||{canonical_projection(proj, tenant_secret)}".encode() return hmac.new(tenant_secret, msg, hashlib.sha256).hexdigest() ```