# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-scoped-recall-hit-that-outlived-its-forget-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-scoped-recall-hit-that-outlived-its-forget-warrant.warrant.json
# Markdown SHA-256:   fca5e65e2e3451fe70b806b76e674df772d3cb62d974c99f88f6e41e7b6b2ad2
# Code AST SHA-256:   87992ba8a41b4f8902d3a914ab2ae8ce536a319fe26a79fe3c80637c2ef0432a
# Verified Classes:   WarrantViolation, RecallHit, ForgetWarrant, MemoryView
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class WarrantViolation(RuntimeError):
    """A scoped-recall hit traces to a record under an active forget-warrant."""


@dataclass
class RecallHit:
    chunk_id: str
    scope: str
    ttl_remaining_s: int
    derived_from: tuple[str, ...]
    written_at: int
    post_erasure_clean: bool = False


@dataclass
class ForgetWarrant:
    record_id: str
    issued_at: int
    status: str = "pending_erasure"  # or "forgotten"


@dataclass
class MemoryView:
    warrants: dict[str, ForgetWarrant] = field(default_factory=dict)

    def active_warrants_for(self, ancestors: tuple[str, ...]) -> list[ForgetWarrant]:
        return [
            self.warrants[a]
            for a in ancestors
            if a in self.warrants
            and self.warrants[a].status in ("pending_erasure", "forgotten")
        ]


def serve_hit(hit: RecallHit, mem: MemoryView, now: int) -> RecallHit:
    # Scope and TTL gates pass trivially here; they are NOT the invariant.
    if hit.ttl_remaining_s <= 0:
        raise WarrantViolation(f"{hit.chunk_id}: expired, treat as miss")

    warrants = mem.active_warrants_for(hit.derived_from)
    if not warrants:
        return hit

    # A warrant exists on an ancestor. Only a post-erasure attestation
    # written strictly after the newest warrant may re-qualify the hit.
    newest = max(w.issued_at for w in warrants)
    if hit.post_erasure_clean and hit.written_at > newest:
        return hit

    raise WarrantViolation(
        f"{hit.chunk_id}: derived_from {hit.derived_from} intersects active "
        f"forget-warrant(s) {[w.record_id for w in warrants]}; "
        f"refusing to serve and refusing to re-derive from same source"
    )


def recall(scope: str, query: str, mem: MemoryView, store, now: int) -> Optional[RecallHit]:
    hit = store.read(scope=scope, query=query)
    if hit is None:
        return None  # genuine miss: caller may re-derive safely
    try:
        return serve_hit(hit, mem, now)
    except WarrantViolation:
        # Do NOT fall back to re-derivation; escalate so erasure completes
        # at the store and to peer instances holding the record in-context.
        raise
