# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-taint-label-after-tool-call-sanitization-rather-than-propagate-it-to-downstream-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-taint-label-after-tool-call-sanitization-rather-than-propagate-it-to-downstream-tool-calls.warrant.json
# Markdown SHA-256:   f277c5ebebf6f8e9820212a2056b7f6646731b38d9d1c30727f59df5ac01b77b
# Code AST SHA-256:   95e51b4be8d8c5e73b7ee4b6cf5b5adebc9d188a4499f956d255a04b3ae8e463
# Verified Classes:   TaintInvalidationError, SlotTaint
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class TaintInvalidationError(RuntimeError):
    """Raised when taint invalidation is attempted without a valid re-grounding witness,
    or when invalidation would leak across sibling argument slots."""
    pass


class SlotTaint:
    def __init__(self, slot: str, sources: set[str], witness: str | None = None):
        self.slot = slot
        self.sources = sources          # provenance set
        self.witness = witness          # trusted-origin witness ID, if any

    @property
    def is_tainted(self) -> bool:
        return bool(self.sources) and self.witness is None


def invalidate_slot_taint(
    slot: SlotTaint,
    claimed_witness: str | None,
    witness_registry: dict[str, str],   # witness_id -> trusted_origin
    call_siblings: list[SlotTaint],
) -> SlotTaint:
    if not slot.sources:
        # Nothing to invalidate; slot was never tainted.
        return slot

    if claimed_witness is None:
        raise TaintInvalidationError(
            f"slot {slot.slot!r} has tainted provenance {slot.sources} "
            f"but no re-grounding witness was supplied; propagate, do not invalidate"
        )

    if claimed_witness not in witness_registry:
        raise TaintInvalidationError(
            f"slot {slot.slot!r} cited unknown witness {claimed_witness!r}; "
            f"model-asserted safety is not a witness"
        )

    # Sibling leakage check: invalidation must not silently clear co-emitted slots.
    for sib in call_siblings:
        if sib is slot:
            continue
        if sib.witness == claimed_witness and sib.sources:
            raise TaintInvalidationError(
                f"witness {claimed_witness!r} cited for slot {slot.slot!r} also "
                f"appears on tainted sibling {sib.slot!r}; invalidation is not "
                f"slot-scoped and would leak provenance"
            )

    return SlotTaint(slot=slot.slot, sources=set(), witness=claimed_witness)


def sanitize_tainted_slot(slot: SlotTaint, value: str, grammar: str) -> str:
    """Scoped sanitization. Never promotes a tainted slot to clean."""
    if not slot.is_tainted:
        return value
    if grammar == "free_text":
        raise TaintInvalidationError(
            f"slot {slot.slot!r} is tainted and free-text; cannot scope sanitization, "
            f"block and force structured re-emission"
        )
    # Typed grammars (uuid, enum, iso8601, int) reduce surface but do not re-ground.
    import re
    patterns = {
        "uuid": r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
        "enum": r"[A-Z_]{2,32}",
        "int": r"-?\d{1,18}",
    }
    pat = patterns.get(grammar)
    if pat is None or not re.fullmatch(pat, value):
        raise TaintInvalidationError(
            f"slot {slot.slot!r} value does not conform to declared grammar {grammar!r}; "
            f"residual taint suspected"
        )
    return value
