# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-its-own-write-audit-trail-has-been-written-by-the-poisoned-writer.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-its-own-write-audit-trail-has-been-written-by-the-poisoned-writer.warrant.json
# Markdown SHA-256:   eda3e25f9628248bd5e10ba4217002bf694ff848d3915f03b3aadf2298728f08
# Code AST SHA-256:   63e15b1904d028ce3b9f8b9dc22c4055dae5bd04c652bde04457f4e13d15c62b
# Verified Classes:   MemoryIntegrityError, Record
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass

class MemoryIntegrityError(RuntimeError):
    """Raised when the audit trail cannot support a poisoning verdict."""

@dataclass
class Record:
    seq: int
    ts: float
    op: str          # "write" | "read"
    key: str
    value_hash: str
    session_id: str

def verify_attribution(records: list[Record], externally_anchored: bool) -> None:
    # 1. Ordering must be storage-assigned and gap-free.
    seqs = [r.seq for r in records]
    if len(seqs) != len(set(seqs)):
        raise MemoryIntegrityError("duplicate seq: trail ordering is unreliable, verdict void")
    for a, b in zip(seqs, seqs[1:]):
        if b != a + 1:
            raise MemoryIntegrityError(f"seq gap {a}->{b}: unattributed window")

    # 2. Every session-boundary state delta must have a write op.
    by_session: dict[str, list[Record]] = {}
    for r in records:
        by_session.setdefault(r.session_id, []).append(r)
    ordered = [by_session[s] for s in sorted(by_session)]
    for prev, nxt in zip(ordered, ordered[1:]):
        last_hash = prev[-1].value_hash
        first = nxt[0]
        if first.value_hash != last_hash and first.op != "write":
            raise MemoryIntegrityError(
                f"unattributed transition at session {first.session_id}: "
                f"state changed with no write op"
            )

    # 3. A self-attested trail cannot yield a positive verdict.
    if not externally_anchored:
        raise MemoryIntegrityError(
            "trail is self-attested (writer == auditor); "
            "consistency check passed but integrity is unverified"
        )

def detect(records: list[Record], externally_anchored: bool) -> str:
    verify_attribution(records, externally_anchored)
    return "memory verified against externally anchored, fully attributed trail"
