# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-successful-memory-erasure-tool-response-as-non-authoritative-until-the-tombstone-is-durably-committed-a.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-successful-memory-erasure-tool-response-as-non-authoritative-until-the-tombstone-is-durably-committed-a.warrant.json
# Markdown SHA-256:   aee67b7c5fa4212c00a3da67782c4919313a22d1a4f2e51dfa15a247f72c9d0c
# Code AST SHA-256:   ee4fcb5796ad2810697fa42d79dc4f0c9282cd9ebcb05a4ac02cdd73d7288305
# Verified Classes:   NonAuthoritativeErasureError, ForgetAck
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class NonAuthoritativeErasureError(RuntimeError):
    """Raised when an agent attempts to distill from a scope whose erasure
    acknowledgment has not been confirmed durable across all replicas."""
    pass


@dataclass
class ForgetAck:
    scope: str
    key: str
    tombstone_ttl: int          # seconds the tombstone is retained
    acked_at: float             # monotonic timestamp of acknowledgment


def assert_erasure_durable(
    ack: ForgetAck,
    max_replication_interval: int,
    erasure_committed: bool,
    now: float | None = None,
) -> None:
    """Invariant: a forget() ack is non-authoritative until tombstone_ttl
    exceeds max_replication_interval OR an explicit commit barrier is present.
    The agent MUST call this before any cross-scope distillation read."""
    now = now if now is not None else time.monotonic()

    # Trigger condition: tombstone can expire before anti-entropy suppresses
    # the stale copy on a lagging replica.
    if ack.tombstone_ttl < max_replication_interval and not erasure_committed:
        raise NonAuthoritativeErasureError(
            f"forget({ack.scope}/{ack.key}) is non-authoritative: "
            f"tombstone_ttl={ack.tombstone_ttl}s < "
            f"max_replication_interval={max_replication_interval}s and no "
            f"erasure_committed barrier was returned. Distillation from any "
            f"scope that may derive from this key is forbidden; the erased "
            f"datum can be resurrected under a new key with a longer TTL."
        )

    # Even with a barrier, the agent must not have already exceeded the
    # tombstone window before the barrier was observed.
    if erasure_committed and (now - ack.acked_at) > ack.tombstone_ttl:
        raise NonAuthoritativeErasureError(
            f"erasure barrier for {ack.scope}/{ack.key} arrived after "
            f"tombstone expiry ({(now - ack.acked_at):.1f}s > "
            f"{ack.tombstone_ttl}s); stale replica may have re-propagated."
        )


def guarded_distill(ack: ForgetAck, backend) -> dict:
    assert_erasure_durable(
        ack,
        max_replication_interval=backend.max_replication_interval,
        erasure_committed=backend.erasure_committed(ack.scope, ack.key),
    )
    # Only now may the agent read derived scopes and re-write summaries.
    return backend.distill(source_scope=ack.scope, provenance=ack.key)
