# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-memory-write-before-it-lands-the-provenance-stamp-content-hash-skew-boundary-in-persistent-agent-memory-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-memory-write-before-it-lands-the-provenance-stamp-content-hash-skew-boundary-in-persistent-agent-memory-stores.warrant.json
# Markdown SHA-256:   73cd1d872d6fa93af15007641b63961d90a9ca50da29ce1ff7422abdba6a4a30
# Code AST SHA-256:   af6f838f9c6424474418b1762d783222ce3fc058d0f86d829e5f5bb4d3d1f3fc
# Verified Classes:   ProvenanceSkewError, WitnessUnavailableError, MemoryWrite
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ProvenanceSkewError(RuntimeError):
    """Raised when a memory write's provenance stamp cannot be independently
    re-derived, meaning content-hash verification is insufficient to admit it."""
    pass


class WitnessUnavailableError(ProvenanceSkewError):
    """Raised when the witness store (warrant/revocation ledger) is unreachable
    or the logical clock is ahead of the store high-water mark."""
    pass


@dataclass
class MemoryWrite:
    payload: bytes
    content_hash: str          # H(payload) under the naive model
    principal_id: str
    warrant_id: str
    logical_clock: int
    parent_write_id: str | None


def canonical(provenance: dict) -> bytes:
    return json.dumps(provenance, sort_keys=True, separators=(",", ":")).encode()


def welded_hash(payload: bytes, provenance: dict) -> str:
    # The weld: hash MUST cover provenance, not just payload.
    return hashlib.sha256(payload + b"\x00" + canonical(provenance)).hexdigest()


def admit_write(
    write: MemoryWrite,
    warrant_store,
    revocation_list,
    store_high_water_clock: int,
) -> str:
    """Return 'admit' or 'quarantine'. Never returns 'admit' on skew."""
    provenance = {
        "principal_id": write.principal_id,
        "warrant_id": write.warrant_id,
        "logical_clock": write.logical_clock,
        "parent_write_id": write.parent_write_id,
    }

    # Step 1: welded integrity check. Catches tamper AND stamp transplant.
    if welded_hash(write.payload, provenance) != write.content_hash:
        # Proven-bad: reject outright, do not quarantine.
        return "reject"

    # Step 2: future-stamped write is a transplant in progress.
    if write.logical_clock > store_high_water_clock:
        raise WitnessUnavailableError(
            f"logical_clock {write.logical_clock} ahead of store high-water "
            f"{store_high_water_clock}; provenance not yet corroborable"
        )

    # Step 3: re-derive witness WITHOUT trusting TTL caches.
    try:
        warrant = warrant_store.fetch(write.warrant_id, bypass_cache=True)
    except LookupError as exc:
        raise WitnessUnavailableError(
            f"warrant {write.warrant_id} not resolvable: {exc}"
        ) from exc

    if warrant.principal_id != write.principal_id:
        # Content authentic, attribution forged: the exact skew case.
        raise ProvenanceSkewError(
            f"warrant {write.warrant_id} belongs to {warrant.principal_id}, "
            f"write claims {write.principal_id}"
        )

    if revocation_list.is_revoked(write.warrant_id, bypass_cache=True):
        raise ProvenanceSkewError(
            f"warrant {write.warrant_id} revoked; write is post-revocation skew"
        )

    # Step 4: ancestry must be live, not merely recorded.
    if write.parent_write_id is not None:
        parent_status = warrant_store.parent_status(write.parent_write_id)
        if parent_status != "verified":
            raise ProvenanceSkewError(
                f"parent {write.parent_write_id} is {parent_status}; "
                f"admission would launder quarantined ancestry"
            )

    return "admit"


def ingest_batch(writes, warrant_store, revocation_list, high_water):
    admitted, quarantined, rejected = [], [], []
    for w in writes:
        try:
            if admit_write(w, warrant_store, revocation_list, high_water) == "admit":
                admitted.append(w)
            else:
                rejected.append(w)
        except ProvenanceSkewError:
            # Quarantine, never admit, never let it become a parent.
            quarantined.append(w)
    return admitted, quarantined, rejected
