# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-leakage-from-corrupting-shared-planner-state-in-multi-agent-dag-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-leakage-from-corrupting-shared-planner-state-in-multi-agent-dag-execution.warrant.json
# Markdown SHA-256:   ae8c6e5134cd08f1703a96963c46fbd7bdec2a77859152212db1770eeb2f876b
# Code AST SHA-256:   3030cb9533bf2c438d0f89d59619c7c0de2ad774d1c3892b00a1f1e221c92ac1
# Verified Classes:   SpeculativeLeakError, BudgetExhaustedError, BranchScope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Any


class SpeculativeLeakError(RuntimeError):
    """Raised when a speculative branch's state footprint escapes its isolation scope."""
    pass


class BudgetExhaustedError(RuntimeError):
    """Raised when speculative metering would debit the committed-path budget."""
    pass


@dataclass
class BranchScope:
    task_id: str
    branch_path: tuple[str, ...]  # hierarchical: ("N_k", "B_2", "N_k+1", "B_1")
    committed: bool = False
    writes: dict[str, Any] = field(default_factory=dict)
    tokens_spent: int = 0

    def namespace_key(self, logical_key: str) -> str:
        # Hierarchical namespace: depth-N speculation cannot collide with siblings.
        path = "/".join(self.branch_path)
        return f"spec/{self.task_id}/{path}/{logical_key}"


def write_speculative(scope: BranchScope, logical_key: str, value: Any) -> str:
    if scope.committed:
        raise SpeculativeLeakError(
            f"branch {scope.branch_path} already committed; speculative write forbidden"
        )
    key = scope.namespace_key(logical_key)
    scope.writes[key] = value
    return key


def commit_branch(scope: BranchScope, committed_store: dict[str, Any],
                  committed_budget: dict[str, int]) -> None:
    # Invariant: every write must be inside this branch's namespace prefix.
    prefix = f"spec/{scope.task_id}/{'/'.join(scope.branch_path)}/"
    for key in scope.writes:
        if not key.startswith(prefix):
            raise SpeculativeLeakError(
                f"commit refused: write {key!r} escapes branch scope {prefix!r}"
            )
    # Budget invariant: speculative tokens never debit the committed budget.
    if scope.tokens_spent > committed_budget.get("speculative_remaining", 0):
        raise BudgetExhaustedError(
            f"branch {scope.branch_path} exceeded speculative sub-budget "
            f"({scope.tokens_spent} > {committed_budget.get('speculative_remaining', 0)})"
        )
    for key, value in scope.writes.items():
        committed_store[key.removeprefix(prefix)] = value
    committed_budget["speculative_remaining"] -= scope.tokens_spent
    scope.committed = True


def rollback_branch(scope: BranchScope, committed_store: dict[str, Any]) -> None:
    # Discard must be a single namespace-scoped delete; nothing reachable from committed reads.
    prefix = f"spec/{scope.task_id}/{'/'.join(scope.branch_path)}/"
    leaked = [k for k in committed_store if k.startswith(prefix)]
    if leaked:
        raise SpeculativeLeakError(
            f"rollback of {scope.branch_path} found committed keys under spec prefix: {leaked!r}"
        )
    scope.writes.clear()
    scope.committed = False
