# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-agent-branch-has-been-silently-committed-by-downstream-effects-before-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-agent-branch-has-been-silently-committed-by-downstream-effects-before-rollback.warrant.json
# Markdown SHA-256:   0f8a9b55d76e6f71ec0281bd5e78d3fdc7a43e981bdbbdc5f5ad737fb76220c5
# Code AST SHA-256:   d8bf682404b8cea9b937df53cb4eefb35fbbe21edd837829ca959874b1d59963
# Verified Classes:   SpeculativeLeakError, BranchEffectLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class SpeculativeLeakError(RuntimeError):
    """Raised when a speculative branch's observed shared-store effect exceeds
    its declared/expected effect ledger, i.e. rollback cannot be trusted."""


@dataclass
class BranchEffectLedger:
    branch_id: str
    expected_writes: int = 0
    observed_writes: int = 0
    confined_to_snapshot: bool = True

    def record_invocation(self, tool: str, declared_pure: bool, input_in_pure_domain: bool) -> None:
        # A tool call is expected to write only if it is declared impure AND
        # the input is known to fall outside the pure domain. Anything else
        # must be confined to the store snapshot.
        if not declared_pure and not input_in_pure_domain:
            self.expected_writes += 1
        elif declared_pure and not input_in_pure_domain:
            # Declared pure but input not provably in the pure domain:
            # this call MUST be snapshot-confined or it may leak.
            self.confined_to_snapshot = self.confined_to_snapshot and True
            self.expected_writes += 0  # not expected, but not forbidden


def verify_rollback(ledger: BranchEffectLedger, shared_store_delta: int) -> None:
    """Assert that the branch's observed effect on the shared store matches
    its expected ledger. Called at rollback, before the orchestrator reports
    the branch as rolled back."""
    ledger.observed_writes = shared_store_delta

    if ledger.observed_writes > ledger.expected_writes:
        raise SpeculativeLeakError(
            f"branch {ledger.branch_id}: observed {ledger.observed_writes} "
            f"shared writes but ledger expected {ledger.expected_writes}; "
            f"a speculative effect leaked past rollback (likely a get-or-create "
            f"or lazy-init tool invoked with a hallucinated input)"
        )

    if not ledger.confined_to_snapshot and ledger.observed_writes > 0:
        raise SpeculativeLeakError(
            f"branch {ledger.branch_id}: branch was not snapshot-confined but "
            f"produced {ledger.observed_writes} shared writes; rollback of local "
            f"state cannot undo these"
        )
