# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-high-write-time-anomaly-score-as-evidence-of-poisoning-rather-than-legitimate-memory-evolution.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-high-write-time-anomaly-score-as-evidence-of-poisoning-rather-than-legitimate-memory-evolution.warrant.json
# Markdown SHA-256:   6be04bb10326b3377080581654f89643e6514e012a257c8addd33b5730191aec
# Code AST SHA-256:   b8f8d5ea23888e2cc893800e300133c4087271d08abfacc66d0812f1f740fbb7
# Verified Classes:   UnauditableRetractionError, Tombstone, AuditTrail
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class UnauditableRetractionError(RuntimeError):
    """Raised when a forget operation would destroy poisoning evidence."""


@dataclass
class Tombstone:
    content_hash: str
    score: float
    threshold: float
    scorer_version: str
    source: str
    occurrence_count: int = 1


@dataclass
class AuditTrail:
    tombstones: dict[str, Tombstone] = field(default_factory=dict)

    def record_retraction(self, content: str, score: float, threshold: float,
                          scorer_version: str, source: str) -> Tombstone:
        if not content or scorer_version is None:
            raise UnauditableRetractionError(
                "retraction lacks content hash or scorer provenance; "
                "evidence would be unattributable"
            )
        h = hashlib.sha256(content.encode("utf-8")).hexdigest()
        if h in self.tombstones:
            self.tombstones[h].occurrence_count += 1
            return self.tombstones[h]
        ts = Tombstone(h, score, threshold, scorer_version, source)
        self.tombstones[h] = ts
        return ts

    def classify(self, h: str) -> str:
        ts = self.tombstones.get(h)
        if ts is None:
            raise UnauditableRetractionError(f"no tombstone for hash {h[:12]}")
        if ts.occurrence_count >= 2:
            return "attributable_poisoning"
        if ts.score > ts.threshold * 1.4:
            return "review"          # single extreme score is NOT attribution
        return "regime_change_or_drift"


def attribute_incident(trail: AuditTrail, content: str) -> str:
    h = hashlib.sha256(content.encode("utf-8")).hexdigest()
    verdict = trail.classify(h)
    if verdict == "attributable_poisoning":
        return verdict
    if verdict == "review":
        raise UnauditableRetractionError(
            "single high score cannot be attributed without a repeat occurrence; "
            "route to review, do not quarantine source"
        )
    return verdict
