# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-provenance-labeled-context-segment-instead-of-merely-redacting-it-taint-join-collapse-at-dynamic-sink-policy-bounda.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-provenance-labeled-context-segment-instead-of-merely-redacting-it-taint-join-collapse-at-dynamic-sink-policy-bounda.warrant.json
# Markdown SHA-256:   36ae2905d08be5753f04a653264c9b8facd4c24de129cd36f769d5f481d975db
# Code AST SHA-256:   12c4327ee543516df862261d0ed56995ca1cf27a67670909e5ca2f4c14ab5120
# Verified Classes:   TaintJoinViolation, Segment
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

class TaintJoinViolation(RuntimeError):
    """Raised when a composed argument reaches a sink with forbidden taint,
    or when a redaction attempts to clear taint without re-classification."""
    pass

@dataclass(frozen=True)
class Segment:
    seg_id: str
    trust: str                      # "system" | "user" | "external"
    taint: FrozenSet[str] = frozenset()
    quarantined: bool = False
    redacted: bool = False

def join(a: Segment, b: Segment) -> Segment:
    if a.quarantined or b.quarantined:
        # A quarantined operand must not silently degrade to redacted text.
        raise TaintJoinViolation(
            f"join touches quarantined segment(s): "
            f"{[s.seg_id for s in (a, b) if s.quarantined]}"
        )
    return Segment(
        seg_id=f"{a.seg_id}+{b.seg_id}",
        trust="system" if "system" in (a.trust, b.trust) else "external",
        taint=a.taint | b.taint,
        redacted=a.redacted or b.redacted,
    )

FORBIDDEN = {
    "shell.exec": frozenset({"injection", "exfil"}),
    "web.fetch":  frozenset({"exfil"}),
    "memory.write": frozenset({"injection"}),
}

def enforce_sink(sink: str, arg: Segment) -> None:
    # Evaluate the taint bitset FIRST; trust tier is admission, not safety.
    hit = arg.taint & FORBIDDEN.get(sink, frozenset())
    if hit:
        raise TaintJoinViolation(
            f"sink {sink!r} rejected: composed arg {arg.seg_id!r} "
            f"carries forbidden taint {sorted(hit)}; quarantine the "
            f"contributing segment(s) instead of redacting in place."
        )
    if arg.trust != "system" and sink == "shell.exec":
        raise TaintJoinViolation(
            f"sink {sink!r} requires system trust; got {arg.trust!r}"
        )

def redact(seg: Segment, span: str) -> Segment:
    # Redaction preserves taint. Demotion requires a re-classifier record.
    if seg.taint and not seg.redacted:
        raise TaintJoinViolation(
            f"redacting {seg.seg_id!r} would leave taint {sorted(seg.taint)} "
            f"attached to redacted bytes; demote only via audited re-classification."
        )
    return Segment(seg.seg_id, seg.trust, seg.taint, seg.quarantined, redacted=True)

def quarantine(seg: Segment, reason: str) -> Segment:
    return Segment(seg.seg_id, seg.trust, seg.taint, quarantined=True, redacted=seg.redacted)

# --- trace of the observed failure, now blocked ---
sys_seg = Segment("seg_2", "system", frozenset())
web_seg = Segment("seg_7", "external", frozenset({"injection"}))

try:
    arg = join(sys_seg, web_seg)      # trust=system, taint={injection}
    enforce_sink("shell.exec", arg)   # blocked on taint, not trust
except TaintJoinViolation as e:
    # correct response: quarantine seg_7, not redact it
    q = quarantine(web_seg, reason="injection span; sink algebra is trust-only")
    try:
        join(sys_seg, q)              # raises: quarantined operand
    except TaintJoinViolation as e2:
        assert "quarantined" in str(e2)
