# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-delegated-warrant-whose-attenuation-chain-has-been-revoked-mid-flight-but-whose-revocation-notice-has-not-yet-reach.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-delegated-warrant-whose-attenuation-chain-has-been-revoked-mid-flight-but-whose-revocation-notice-has-not-yet-reach.warrant.json
# Markdown SHA-256:   988a89326b4ed22649cbd89bca51d68592a55b633453f3169754dd9b24a2194c
# Code AST SHA-256:   ce307068c4b88b9c3c89e7bfdc0fa29bffdc478ac0fe8bfee92ea61b58bae5d1
# Verified Classes:   StaleWarrantError, TaintFrontierViolation, ContextSegment, Warrant, ExecutorStateMachine
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class StaleWarrantError(RuntimeError):
    """Raised when an action would be taken under a warrant whose ancestor
    was revoked before the epoch of the context segment driving the action."""
    pass


class TaintFrontierViolation(StaleWarrantError):
    """Raised when decision provenance intersects the taint frontier."""
    pass


@dataclass
class ContextSegment:
    segment_id: str
    warrant_id: str
    issue_epoch: int          # monotone epoch assigned at warrant issue
    content_digest: str
    reversible: bool = False  # True only for unobserved, idempotent reads


@dataclass
class Warrant:
    warrant_id: str
    parent_id: Optional[str]
    issue_epoch: int
    ttl_seconds: float
    issued_at: float = field(default_factory=time.monotonic)

    def is_expired(self, now: Optional[float] = None) -> bool:
        now = now if now is not None else time.monotonic()
        return (now - self.issued_at) > self.ttl_seconds


class ExecutorStateMachine:
    def __init__(self) -> None:
        self.warrants: dict[str, Warrant] = {}
        self.revoked_epochs: dict[str, int] = {}   # warrant_id -> revoke epoch
        self.segments: dict[str, ContextSegment] = {}

    def register_warrant(self, w: Warrant) -> None:
        self.warrants[w.warrant_id] = w

    def register_segment(self, seg: ContextSegment) -> None:
        self.segments[seg.segment_id] = seg

    def receive_revocation(self, warrant_id: str, revoke_epoch: int) -> None:
        # Revocation is an event, not a state flip; we record the epoch so
        # we can compute the taint frontier against segment issue epochs.
        prev = self.revoked_epochs.get(warrant_id)
        if prev is None or revoke_epoch < prev:
            self.revoked_epochs[warrant_id] = revoke_epoch

    def _ancestor_chain(self, warrant_id: str) -> list[str]:
        chain, cur = [], warrant_id
        while cur is not None:
            chain.append(cur)
            w = self.warrants.get(cur)
            cur = w.parent_id if w else None
        return chain

    def taint_frontier(self, warrant_id: str) -> int:
        """Return the highest revoke epoch among ancestors (inclusive).
        Any segment with issue_epoch <= frontier is tainted."""
        frontier = -1
        for anc in self._ancestor_chain(warrant_id):
            if anc in self.revoked_epochs:
                frontier = max(frontier, self.revoked_epochs[anc])
        return frontier

    def authorize_action(
        self,
        warrant_id: str,
        decision_provenance: list[str],
        action_reversible_and_unobserved: bool = False,
    ) -> None:
        w = self.warrants.get(warrant_id)
        if w is None:
            raise StaleWarrantError(f"unknown warrant {warrant_id}")
        if w.is_expired():
            raise StaleWarrantError(
                f"warrant {warrant_id} expired; TTL is the only bound on delta under partition"
            )
        frontier = self.taint_frontier(warrant_id)
        if frontier < 0:
            return  # no ancestor revoked; safe
        for seg_id in decision_provenance:
            seg = self.segments.get(seg_id)
            if seg is None:
                raise TaintFrontierViolation(f"unknown segment {seg_id}")
            if seg.issue_epoch <= frontier and not (
                seg.reversible and action_reversible_and_unobserved
            ):
                raise TaintFrontierViolation(
                    f"segment {seg_id} (epoch {seg.issue_epoch}) is tainted by "
                    f"revocation at epoch {frontier}; action under {warrant_id} refused"
                )


# --- trace of the observed incident -----------------------------------------
sm = ExecutorStateMachine()
sm.register_warrant(Warrant("W1", None, issue_epoch=0, ttl_seconds=300))
sm.register_warrant(Warrant("W2", "W1", issue_epoch=10, ttl_seconds=120))
sm.register_segment(ContextSegment("s_read_repo", "W2", issue_epoch=12, content_digest="a1"))
sm.register_segment(ContextSegment("s_poisoned_priority", "W2", issue_epoch=38, content_digest="b2"))

# t=40s: orchestrator revokes W1 at epoch 40; notice reaches E at epoch 44
sm.receive_revocation("W1", revoke_epoch=40)

# E attempts an action whose provenance includes the poisoned segment.
try:
    sm.authorize_action(
        warrant_id="W2",
        decision_provenance=["s_read_repo", "s_poisoned_priority"],
    )
except TaintFrontierViolation as e:
    # Correct outcome: halt, quarantine tainted context, require fresh warrant.
    print(f"halted: {e}")
