# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-write-audit-diff-as-evidence-of-memory-poisoning-rather-than-as-benign-drift.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-write-audit-diff-as-evidence-of-memory-poisoning-rather-than-as-benign-drift.warrant.json
# Markdown SHA-256:   cc58128551148902b9edfaaeef64e2d8f86f33ef73325184f83e2f83e86439f8
# Code AST SHA-256:   964f92871242fe206c804122394df9a6187b752e359f859195f7ec9e8dc96056
# Verified Classes:   MemoryPoisoningError, SubstrateIntegrityError, DivergenceClass, AuditRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class MemoryPoisoningError(RuntimeError):
    """Raised when a write-audit diff yields non-reconcilable divergence."""
    pass


class SubstrateIntegrityError(RuntimeError):
    """Raised when the audit log itself cannot be trusted as evidence."""
    pass


class DivergenceClass(Enum):
    LAG = "lag"
    DERIVED = "derived"
    ORPHAN = "orphan"
    AMBIGUOUS = "ambiguous"


@dataclass
class AuditRecord:
    key: str
    value_hash: str
    source: str
    write_ts: int
    prev_hash: str
    record_hash: str

    def verify_chain(self, expected_prev: str) -> bool:
        payload = f"{self.key}|{self.value_hash}|{self.source}|{self.write_ts}|{self.prev_hash}"
        return hashlib.sha256(payload.encode()).hexdigest() == self.record_hash


def classify_divergence(
    key: str,
    store_value_hash: str,
    ground_truth_hash: str | None,
    ground_truth_version_ts: int,
    audit_log: dict[str, AuditRecord],
) -> DivergenceClass:
    record = audit_log.get(key)

    if record is None:
        # No write-audit record at all: unambiguously non-reconcilable.
        return DivergenceClass.ORPHAN

    if not record.verify_chain(record.prev_hash):
        # The evidence channel is compromised; cannot decide.
        return DivergenceClass.AMBIGUOUS

    if ground_truth_hash is None:
        # Store holds a value with no ground-truth counterpart.
        # Benign only if the write postdates the ground-truth snapshot.
        if record.write_ts > ground_truth_version_ts:
            return DivergenceClass.LAG
        return DivergenceClass.ORPHAN

    if store_value_hash == ground_truth_hash:
        return DivergenceClass.DERIVED  # matched, no action

    if record.write_ts > ground_truth_version_ts:
        return DivergenceClass.LAG

    # Divergence with a verified record that predates ground truth:
    # the record cannot explain the mismatch -> treat as poisoning.
    return DivergenceClass.ORPHAN


def audit_memory_store(
    store: dict[str, str],
    ground_truth: dict[str, tuple[str, int]],
    audit_log: dict[str, AuditRecord],
) -> list[str]:
    quarantined: list[str] = []
    for key, value_hash in store.items():
        gt = ground_truth.get(key)
        gt_hash, gt_ts = (gt[0], gt[1]) if gt else (None, 0)

        cls = classify_divergence(key, value_hash, gt_hash, gt_ts, audit_log)

        if cls is DivergenceClass.AMBIGUOUS:
            raise SubstrateIntegrityError(
                f"Audit chain broken for key={key!r}; refusing to classify as poisoning. "
                "Repair audit substrate before continuing."
            )
        if cls is DivergenceClass.ORPHAN:
            quarantined.append(key)

    if quarantined:
        raise MemoryPoisoningError(
            f"Non-reconcilable divergence detected; quarantined keys: {quarantined}"
        )
    return quarantined
