# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-memory-write-that-its-own-forgetting-curve-eviction-policy-will-silently-reverse.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-memory-write-that-its-own-forgetting-curve-eviction-policy-will-silently-reverse.warrant.json
# Markdown SHA-256:   f10b1fa4c993c50a41b04250896a6ebb7e3e7e7465d74f90706783a48a0d020f
# Code AST SHA-256:   934a297ebe7d80356342abdb7bf95a2154888a96ecd09a5b71ee0735f24ce7f0
# Verified Classes:   DurabilityHorizonViolation, WriteReceipt
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass


class DurabilityHorizonViolation(RuntimeError):
    """Raised when a memory write cannot be guaranteed to survive until its next intended use."""
    pass


@dataclass
class WriteReceipt:
    key: str
    stability_seconds: float          # S assigned by the store's classifier
    eviction_threshold: float         # retention score below which the sweep evicts
    supports_reinforce: bool
    supports_pin: bool
    durability_token: str | None


def eviction_horizon_seconds(receipt: WriteReceipt) -> float:
    if receipt.stability_seconds <= 0:
        return 0.0
    if not (0.0 < receipt.eviction_threshold < 1.0):
        raise DurabilityHorizonViolation(
            f"invalid eviction threshold {receipt.eviction_threshold!r} for key {receipt.key!r}"
        )
    return -receipt.stability_seconds * math.log(receipt.eviction_threshold)


def assert_write_is_durable(
    receipt: WriteReceipt,
    dependency_span_seconds: float,
    crosses_compaction: bool,
) -> None:
    """
    Call immediately after a memory write returns success, before the agent
    relies on the record across a context boundary. Raises if the record's
    forgetting-curve lifetime cannot cover the intended dependency span.
    """
    horizon = eviction_horizon_seconds(receipt)

    # A compaction boundary invalidates in-store durability assumptions
    # unless the record is pinned or carries a re-validatable token.
    if crosses_compaction and not (receipt.supports_pin or receipt.durability_token):
        raise DurabilityHorizonViolation(
            f"write {receipt.key!r} crosses a compaction boundary but has no pin "
            f"or durability token; eviction horizon {horizon:.1f}s is not a warranty"
        )

    if dependency_span_seconds > horizon:
        if receipt.supports_reinforce or receipt.supports_pin:
            raise DurabilityHorizonViolation(
                f"write {receipt.key!r} horizon {horizon:.1f}s < dependency span "
                f"{dependency_span_seconds:.1f}s; escalate via reinforce/pin before proceeding"
            )
        raise DurabilityHorizonViolation(
            f"write {receipt.key!r} horizon {horizon:.1f}s < dependency span "
            f"{dependency_span_seconds:.1f}s and no upgrade verb exists; "
            f"carry in-context or re-derive at use time"
        )


def checked_write(receipt: WriteReceipt, span_s: float, compaction: bool) -> str:
    assert_write_is_durable(receipt, span_s, compaction)
    return receipt.durability_token or f"in-context:{receipt.key}"
