# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-delegated-warrant-as-expired-before-its-parent-revokes-it.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-delegated-warrant-as-expired-before-its-parent-revokes-it.warrant.json
# Markdown SHA-256:   ccca212354863f342178dc6d7a0adbc6d1224cbf565a9ac26b1f3367acb4e5cf
# Code AST SHA-256:   f5f69af46a933829fe36700bcbfdf633d0adb66926ef7655c2d4da94307d1a6c
# Verified Classes:   StaleWarrantError, Warrant, LivenessProof, DelegatedInstance
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleWarrantError(RuntimeError):
    """Raised when an instance cannot prove root liveness within its freshness bound."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    parent_id: str | None
    scope: str
    expires_at: float
    derivation_path: tuple[str, ...]  # signed chain back to root


@dataclass(frozen=True)
class LivenessProof:
    root_id: str
    confirmed_at: float
    signature_ok: bool


class DelegatedInstance:
    def __init__(self, instance_id: str, delta: float, clock=time.monotonic):
        self.instance_id = instance_id
        self.delta = delta
        self.clock = clock
        self._last_liveness: LivenessProof | None = None
        self._revoked_lineage: set[str] = set()

    def record_liveness(self, proof: LivenessProof) -> None:
        if not proof.signature_ok:
            raise StaleWarrantError(f"{self.instance_id}: liveness proof signature invalid")
        self._last_liveness = proof

    def record_revocation(self, revoked_warrant_id: str) -> None:
        # transitive invalidation: any descendant whose path contains the
        # revoked id is dead, regardless of its own TTL.
        self._revoked_lineage.add(revoked_warrant_id)

    def _lineage_dead(self, w: Warrant) -> bool:
        return any(ancestor in self._revoked_lineage for ancestor in w.derivation_path)

    def authorize(self, w: Warrant, action_duration: float) -> None:
        now = self.clock()

        if not w.derivation_path or w.derivation_path[-1] != w.warrant_id:
            raise StaleWarrantError(
                f"{self.instance_id}: warrant {w.warrant_id} has no verifiable lineage to root"
            )

        if self._lineage_dead(w):
            raise StaleWarrantError(
                f"{self.instance_id}: warrant {w.warrant_id} derives from revoked lineage"
            )

        if now >= w.expires_at:
            raise StaleWarrantError(
                f"{self.instance_id}: warrant {w.warrant_id} TTL expired"
            )

        if self._last_liveness is None:
            raise StaleWarrantError(
                f"{self.instance_id}: no root-liveness proof on record; cannot bound staleness"
            )

        age = now - self._last_liveness.confirmed_at
        if age > self.delta:
            raise StaleWarrantError(
                f"{self.instance_id}: root liveness stale by {age - self.delta:.1f}s "
                f"(bound Δ={self.delta}s); refusing authority-bearing action"
            )

        if action_duration > (self.delta - age):
            raise StaleWarrantError(
                f"{self.instance_id}: action duration {action_duration:.1f}s would exceed "
                f"remaining freshness {self.delta - age:.1f}s; must checkpoint and re-confirm"
            )
        # action permitted
