# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-brokered-capability-grant-as-invalid-the-moment-the-broker-s-trust-attestation-expires-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-brokered-capability-grant-as-invalid-the-moment-the-broker-s-trust-attestation-expires-mid-execution.warrant.json
# Markdown SHA-256:   5cf90c3b78e90b2da56eacb5ca301b8d4a12c5ebdd5d5429378cfa22232bca3a
# Code AST SHA-256:   8009c776c9d3286ca5f5132198eb62a33e39c538724ba013805f213333c92289
# Verified Classes:   TrustChainBroken, Attestation, Grant, Worker
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TrustChainBroken(RuntimeError):
    """Raised when a worker attempts a durable effect under an attestation
    that is no longer valid at commit time."""
    pass


@dataclass
class Attestation:
    attestation_id: str
    broker_key_id: str
    not_after: float          # epoch seconds
    revoked: bool = False


@dataclass
class Grant:
    grant_id: str
    capability: str
    resource_scope: str
    attestation: Attestation
    not_after: float


@dataclass
class Worker:
    grant: Grant
    admitted_at: float
    max_slice: float = 120.0
    last_verified_at: float = field(default_factory=time.time)

    def _attestation_valid(self, now: float, skew: float = 5.0) -> bool:
        a = self.grant.attestation
        if a.revoked:
            return False
        if now + skew >= a.not_after:
            return False
        return True

    def checkpoint(self, now: Optional[float] = None) -> None:
        """Must be called before any durable effect. Raises if the trust
        chain has decayed since admission or since the last checkpoint."""
        now = now if now is not None else time.time()

        if now - self.last_verified_at > self.max_slice:
            raise TrustChainBroken(
                f"execution slice exceeded max_slice={self.max_slice}s "
                f"without re-verification; grant={self.grant.grant_id}"
            )

        if not self._attestation_valid(now):
            raise TrustChainBroken(
                f"attestation {self.grant.attestation.attestation_id} "
                f"invalid at commit time (revoked={self.grant.attestation.revoked}, "
                f"not_after={self.grant.attestation.not_after}, now={now}); "
                f"grant={self.grant.grant_id} is unbacked — re-broker required"
            )

        # Grant TTL is checked separately; note that a live grant under a
        # dead attestation is exactly the orphaned-effect case.
        if now >= self.grant.not_after:
            raise TrustChainBroken(
                f"grant {self.grant.grant_id} expired at {self.grant.not_after}"
            )

        self.last_verified_at = now

    def commit_effect(self, effect: dict, now: Optional[float] = None) -> dict:
        self.checkpoint(now=now)
        return {
            "effect": effect,
            "grant_id": self.grant.grant_id,
            "attestation_id": self.grant.attestation.attestation_id,
            "verified_at": self.last_verified_at,
        }


# --- reproduction of the observed trace ---
if __name__ == "__main__":
    att = Attestation("A", "broker-key-7", not_after=300.0)
    grant = Grant("G", "purchase_order.commit", "supplier:acme-42", att, not_after=900.0)
    w = Worker(grant=grant, admitted_at=0.0, max_slice=600.0, last_verified_at=0.0)

    # t=310: attestation expired, grant still live. Worker tries to commit.
    try:
        w.commit_effect({"po": "PO-9931"}, now=310.0)
    except TrustChainBroken as e:
        print(f"HALTED: {e}")
        # orchestrator must re-broker before retrying
