# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-redaction-pipelines-from-silently-breaking-semantic-convention-compliant-trace-sampling.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-redaction-pipelines-from-silently-breaking-semantic-convention-compliant-trace-sampling.warrant.json
# Markdown SHA-256:   69d30fc69d74893dbb2c0a28c65f92ecb29122846f35717550309f76b194f981
# Code AST SHA-256:   81a94fe9318247f3773babda7e6f7b122f9d3e4201d4550ba0bf4ddd11b5cfab
# Verified Classes:   RedactionSamplingContractError, RedactionStage, SamplingPolicy
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class RedactionSamplingContractError(RuntimeError):
    """Raised when a redaction stage mutates attributes the sampler reads."""


@dataclass(frozen=True)
class RedactionStage:
    name: str
    # Attributes whose *semantic property* the sampler may depend on.
    writes: FrozenSet[str]
    # Attributes the stage guarantees to preserve verbatim in meaning.
    preserves: FrozenSet[str] = field(default_factory=frozenset)


@dataclass(frozen=True)
class SamplingPolicy:
    name: str
    # Attributes the policy reads to make a keep/drop decision.
    reads: FrozenSet[str]


def assert_redaction_sampling_invariant(
    redaction: RedactionStage,
    policies: list[SamplingPolicy],
) -> None:
    """
    Enforce that no sampling policy reads an attribute that redaction
    mutates without an explicit preservation contract.

    Ordering assumption: redaction runs BEFORE sampling in the processor
    chain. If sampling runs first, pass policies=[] here and validate the
    persisted-decision path instead.
    """
    for policy in policies:
        violated = (policy.reads & redaction.writes) - redaction.preserves
        if violated:
            raise RedactionSamplingContractError(
                f"redaction stage '{redaction.name}' mutates "
                f"{sorted(violated)} which sampling policy "
                f"'{policy.name}' reads, without a preservation contract; "
                f"sampling will be silently biased. Either reorder the "
                f"pipeline, add these attributes to redaction.preserves, "
                f"or key the policy on redaction-invariant attributes."
            )


def build_pipeline(
    redaction: RedactionStage, policies: list[SamplingPolicy]
) -> None:
    assert_redaction_sampling_invariant(redaction, policies)
    # ... construct processor chain only after invariant holds ...


# The observed failure, reproduced as a startup-time rejection:
_observed_redaction = RedactionStage(
    name="pii_message_scrubber",
    writes=frozenset(
        {"gen_ai.completion", "gen_ai.tool.call", "gen_ai.usage.output_tokens"}
    ),
    preserves=frozenset({"gen_ai.completion"}),  # tool.call NOT preserved
)
_observed_policies = [
    SamplingPolicy(
        name="tool_call_always_retain",
        reads=frozenset({"gen_ai.tool.call", "gen_ai.usage.output_tokens"}),
    ),
    SamplingPolicy(
        name="error_always_retain",
        reads=frozenset({"error.type"}),
    ),
]

if __name__ == "__main__":
    build_pipeline(_observed_redaction, _observed_policies)
