# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-arbitrate-context-window-budget-across-concurrent-subagents-that-share-a-memory-pool.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-arbitrate-context-window-budget-across-concurrent-subagents-that-share-a-memory-pool.warrant.json
# Markdown SHA-256:   c874cb25734d04ab049d485e687f27ccb338eb7cc20afdbbe42ea10258bb3d2e
# Code AST SHA-256:   ce0d4376ffa5bfeee30361c7c7909d3ac63a5edaa73d4a8d9a9bec72bd7304b0
# Verified Classes:   ContextBudgetOvercommit, Subagent
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ContextBudgetOvercommit(RuntimeError):
    """Raised when aggregate retrieval-inflated context exceeds the usable window."""
    pass


@dataclass
class Subagent:
    name: str
    nominal_budget: int
    private_working: int


def reserve_shared_pool(
    subagents: list[Subagent],
    hot_region_tokens: int,
    orchestrator_retained: int,
    usable_window: int,
    safety_factor: float = 0.7,
) -> dict:
    """
    Arbitrate context budget for concurrent subagents sharing a memory pool.

    Rejects the scalar model: reserves against N * hot_region (salience-correlated
    redundant retrieval) plus private working state plus orchestrator retention.
    """
    n = len(subagents)
    if n == 0:
        raise ContextBudgetOvercommit("no subagents to reserve for")

    # Worst case: every subagent re-retrieves the full hot region.
    redundant_hot = n * hot_region_tokens
    private_total = sum(s.private_working for s in subagents)
    aggregate = redundant_hot + private_total + orchestrator_retained
    ceiling = int(usable_window * safety_factor)

    if aggregate > ceiling:
        # Try the shared-digest mitigation: materialize hot region once.
        digest_tokens = max(1, hot_region_tokens // 7)
        mitigated = digest_tokens + private_total + orchestrator_retained
        if mitigated > ceiling:
            raise ContextBudgetOvercommit(
                f"aggregate {aggregate} > ceiling {ceiling} even with shared digest "
                f"({mitigated}); serialize contending subagents or reduce fan-out"
            )
        return {
            "mode": "shared_digest",
            "aggregate": mitigated,
            "digest_tokens": digest_tokens,
            "ceiling": ceiling,
        }

    return {"mode": "nominal", "aggregate": aggregate, "ceiling": ceiling}


# Example trigger: 6 subagents, 9k hot entries x5 = 45k hot region.
try:
    plan = reserve_shared_pool(
        subagents=[Subagent(f"sa{i}", 24_000, 12_000) for i in range(6)],
        hot_region_tokens=45_000,
        orchestrator_retained=50_000,
        usable_window=200_000,
    )
    print(plan)
except ContextBudgetOvercommit as e:
    raise ContextBudgetOvercommit(f"fan-out rejected: {e}") from None
