# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-s-tool-side-effects-have-already-escaped-the-rollback-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-s-tool-side-effects-have-already-escaped-the-rollback-horizon.warrant.json
# Markdown SHA-256:   6d11ba7edee05c295e8c73b431b5dded40b0b116796d8523345ee4e5f6e4023b
# Code AST SHA-256:   c313d9b42c0d40c8cacb55f2756bd7bf0d7b1d0f82abd451e4fd848f19b958a1
# Verified Classes:   RollbackHorizonBreach
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class RollbackHorizonBreach(RuntimeError):
    """Raised when a speculative branch produced an external effect that
    survived snapshot rollback and is not accounted for by the committed ledger."""
    pass


REVERSIBLE = "reversible"
IDEMPOTENT = "idempotent"
IRREVERSIBLE = "irreversible"


def classify_speculatable(effect_class: str, key_provenance: frozenset[str]) -> bool:
    if effect_class == REVERSIBLE:
        return True
    if effect_class == IDEMPOTENT:
        # A branch-derived key defeats idempotency across branch identity.
        return "branch_id" not in key_provenance and "attempt_nonce" not in key_provenance
    return False


def dispatch_speculative(call, branch_id, committed_ledger, external_audit):
    if not classify_speculatable(call.effect_class, call.key_provenance):
        raise RollbackHorizonBreach(
            f"tool {call.name!r} in branch {branch_id!r} is not speculatable: "
            f"effect_class={call.effect_class!r}, key_provenance={sorted(call.key_provenance)}; "
            f"pin behind commit instead"
        )
    result = call.invoke()
    committed_ledger.record(branch_id, call)
    return result


def reconcile_after_commit(committed_ledger, external_audit):
    for intent, committed_count in committed_ledger.count_by_intent().items():
        observed = external_audit.count_by_intent(intent)
        if observed != committed_count:
            raise RollbackHorizonBreach(
                f"intent {intent!r}: committed ledger claims {committed_count} "
                f"effect(s) but external audit shows {observed}; "
                f"a speculative branch escaped the rollback horizon"
            )
