# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-memory-write-rather-than-label-it-provenance-join-failure-across-tool-output-and-memory-taint-domains.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-memory-write-rather-than-label-it-provenance-join-failure-across-tool-output-and-memory-taint-domains.warrant.json
# Markdown SHA-256:   8d52341107f75e8e7070e498bce7a0142205d2174828ea7124ff7a572e30fc8a
# Code AST SHA-256:   f82c68f16e7c881e1bcba54323e1cb8c7d7c54d0a0bd63e58976951f9a520b5a
# Verified Classes:   ProvenanceJoinError, Provenance, MemoryWrite
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional

class ProvenanceJoinError(RuntimeError):
    """Raised when a memory write cannot produce a closed, re-derivable provenance join."""
    pass

@dataclass(frozen=True)
class Provenance:
    sources: FrozenSet[str]
    tier: int          # higher = more trusted
    taint: bool

def join(inputs: list[Provenance]) -> Provenance:
    if not inputs:
        raise ProvenanceJoinError("empty provenance set: join undefined")
    return Provenance(
        sources=frozenset().union(*(p.sources for p in inputs)),
        tier=min(p.tier for p in inputs),      # meet
        taint=any(p.taint for p in inputs),    # join (OR)
    )

@dataclass
class MemoryWrite:
    content: str
    provenance: Provenance
    derived_from: Optional[FrozenSet[str]] = None  # record ids, required for derived writes

INTERNAL = 2
QUARANTINE = "quarantine"

def admit_write(w: MemoryWrite, store: dict[str, Provenance]) -> str:
    # Derived writes must carry their derivation set; otherwise taint is not re-derivable.
    if w.derived_from is None:
        if w.provenance.tier >= INTERNAL:
            raise ProvenanceJoinError(
                f"derived write at tier {w.provenance.tier} lacks derived_from; "
                "taint not re-derivable -> must quarantine"
            )
        return QUARANTINE

    # Recompute the join over the full derivation closure.
    try:
        contributing = [store[rid] for rid in w.derived_from]
    except KeyError as e:
        raise ProvenanceJoinError(f"unknown derivation source {e}") from e
    recomputed = join(contributing + [w.provenance])

    if recomputed.taint and recomputed.tier >= INTERNAL:
        raise ProvenanceJoinError(
            "tainted content targeted at internal-or-higher tier; "
            "no declassification path -> reject"
        )
    if recomputed.taint:
        return QUARANTINE
    return "stored"
