# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-silently-outlived-its-verification-warrant-in-cost-aware-multi-agent-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-silently-outlived-its-verification-warrant-in-cost-aware-multi-agent-rollback.warrant.json
# Markdown SHA-256:   a6f34cee44ff8a4a54e7d094f8297f5f22086f6a4242dae71dd9fd8972d7b909
# Code AST SHA-256:   25752952f16e3f45846e55e6229908531b4b9afb636018982bf5b37c25841a18
# Verified Classes:   WarrantViolation, Checkpoint, Verdict, Branch
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class WarrantViolation(RuntimeError):
    """Raised when a speculative branch attempts to commit under an expired or
    structurally mismatched verification warrant."""
    pass


@dataclass
class Checkpoint:
    hash: str
    time: float


@dataclass
class Verdict:
    branch_id: str
    checkpoint_hash: str
    valid_until: float
    cost_generation: int
    score: float


@dataclass
class Branch:
    branch_id: str
    current: Checkpoint
    cost_generation: int = 0
    quarantined: bool = False


def reallocate_budget(branch: Branch, extra_usd: float) -> None:
    # Budget reallocation mutates the execution envelope (deadline, step ceiling),
    # so it MUST bump the cost generation. Forgetting this is the root cause.
    branch.cost_generation += 1


def commit_branch(branch: Branch, verdict: Optional[Verdict], now: Optional[float] = None) -> str:
    now = time.time() if now is None else now

    if branch.quarantined:
        raise WarrantViolation(f"{branch.branch_id}: branch is quarantined; cannot commit")

    if verdict is None or verdict.branch_id != branch.branch_id:
        raise WarrantViolation(f"{branch.branch_id}: no matching verdict")

    if verdict.checkpoint_hash != branch.current.hash:
        branch.quarantined = True
        raise WarrantViolation(
            f"{branch.branch_id}: checkpoint divergence "
            f"(scored {verdict.checkpoint_hash} vs current {branch.current.hash}); quarantined"
        )

    if verdict.cost_generation != branch.cost_generation:
        branch.quarantined = True
        raise WarrantViolation(
            f"{branch.branch_id}: cost generation mismatch "
            f"(verdict gen {verdict.cost_generation} vs branch gen {branch.cost_generation}); "
            f"reallocation invalidated the warrant; quarantined"
        )

    if now > verdict.valid_until:
        raise WarrantViolation(
            f"{branch.branch_id}: warrant expired at {verdict.valid_until:.0f}; "
            f"state unchanged, re-verify cheaply"
        )

    return f"committed:{branch.branch_id}:{verdict.checkpoint_hash}"


def _demo() -> None:
    t0 = 1000.0
    b = Branch("B2", Checkpoint("h2@40s", t0 + 40))
    verdict = Verdict("B2", "h2@40s", valid_until=t0 + 60, cost_generation=0, score=0.81)

    # Benign case: commit succeeds.
    assert commit_branch(b, verdict, now=t0 + 50).startswith("committed")

    # Reallocation resets budget -> generation bumps -> warrant is now stale.
    reallocate_budget(b, extra_usd=0.15)
    try:
        commit_branch(b, verdict, now=t0 + 52)
    except WarrantViolation as e:
        print("blocked as expected:", e)


if __name__ == "__main__":
    _demo()
