# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-tool-write-acknowledgment-as-non-durable-when-retention-policy-and-audit-trail-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-tool-write-acknowledgment-as-non-durable-when-retention-policy-and-audit-trail-disagree.warrant.json
# Markdown SHA-256:   f735221e629a9b3e800c04e01f031fa81167aaeb367b2bad83a8690050adba51
# Code AST SHA-256:   5461ad706d97ac55d2b9c78b7f490ba8593936a330c45cf33adb69ccdd24f17a
# Verified Classes:   DurabilityUnconfirmedError, WriteAck
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DurabilityUnconfirmedError(RuntimeError):
    """Raised when a memory write's audit confirmation is missing or its
    retention class is incompatible with the required task lifetime."""


@dataclass
class WriteAck:
    record_id: str
    status: str                 # "accepted" | "rejected"
    audit_ref: str | None       # None or "pending" => unconfirmed
    retention_class: str        # echoed class, may be inherited default
    content: bytes


REQUIRED_CLASSES = {"durable_task", "legal_hold"}


def confirm_durable_write(ack: WriteAck, audit_lookup) -> str:
    """Return a content hash usable as a checkpoint anchor, or raise.

    The invariant: an ID may only be used as a continuity anchor after the
    audit trail independently confirms the same record_id and content hash.
    """
    if ack.status != "accepted":
        raise DurabilityUnconfirmedError(
            f"write {ack.record_id} not accepted: {ack.status}"
        )
    if ack.audit_ref in (None, "", "pending"):
        raise DurabilityUnconfirmedError(
            f"write {ack.record_id} has no audit confirmation; "
            f"ID is not a valid checkpoint anchor"
        )
    if ack.retention_class not in REQUIRED_CLASSES:
        raise DurabilityUnconfirmedError(
            f"write {ack.record_id} retention_class={ack.retention_class!r} "
            f"incompatible with task lifetime; may be swept as orphan"
        )

    audit_entry = audit_lookup(ack.audit_ref)
    expected = hashlib.sha256(ack.content).hexdigest()
    if audit_entry is None or audit_entry["hash"] != expected:
        raise DurabilityUnconfirmedError(
            f"audit entry for {ack.record_id} missing or hash mismatch; "
            f"record may be expired as unattributable on next sweep"
        )
    return expected


def resolve_read(record_id: str, read_result: dict, checkpoint_hash: str | None):
    """Distinguish a tombstoned record from one never written."""
    if read_result.get("status") == "expired":
        # NOT absence: this is a durability failure of a prior write.
        raise DurabilityUnconfirmedError(
            f"record {record_id} expired after accepted write; "
            f"treat as durability failure, re-write from checkpoint "
            f"(hash={checkpoint_hash}) or invalidate dependent step"
        )
    if read_result.get("status") == "live":
        return read_result["content"]
    return None
