# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-trust-anchor-that-validates-but-has-expired-mid-handoff-in-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-trust-anchor-that-validates-but-has-expired-mid-handoff-in-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   58288686a4a0a2c6362e0413cc9f2da5bf388049462a729eba5e7f3ff1b92033
# Code AST SHA-256:   132d9c403f293e0e1dcf83efef557a340b93626bc03c3ea4409f4d04a68c7a04
# Verified Classes:   StaleAnchorError, DelegatedAnchor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAnchorError(RuntimeError):
    """Raised when a delegated trust anchor has expired at time-of-effect."""
    pass


@dataclass(frozen=True)
class DelegatedAnchor:
    anchor_id: str
    subject: str
    scope: str
    not_before: float
    not_after: float


def assert_anchor_live_at_effect(
    anchor: DelegatedAnchor,
    effect_name: str,
    clock_drift_bound: float,
    now: float | None = None,
) -> float:
    """
    Re-evaluate a delegated anchor against the relying party's clock
    immediately before an irreversible effect. Returns the clock reading
    used, so it can be signed into the execution log for auditor replay.

    Fails closed when the relying party's drift bound exceeds the anchor's
    remaining validity, because the comparison would be meaningless.
    """
    if now is None:
        now = time.time()

    if now < anchor.not_before:
        raise StaleAnchorError(
            f"anchor {anchor.anchor_id} not yet valid for effect {effect_name!r}: "
            f"now={now:.3f} not_before={anchor.not_before:.3f}"
        )

    remaining = anchor.not_after - now
    if remaining <= 0.0:
        raise StaleAnchorError(
            f"anchor {anchor.anchor_id} expired before effect {effect_name!r}: "
            f"now={now:.3f} not_after={anchor.not_after:.3f} "
            f"lapsed={-remaining:.3f}s"
        )

    if clock_drift_bound >= remaining:
        raise StaleAnchorError(
            f"anchor {anchor.anchor_id} cannot be proven live for effect "
            f"{effect_name!r}: drift_bound={clock_drift_bound:.3f}s "
            f">= remaining={remaining:.3f}s; failing closed"
        )

    return now


def execute_irreversible_effect(
    anchor: DelegatedAnchor,
    effect_name: str,
    clock_drift_bound: float,
    perform,
) -> float:
    """Guard then perform an irreversible effect; log the effect-time clock."""
    effect_clock = assert_anchor_live_at_effect(
        anchor, effect_name, clock_drift_bound
    )
    perform()
    return effect_clock
