# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-write-ack-as-durable-the-read-after-write-divergence-between-acknowledged-writes-and-post-compac.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-write-ack-as-durable-the-read-after-write-divergence-between-acknowledged-writes-and-post-compac.warrant.json
# Markdown SHA-256:   b8aa14155755ac803e52aa8a2b7780a88517a739a942f40e4c5415a33795a939
# Code AST SHA-256:   147e966cac3ceab719ca35324ad1488991e294ccb7b5fa2597a659ccdd62ce8d
# Verified Classes:   MemoryDurabilityError, WriteReceipt
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class MemoryDurabilityError(RuntimeError):
    """Raised when a write ACK does not correspond to a retrievable, content-matching record."""
    pass


@dataclass
class WriteReceipt:
    mem_id: str
    content_hash: str
    indexed: bool
    merged_into: Optional[str]


def content_hash(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def write_with_receipt(memory_tool, text: str) -> WriteReceipt:
    resp = memory_tool.write(text=text)
    if resp.get("status") != "ok":
        raise MemoryDurabilityError(f"write rejected: {resp}")
    receipt = WriteReceipt(
        mem_id=resp["id"],
        content_hash=content_hash(text),
        indexed=bool(resp.get("indexed", False)),
        merged_into=resp.get("merged_into"),
    )
    # ACK alone is never sufficient: confirm retrievability now.
    if not verify_receipt(memory_tool, receipt, expected_text=text):
        raise MemoryDurabilityError(
            f"write ACKed but not retrievable/content-mismatched: id={receipt.mem_id} "
            f"indexed={receipt.indexed} merged_into={receipt.merged_into}"
        )
    return receipt


def verify_receipt(memory_tool, receipt: WriteReceipt, expected_text: str) -> bool:
    if receipt.merged_into is not None:
        # Dedup fired; the standalone record does not exist. Treat as lost unless
        # the merge target carries our content.
        target = memory_tool.read(id=receipt.merged_into)
        return target is not None and content_hash(target["text"]) == receipt.content_hash
    record = memory_tool.read(id=receipt.mem_id)
    if record is None:
        return False  # index lag or eviction
    return content_hash(record["text"]) == receipt.content_hash == content_hash(expected_text)


def resume_and_reconcile(memory_tool, receipts: list[WriteReceipt]) -> list[WriteReceipt]:
    """On cold start, verify every receipted fact before relying on it."""
    lost = []
    for r in receipts:
        record = memory_tool.read(id=r.merged_into or r.mem_id)
        if record is None or content_hash(record["text"]) != r.content_hash:
            lost.append(r)
    if lost:
        raise MemoryDurabilityError(
            f"{len(lost)} receipted writes are non-retrievable or content-drifted on resume: "
            f"{[r.mem_id for r in lost]}"
        )
    return receipts
