# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-capability-attestation-as-expired-at-the-moment-of-execution-rather-than-at-the-moment-of-verifi.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-capability-attestation-as-expired-at-the-moment-of-execution-rather-than-at-the-moment-of-verifi.warrant.json
# Markdown SHA-256:   157c5f1657e8447429398f38417bb5d01827e2de3337de5a32ac93c88c9f6572
# Code AST SHA-256:   f4125228152087fd9d585c506b7de716a8e7cd6246445f208cac95419403e738
# Verified Classes:   RuntimeDriftError, AttestationExpiredError, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class RuntimeDriftError(RuntimeError):
    """Raised when a callee's live runtime no longer matches the attested tuple."""


class AttestationExpiredError(RuntimeError):
    """Raised when a warrant's not_after has passed at execution time."""


@dataclass(frozen=True)
class Warrant:
    subject: str
    model_fingerprint: str
    tool_manifest_hash: str
    not_before: float
    not_after: float


def measure_runtime(model_bytes: bytes, manifest_bytes: bytes) -> tuple[str, str]:
    return (
        "sha256:" + hashlib.sha256(model_bytes).hexdigest(),
        "sha256:" + hashlib.sha256(manifest_bytes).hexdigest(),
    )


def authorize_side_effect(
    warrant: Warrant,
    model_bytes: bytes,
    manifest_bytes: bytes,
    now: float,
) -> None:
    # Execution-clock check: expiry is evaluated HERE, not at dispatch.
    if now >= warrant.not_after:
        raise AttestationExpiredError(
            f"warrant for {warrant.subject} expired at execution: "
            f"now={now} not_after={warrant.not_after}"
        )
    if now < warrant.not_before:
        raise AttestationExpiredError(
            f"warrant for {warrant.subject} not yet valid: now={now}"
        )

    live_model, live_manifest = measure_runtime(model_bytes, manifest_bytes)

    if live_model != warrant.model_fingerprint:
        raise RuntimeDriftError(
            f"model drift for {warrant.subject}: "
            f"attested={warrant.model_fingerprint} live={live_model}"
        )
    if live_manifest != warrant.tool_manifest_hash:
        raise RuntimeDriftError(
            f"tool manifest drift for {warrant.subject}: "
            f"attested={warrant.tool_manifest_hash} live={live_manifest}"
        )
    # Only here, with both clocks and runtime identity confirmed, may the
    # caller proceed to the side-effecting action.
