# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-arbitrate-a-single-context-budget-between-compaction-retrieval-and-scratchpad-when-the-latency-slo-is-already-the-binding-const.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-arbitrate-a-single-context-budget-between-compaction-retrieval-and-scratchpad-when-the-latency-slo-is-already-the-binding-const.warrant.json
# Markdown SHA-256:   99b895b26a000d2467248ebedf4f55372eb39b3a18a9a89f689fe82b8b239ed9
# Code AST SHA-256:   d187ad8ac1b07050322e6226ac9c1fce913180944f5343d98a2722e4b3a9fe6d
# Verified Classes:   ContextBudgetViolation, ScratchpadNode, RetrievalChunk
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ContextBudgetViolation(RuntimeError):
    """Raised when arbitration would trim a hard (non-reconstructible) consumer."""


@dataclass
class ScratchpadNode:
    seq: int
    payload: str
    length: int = field(init=False)
    digest: str = field(init=False)

    def __post_init__(self) -> None:
        self.length = len(self.payload)
        self.digest = hashlib.sha256(self.payload.encode()).hexdigest()

    def verify(self) -> None:
        if len(self.payload) != self.length:
            raise ContextBudgetViolation(
                f"scratchpad node {self.seq} corrupt: length {len(self.payload)} "
                f"!= recorded {self.length}; treat as CORRUPT, not empty"
            )
        if hashlib.sha256(self.payload.encode()).hexdigest() != self.digest:
            raise ContextBudgetViolation(
                f"scratchpad node {self.seq} corrupt: digest mismatch"
            )


@dataclass
class RetrievalChunk:
    chunk_id: str
    grounds_commitments: frozenset[str]


def arbitrate(
    budget_tokens: int,
    scratchpad: list[ScratchpadNode],
    retrieval: list[RetrievalChunk],
    live_commitments: set[str],
    compaction_floor: int,
) -> dict[str, int]:
    """Allocate budget: scratchpad first (hard), retrieval whole-or-nothing
    (hard if it grounds a live commitment), compaction absorbs the rest."""
    scratch_cost = sum(len(n.payload) for n in scratchpad)
    if scratch_cost > budget_tokens:
        raise ContextBudgetViolation(
            f"scratchpad needs {scratch_cost} tokens but only {budget_tokens} "
            f"available; refusing to truncate durable state — abort step or "
            f"request more budget"
        )

    remaining = budget_tokens - scratch_cost

    # Retrieval is trimmable only if dropping a chunk grounds no live commitment.
    kept: list[RetrievalChunk] = []
    for chunk in retrieval:
        if chunk.grounds_commitments & live_commitments:
            kept.append(chunk)  # load-bearing: cannot drop
    retrieval_cost = len(kept)  # 1 token per chunk proxy
    if retrieval_cost > remaining:
        raise ContextBudgetViolation(
            f"load-bearing retrieval needs {retrieval_cost} tokens, only "
            f"{remaining} left after scratchpad; cannot silently drop a "
            f"commitment anchor"
        )

    remaining -= retrieval_cost
    if remaining < compaction_floor:
        raise ContextBudgetViolation(
            f"compaction floor {compaction_floor} exceeds residual {remaining}; "
            f"soft consumer cannot absorb further pressure"
        )

    return {
        "scratchpad": scratch_cost,
        "retrieval": retrieval_cost,
        "compaction": remaining,
    }
