# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-memory-write-when-label-propagation-and-retrieval-labeling-disagree-across-a-tool-output-bound.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-memory-write-when-label-propagation-and-retrieval-labeling-disagree-across-a-tool-output-bound.warrant.json
# Markdown SHA-256:   d2f9dfb73ba23a23b2dbdf788f6d1679b24344072d68f4a3a1b8266a9e75756d
# Code AST SHA-256:   6b3d8ada59f50e14d4bc02ce91968762d773a65c28ca463d2dce1538ba757791
# Verified Classes:   ProvenanceReconstructionError, MemoryRecord, TaintLabel
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceReconstructionError(RuntimeError):
    """Raised when a memory record's taint label cannot be reconstructed from durable state."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    content: str
    write_time_label: str          # "clean" | "tainted"
    provenance_root: Optional[str]  # hash/id of the taint root, or None if clean
    provenance_incomplete: bool = False


@dataclass
class TaintLabel:
    tainted: bool
    root: Optional[str]


def reconstruct_read_time_label(record: MemoryRecord) -> TaintLabel:
    """
    Total function: returns a root-anchored label OR raises.
    There is deliberately NO 'unknown -> clean' fallback branch.
    """
    if record.write_time_label == "clean":
        return TaintLabel(tainted=False, root=None)

    # write-time label is tainted; we MUST be able to anchor to a root.
    if record.provenance_incomplete or record.provenance_root is None:
        raise ProvenanceReconstructionError(
            f"record {record.record_id}: tainted at write time but provenance "
            f"root is missing (compaction orphaned the edge); cannot prove clean"
        )
    return TaintLabel(tainted=True, root=record.provenance_root)


def admit_to_trusted_context(record: MemoryRecord) -> TaintLabel:
    """
    Gate for placing a retrieved record into trusted context.
    Fails closed: reconstruction failure => quarantine, never silent clean.
    """
    try:
        label = reconstruct_read_time_label(record)
    except ProvenanceReconstructionError as exc:
        # Quarantine: treat as maximally tainted, revoke tool authority.
        raise ProvenanceReconstructionError(
            f"QUARANTINE record {record.record_id}: {exc}. "
            f"Record excluded from trusted context pending re-derivation."
        ) from exc

    if label.tainted:
        # Still admitted, but only under an untrusted-content frame.
        return label
    return label


def declassify(record: MemoryRecord, policy_id: str, residual_risk_justification: str) -> MemoryRecord:
    """
    Explicit declassification. Silent downgrade is prohibited; this must be logged.
    """
    if record.write_time_label != "tainted":
        return record
    if not policy_id or not residual_risk_justification:
        raise ProvenanceReconstructionError(
            f"declassification of {record.record_id} requires policy_id and justification"
        )
    # Emit audit event here in production.
    record.write_time_label = "clean"
    record.provenance_root = None
    return record


# --- demonstration of the boundary failure ---
def _demo() -> None:
    # Legitimate tainted record with intact provenance: admitted as tainted.
    good = MemoryRecord("m1", "the key rotates on the 1st", "tainted", provenance_root="h:fetch_url:abc")
    assert admit_to_trusted_context(good).tainted is True

    # Compaction orphaned the provenance edge: must quarantine, not pass as clean.
    orphaned = MemoryRecord("m2", "the key rotates on the 1st", "tainted",
                            provenance_root=None, provenance_incomplete=True)
    try:
        admit_to_trusted_context(orphaned)
    except ProvenanceReconstructionError as e:
        print("quarantined as required:", e)
    else:
        raise ProvenanceReconstructionError("fail-open: orphaned tainted record was admitted as clean")


if __name__ == "__main__":
    _demo()
