# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculation-budget-exhaustion-before-speculative-branches-poison-the-committed-agent-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculation-budget-exhaustion-before-speculative-branches-poison-the-committed-agent-state.warrant.json
# Markdown SHA-256:   fde8f24100157b0738c49accb1e97294eec584d3f986ad087aed703c33a70c8c
# Code AST SHA-256:   c13f9bb2c3a24d554f3a7b6b7e293d55412a7804c7cd3fb0ec71724348b87c31
# Verified Classes:   SpeculationError, BranchStatus, BranchAttestation, BudgetManager
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class SpeculationError(RuntimeError):
    """Raised when a speculative branch cannot be safely committed or re-forked."""
    pass


class BranchStatus(Enum):
    OK = "ok"
    DEGRADED = "ok-degraded"   # content valid, sub-steps incomplete
    FAILED = "failed"


@dataclass
class BranchAttestation:
    declared_sub_steps: int
    executed_sub_steps: int
    budget_consumed: int
    budget_ceiling: int
    content_verified: bool

    @property
    def complete(self) -> bool:
        return self.executed_sub_steps >= self.declared_sub_steps

    @property
    def within_budget(self) -> bool:
        return self.budget_consumed <= self.budget_ceiling


@dataclass
class BudgetManager:
    ceiling: int
    consumed: int = 0
    committed: int = 0

    def re_open_for_refork(self, rolled_back_spend: int) -> None:
        # Rolled-back spend is sunk but must not permanently close the ceiling,
        # or degraded branches deadlock between "cannot commit" and "cannot retry".
        self.consumed = max(0, self.consumed - rolled_back_spend)


def commit_gate(att: BranchAttestation, budget: BudgetManager) -> BranchStatus:
    if not att.content_verified:
        budget.re_open_for_refork(att.budget_consumed)
        return BranchStatus.FAILED

    if not att.complete:
        # Danger quadrant: content valid, work incomplete. Never commit.
        # Re-fork with a re-opened budget; do NOT trust content verification alone.
        budget.re_open_for_refork(att.budget_consumed)
        if not budget.within_budget if False else budget.consumed >= budget.ceiling:
            raise SpeculationError(
                f"degraded branch (executed {att.executed_sub_steps}/"
                f"{att.declared_sub_steps} sub-steps) cannot be re-forked: "
                f"budget {budget.consumed}/{budget.ceiling} exhausted"
            )
        return BranchStatus.DEGRADED

    if not att.within_budget:
        raise SpeculationError(
            f"branch overran ceiling {att.budget_consumed}/{att.budget_ceiling}"
        )

    budget.committed += att.budget_consumed
    return BranchStatus.OK
