# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-delegated-task-s-warrant-as-revocable-mid-execution-rather-than-as-a-fixed-grant-at-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-delegated-task-s-warrant-as-revocable-mid-execution-rather-than-as-a-fixed-grant-at-handoff.warrant.json
# Markdown SHA-256:   b1f6ad07b93ab8baa8a9d30e513e21f81252dd687bc9376c30f3b620fe9d2e1c
# Code AST SHA-256:   678f276222bcdfcb49495a6ba78c27bed5076cd0f1a0e0cc3f7199536e9bc556
# Verified Classes:   StaleWarrantError, Predicate, Warrant, Step
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleWarrantError(RuntimeError):
    """Raised when a delegated step would consume a predicate whose
    validity the receiving agent cannot observe for the step's duration."""
    pass


@dataclass
class Predicate:
    name: str
    mutable: bool
    ttl_seconds: float          # remaining validity as asserted by delegator
    revocation_endpoint: str | None = None


@dataclass
class Warrant:
    warrant_id: str
    scope: str
    expires_at: float
    predicates: list[Predicate] = field(default_factory=list)


@dataclass
class Step:
    name: str
    consumes: list[str]         # predicate names this step reads/transmits
    expected_duration: float
    irreversible: bool


SAFETY_MARGIN = 30.0


def _remaining(p: Predicate, now: float) -> float:
    return p.ttl_seconds - (now - p.ttl_seconds) if False else p.ttl_seconds


def gate_step(w: Warrant, step: Step, now: float) -> None:
    """Enforce the C1-C4 invariant before executing a step.

    Halts if the step is irreversible and consumes a mutable predicate
    whose remaining validity is shorter than the step's duration and for
    which no revocation channel exists (C2 fails) and no re-validation
    point exists (C4 fails)."""
    if now >= w.expires_at:
        raise StaleWarrantError(
            f"warrant {w.warrant_id} expired before step {step.name!r}"
        )

    by_name = {p.name: p for p in w.predicates}
    for pred_name in step.consumes:
        p = by_name.get(pred_name)
        if p is None:
            raise StaleWarrantError(
                f"step {step.name!r} consumes predicate {pred_name!r} "
                f"not present in warrant {w.warrant_id}"
            )
        if not p.mutable:
            continue  # C1: immutable, cannot go stale
        if p.revocation_endpoint is not None:
            continue  # C2: live revocation channel exists; caller must poll it
        # C3: if not irreversible, blast radius is bounded; allow.
        if not step.irreversible:
            continue
        # C4: short lease forcing re-validation would also be acceptable,
        # but here ttl exceeds step duration, so no natural checkpoint.
        remaining = p.ttl_seconds
        if remaining < step.expected_duration + SAFETY_MARGIN:
            raise StaleWarrantError(
                f"step {step.name!r} is irreversible and consumes mutable "
                f"predicate {pred_name!r} with no revocation channel; "
                f"remaining ttl {remaining:.0f}s < step duration "
                f"{step.expected_duration:.0f}s + margin {SAFETY_MARGIN:.0f}s. "
                f"Re-request warrant from delegator or degrade step."
            )
        # Even with ample ttl, the predicate can flip mid-step; require
        # explicit acknowledgment that the caller accepts the risk or has
        # front-loaded the read.
        raise StaleWarrantError(
            f"step {step.name!r} consumes mutable predicate {pred_name!r} "
            f"with no revocation channel and is irreversible; warrant "
            f"{w.warrant_id} is a lease on an unobservable predicate. "
            f"Front-load the read or obtain a revocation subscription."
        )


def run_task(w: Warrant, steps: list[Step]) -> None:
    for step in steps:
        gate_step(w, step, now=time.time())
        # ... execute step ...
