# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-redaction-as-a-semantic-invariant-rather-than-a-post-hoc-filter.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-redaction-as-a-semantic-invariant-rather-than-a-post-hoc-filter.warrant.json
# Markdown SHA-256:   3c71be5f3b941b18217d2d00ca94a6163aeaac3c8eac9f9f9526c3aa81a0066e
# Code AST SHA-256:   6226e6282a727cda9f3f826e082f23c330fb21096b8cb464e9e414db320322b9
# Verified Classes:   UnredactedSensitiveAttributeError, GenAiSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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"})
