# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-revocation-proof-is-newer-than-its-own-witness.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-revocation-proof-is-newer-than-its-own-witness.warrant.json
# Markdown SHA-256:   07c30f5037f74745e92483928e3b9d8ac2110f628df1c7a9cea2d33ff18a82b6
# Code AST SHA-256:   2387991f9664da710412e1d82e4dd9c4d1d5d88e12898fc98fbdf563c4a646df
# Verified Classes:   StaleWitnessError, Witness, ExecutorState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleWitnessError(RuntimeError):
    """Raised when a delegated credential's revocation witness cannot be
    proven current relative to the executor's own clock and revocation frontier."""


@dataclass(frozen=True)
class Witness:
    cred_id: str
    not_revoked_as_of: float   # instant W, signed by witness service
    epoch: int                 # revocation epoch the witness observed
    signature_valid: bool


@dataclass(frozen=True)
class ExecutorState:
    now: float                 # trusted local clock
    current_epoch: int         # executor's revocation frontier
    max_witness_age: float     # per-hop policy, NOT a credential field


def admit_delegated(cred_id: str, w: Witness, st: ExecutorState) -> bool:
    if not w.signature_valid:
        raise StaleWitnessError(f"witness signature invalid for {cred_id}")
    if w.cred_id != cred_id:
        raise StaleWitnessError(
            f"witness binding mismatch: witness for {w.cred_id}, presented for {cred_id}"
        )

    age = st.now - w.not_revoked_as_of
    if age < 0:
        raise StaleWitnessError(
            f"future witness for {cred_id}: W={w.not_revoked_as_of} > now={st.now}"
        )
    if age > st.max_witness_age:
        # The credential may be revoked in the gap (W, now]. Fail closed.
        raise StaleWitnessError(
            f"stale witness for {cred_id}: age={age:.1f}s exceeds "
            f"max_witness_age={st.max_witness_age:.1f}s"
        )
    if st.current_epoch < w.epoch:
        # Executor is behind the revocation frontier the witness observed.
        raise StaleWitnessError(
            f"epoch regression for {cred_id}: executor epoch={st.current_epoch} "
            f"< witness epoch={w.epoch}"
        )
    return True


# --- exercise the boundary ---
if __name__ == "__main__":
    now = time.time()
    w = Witness(cred_id="worker-7", not_revoked_as_of=now - 40, epoch=11,
                signature_valid=True)
    st = ExecutorState(now=now, current_epoch=11, max_witness_age=30)
    try:
        admit_delegated("worker-7", w, st)   # 40s > 30s -> must refuse
    except StaleWitnessError as e:
        print(f"refused as required: {e}")
