# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-draft-token-whose-provenance-warrant-has-expired-mid-verification.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-draft-token-whose-provenance-warrant-has-expired-mid-verification.warrant.json
# Markdown SHA-256:   6f1c11a157e306a7f7d1246b201244a8ddf439e0849bd91a1ca20bb044bea85b
# Code AST SHA-256:   40d73df35a9b4fc0329ef2c2c427fa208ffdeee0ef8c11a3e20b4d2a927c1210
# Verified Classes:   WarrantMarginExhausted, Warrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class WarrantMarginExhausted(RuntimeError):
    """Raised when a draft token cannot be committed within its warrant's validity margin."""
    pass


@dataclass
class Warrant:
    issuer: str
    not_before: float
    not_after: float

    @property
    def window(self) -> float:
        return self.not_after - self.not_before


def commit_draft_block(
    block: list[Warrant],
    *,
    now_verifier: float,
    max_skew: float,
    commit_latency_p99: float,
    abort_fraction: float = 0.4,
) -> list[int]:
    """
    Return indices of tokens safe to commit. Raises if the block is
    structurally unverifiable under the measured skew/commit margin.
    """
    margin = max_skew + commit_latency_p99
    safe: list[int] = []
    unsafe = 0

    for i, w in enumerate(block):
        if w.window <= 2 * max_skew + commit_latency_p99:
            # Window is too small to ever be soundly committed.
            unsafe += 1
            continue
        if w.not_before + max_skew > now_verifier:
            unsafe += 1
            continue
        if now_verifier + margin > w.not_after:
            unsafe += 1
            continue
        safe.append(i)

    if block and (unsafe / len(block)) >= abort_fraction:
        raise WarrantMarginExhausted(
            f"{unsafe}/{len(block)} tokens uncommittable under margin={margin:.3f}s; "
            f"proposer warrant TTL misconfigured for observed skew"
        )
    return safe


def verify_and_commit(block, *, now_verifier, max_skew, commit_latency_p99):
    safe = commit_draft_block(
        block,
        now_verifier=now_verifier,
        max_skew=max_skew,
        commit_latency_p99=commit_latency_p99,
    )
    if not safe:
        raise WarrantMarginExhausted("no tokens committable; resample from p_target as fresh proposal")
    return safe
