# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-prompt-injection-taint-tracking-with-provenance-labels-fail-at-the-label-relabeling-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-prompt-injection-taint-tracking-with-provenance-labels-fail-at-the-label-relabeling-boundary.warrant.json
# Markdown SHA-256:   8b0c8596f280fe49190792cd83b29dc0ce6d04426c2fe0c44e50bd8d9a039416
# Code AST SHA-256:   4ba1f406b417853469e764f3f20c8695a599967cb7e23fc98221acbfc480e287
# Verified Classes:   ProvenanceDiscontinuityError, Segment
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class ProvenanceDiscontinuityError(RuntimeError):
    """Raised when a context segment's label cannot be traced to an oracle-assigned origin."""
    pass

@dataclass
class Segment:
    text: str
    label: str                      # "system" | "retrieved" | "user"
    derived_from: Optional[str] = None   # provenance record id, or None if oracle-assigned
    origin_label: Optional[str] = None   # set only when derived_from is None

TRUST_ORDER = {"system": 0, "retrieved": 1, "user": 2}
PRIVILEGED_SINKS = {"tool_call", "code_exec", "file_write"}

def enforce_sink(segment: Segment, sink: str, provenance_index: dict) -> None:
    # Resolve the true origin label by walking derived_from to an oracle record.
    seen = set()
    cur = segment
    while cur.derived_from is not None:
        if cur.derived_from in seen:
            raise ProvenanceDiscontinuityError(
                f"cycle in provenance chain at {cur.derived_from}"
            )
        seen.add(cur.derived_from)
        record = provenance_index.get(cur.derived_from)
        if record is None:
            raise ProvenanceDiscontinuityError(
                f"segment label {segment.label!r} has no resolvable origin "
                f"(missing provenance record {cur.derived_from!r})"
            )
        cur = record

    if cur.origin_label is None:
        raise ProvenanceDiscontinuityError(
            f"segment label {segment.label!r} terminates at a non-oracle record"
        )

    # Monotonicity check: attached label must not be weaker than true origin.
    if TRUST_ORDER[segment.label] < TRUST_ORDER[cur.origin_label]:
        raise ProvenanceDiscontinuityError(
            f"label laundering: attached {segment.label!r} is stronger than "
            f"origin {cur.origin_label!r}"
        )

    if sink in PRIVILEGED_SINKS and TRUST_ORDER[cur.origin_label] >= TRUST_ORDER["retrieved"]:
        raise ProvenanceDiscontinuityError(
            f"tainted origin {cur.origin_label!r} blocked from privileged sink {sink!r}"
        )
