# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-poisoning-attestation-as-invalid-rather-than-as-evidence-of-drift.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-poisoning-attestation-as-invalid-rather-than-as-evidence-of-drift.warrant.json
# Markdown SHA-256:   53ae1af34c30a2102f162de810aec29a7ab4468a45809428c1aa14904a26780c
# Code AST SHA-256:   a2f3a672a1aecb3f9a7e194e013806fe94b3acb1da96a54f00c1303c906b75bc
# Verified Classes:   ProvenanceUnverifiableError, Record, StoreManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ProvenanceUnverifiableError(RuntimeError):
    """Raised when a memory record's attestation is internally consistent but
    cannot be anchored to a trust root held independently by the verifier."""
    pass


@dataclass(frozen=True)
class Record:
    payload: bytes
    digest: str
    signer_id: str
    commit_ts: float


@dataclass(frozen=True)
class StoreManifest:
    store_root: str
    root_signer_id: str
    root_commit_ts: float


def verify_record(
    record: Record,
    manifest: StoreManifest,
    pinned_root: str,
    pinned_root_ts: float,
    authorized_signer_at_commit: dict,
) -> str:
    # Internal consistency check: digest matches payload.
    if hashlib.sha256(record.payload).hexdigest() != record.digest:
        return "drift"

    # The critical boundary: the manifest's root must match the root the
    # verifier held BEFORE reading the store. If it does not, the attestation
    # is consistent but unverifiable, and we must not repair it in-place.
    if manifest.store_root != pinned_root:
        raise ProvenanceUnverifiableError(
            f"store_root {manifest.store_root[:12]}... does not match pinned "
            f"root {pinned_root[:12]}...; record cannot be anchored"
        )

    # Root must have been committed at or before the verifier's pinned epoch.
    if manifest.root_commit_ts > pinned_root_ts:
        raise ProvenanceUnverifiableError(
            "manifest root was re-signed after the verifier's pinned epoch; "
            "possible re-rooting by a compromised writer"
        )

    # Signer identity must resolve to a key authorized at the record's commit
    # time, not merely at read time. String equality of signer_id is not
    # identity continuity across key rotation.
    authorized_key = authorized_signer_at_commit.get(record.signer_id)
    if authorized_key is None:
        raise ProvenanceUnverifiableError(
            f"signer {record.signer_id!r} was not authorized at commit_ts "
            f"{record.commit_ts}; cannot distinguish rotation from impostor"
        )

    return "verified"


def load_store(records, manifest, pinned_root, pinned_root_ts, auth_map):
    verified, drift, quarantined = [], [], []
    for rec in records:
        try:
            status = verify_record(
                rec, manifest, pinned_root, pinned_root_ts, auth_map
            )
        except ProvenanceUnverifiableError:
            quarantined.append(rec)
            continue
        (verified if status == "verified" else drift).append(rec)
    return {"verified": verified, "drift": drift, "quarantined": quarantined}
