# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-memory-whose-provenance-hash-was-computed-over-a-redacted-field-the-silent-provenance-split-failure-in-persiste.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-memory-whose-provenance-hash-was-computed-over-a-redacted-field-the-silent-provenance-split-failure-in-persiste.warrant.json
# Markdown SHA-256:   d4b4a603b988842d267d5addd66b6e6d501efb956eab0576302f6d9bc94b5efe
# Code AST SHA-256:   5110e7505cd6d4195331fbff60d7adc21ab5ec71ef4da1b4b16a2bfa0fc46348
# Verified Classes:   ProvenanceSplitError, UnverifiedRecordError, MemoryRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ProvenanceSplitError(RuntimeError):
    """Raised when a memory record's provenance digest does not bind the served payload."""
    pass


class UnverifiedRecordError(RuntimeError):
    """Raised when a record cannot be re-attested from source and must not be served."""
    pass


def canonical(body: str, redactions: list[str], source: str, signer: str) -> bytes:
    # C1: digest covers body AND redaction set AND provenance pointers.
    return json.dumps(
        {"body": body, "redactions": sorted(redactions), "source": source, "signer": signer},
        sort_keys=True, separators=(",", ":"),
    ).encode("utf-8")


def attest(body: str, redactions: list[str], source: str, signer: str) -> str:
    return hashlib.sha256(canonical(body, redactions, source, signer)).hexdigest()


@dataclass
class MemoryRecord:
    body: str
    redactions: list[str]
    source: str
    signer: str
    content_hash: str
    verified: bool = field(default=False)


def serve(record: MemoryRecord, raw_source_lookup) -> MemoryRecord:
    expected = attest(record.body, record.redactions, record.source, record.signer)
    if expected == record.content_hash:
        record.verified = True
        return record

    # Hard fail: do not soft-pass on "redactions present". Re-attest from source.
    raw = raw_source_lookup(record.source)
    if raw is None:
        raise UnverifiedRecordError(
            f"record {record.source} digest mismatch and source unavailable; refusing to serve"
        )

    reattested = attest(raw.body, raw.redactions, raw.source, raw.signer)
    if reattested != record.content_hash:
        # Digest was computed over a different payload than any honest derivation yields.
        raise ProvenanceSplitError(
            f"provenance split on {record.source}: stored={record.content_hash[:12]} "
            f"reattested={reattested[:12]} served_body={record.body!r}"
        )
    record.body, record.redactions = raw.body, raw.redactions
    record.verified = True
    return record
