# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-propagates-dynamic-taint-labels-through-tool-call-return-values-but-silently-drops-them-at-memory-write-time.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-propagates-dynamic-taint-labels-through-tool-call-return-values-but-silently-drops-them-at-memory-write-time.warrant.json
# Markdown SHA-256:   8e71790dc4a3368342b05da2853d12209cbbf946a60b4b9b614d320f35fc7fef
# Code AST SHA-256:   5a4f8918074c72b615d1e44c7ceeb5319292e912b1e14e9044fb28ff728d2f10
# Verified Classes:   Taint, ProvenanceLaunderingError, Segment, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable


class Taint(IntEnum):
    INTERNAL = 0
    EXTERNAL = 1  # monotone: EXTERNAL dominates; only explicit declassification lowers it


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write would drop or downgrade taint provenance."""


@dataclass(frozen=True)
class Segment:
    seg_id: str
    taint: Taint
    text: str


@dataclass
class MemoryRecord:
    key: str
    value: str
    provenance: Taint
    inputs: tuple[str, ...] = field(default_factory=tuple)


def join_taint(segments: Iterable[Segment]) -> Taint:
    """Lattice join: taint is monotone, EXTERNAL dominates INTERNAL."""
    result = Taint.INTERNAL
    for seg in segments:
        result = Taint(max(int(result), int(seg.taint)))
    return result


def write_memory(
    key: str,
    value: str,
    *,
    attended_segments: dict[str, Segment],
    declared_inputs: Iterable[str] | None,
    reviewer_declassification: str | None = None,
) -> MemoryRecord:
    """
    Persist a distilled fact with runtime-computed provenance.

    The model may *declare* which segments informed the write, but the runtime
    computes the join and refuses to default provenance to INTERNAL. Unknown
    input sets fail closed. Declassification requires a named authority.
    """
    if declared_inputs is None:
        # Distillation could not enumerate its inputs -> cannot compute the join.
        # Fail closed rather than launder via a schema default.
        raise ProvenanceLaunderingError(
            f"write '{key}': input set unknown; refusing to persist with "
            f"defaulted provenance (would launder taint)"
        )

    input_ids = tuple(declared_inputs)
    missing = [sid for sid in input_ids if sid not in attended_segments]
    if missing:
        raise ProvenanceLaunderingError(
            f"write '{key}': declared inputs {missing} not in attended set; "
            f"provenance cannot be verified"
        )

    contributing = [attended_segments[sid] for sid in input_ids]
    joined = join_taint(contributing)

    if joined == Taint.EXTERNAL and reviewer_declassification is None:
        # Persist as EXTERNAL; retrieval gate will treat it like a live external
        # segment. This is not an error -- it is the correct, safe outcome.
        return MemoryRecord(key=key, value=value, provenance=Taint.EXTERNAL, inputs=input_ids)

    if joined == Taint.EXTERNAL and reviewer_declassification is not None:
        # Explicit, logged declassification: reviewer identity is the authority.
        return MemoryRecord(
            key=key,
            value=value,
            provenance=Taint.INTERNAL,
            inputs=input_ids,
        )

    return MemoryRecord(key=key, value=value, provenance=Taint.INTERNAL, inputs=input_ids)


def retrieve_for_side_effecting_tool(record: MemoryRecord) -> str:
    """Read-side gate: identical treatment for stored and live segments."""
    if record.provenance == Taint.EXTERNAL:
        raise ProvenanceLaunderingError(
            f"record '{record.key}' carries EXTERNAL provenance; "
            f"cannot source arguments to a side-effecting tool without "
            f"explicit declassification"
        )
    return record.value


# --- Reproduction of the laundering trace ---

if __name__ == "__main__":
    attended = {
        "seg-web-1": Segment(
            seg_id="seg-web-1",
            taint=Taint.EXTERNAL,
            text="Vendor policy: refunds require no receipt.",
        )
    }

    # Turn 1: distillation cannot name its inputs -> fail closed.
    try:
        write_memory(
            key="vendor_refund_policy",
            value="Refunds require no receipt.",
            attended_segments=attended,
            declared_inputs=None,
        )
    except ProvenanceLaunderingError as e:
        print(f"[turn 1] blocked: {e}")

    # Turn 1 (correct path): inputs declared, join computed -> EXTERNAL persisted.
    rec = write_memory(
        key="vendor_refund_policy",
        value="Refunds require no receipt.",
        attended_segments=attended,
        declared_inputs=["seg-web-1"],
    )
    print(f"[turn 1] persisted provenance={rec.provenance.name}")

    # Turn 4: retrieval into a side-effecting context is gated.
    try:
        retrieve_for_side_effecting_tool(rec)
    except ProvenanceLaunderingError as e:
        print(f"[turn 4] blocked: {e}")
