# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-rollback-when-parallel-agent-plans-share-a-non-idempotent-side-effect-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-rollback-when-parallel-agent-plans-share-a-non-idempotent-side-effect-ledger.warrant.json
# Markdown SHA-256:   15a70fe575520802fb81d5fb19628f0e9b35e979a8f3bf3e8905096c6de16a5e
# Code AST SHA-256:   584c57a38a37f8d4c24623ea3e4ddf437c2d0362a062e7e028db71044c3e1190
# Verified Classes:   SpeculativeRollbackError, EffectState, AllocationLog
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Optional


class SpeculativeRollbackError(RuntimeError):
    """Raised when a branch attempts to emit a non-idempotent effect without
    a reconciler-allocated commit token, or when commit-time coverage
    inference would re-emit an effect already marked escaped."""
    pass


class EffectState(Enum):
    PROPOSED = "proposed"
    ESCAPED = "escaped"
    REVOKED = "revoked"
    COMMITTED = "committed"


@dataclass
class AllocationLog:
    """Append-only ownership ledger. Survives branch rollback; tombstones
    escaped effects so sibling commits cannot infer coverage from a hole."""
    entries: Dict[str, EffectState] = field(default_factory=dict)

    def allocate(self, effect_id: str, branch: str) -> str:
        if effect_id in self.entries:
            raise SpeculativeRollbackError(
                f"effect {effect_id} already allocated to "
                f"{self.entries[effect_id]}; branch {branch} cannot own it"
            )
        token = f"{branch}:{effect_id}"
        self.entries[effect_id] = EffectState.PROPOSED
        return token

    def mark_escaped(self, effect_id: str) -> None:
        if self.entries.get(effect_id) != EffectState.PROPOSED:
            raise SpeculativeRollbackError(
                f"cannot mark {effect_id} escaped from state "
                f"{self.entries.get(effect_id)}"
            )
        self.entries[effect_id] = EffectState.ESCAPED

    def revoke(self, effect_id: str) -> None:
        # Rollback revokes intent but MUST leave a tombstone, never delete.
        if effect_id not in self.entries:
            raise SpeculativeRollbackError(
                f"revoke of unknown effect {effect_id}"
            )
        if self.entries[effect_id] == EffectState.PROPOSED:
            self.entries[effect_id] = EffectState.REVOKED
        # If already ESCAPED, tombstone stays ESCAPED — the effect happened.

    def commit(self, effect_id: str, branch: str) -> None:
        state = self.entries.get(effect_id)
        if state == EffectState.ESCAPED:
            # Accept the single escaped emission retroactively.
            self.entries[effect_id] = EffectState.COMMITTED
            return
        if state == EffectState.COMMITTED:
            raise SpeculativeRollbackError(
                f"double commit of {effect_id} by {branch}"
            )
        if state in (EffectState.REVOKED, None):
            raise SpeculativeRollbackError(
                f"branch {branch} commits {effect_id} in state {state}; "
                f"no live token"
            )
        self.entries[effect_id] = EffectState.COMMITTED


def emit_non_idempotent(log: AllocationLog, effect_id: str, branch: str) -> None:
    state = log.entries.get(effect_id)
    if state is None:
        raise SpeculativeRollbackError(
            f"branch {branch} attempted to emit {effect_id} without an "
            f"allocated commit token; speculative flush is forbidden"
        )
    if state == EffectState.ESCAPED:
        raise SpeculativeRollbackError(
            f"branch {branch} attempted to re-emit {effect_id} already "
            f"marked escaped; route to reconciler for compensation, do not "
            f"infer coverage from truncated intent index"
        )
    if state != EffectState.PROPOSED:
        raise SpeculativeRollbackError(
            f"branch {branch} cannot emit {effect_id} in state {state}"
        )
    log.mark_escaped(effect_id)


def rollback_branch(log: AllocationLog, effect_ids: list[str]) -> None:
    for eid in effect_ids:
        log.revoke(eid)  # tombstone preserved; never deletes


# Reproduction of the observed double-notice under the fixed protocol.
log = AllocationLog()
log.allocate("send_notice:4471", branch="A")
emit_non_idempotent(log, "send_notice:4471", branch="A")   # A flushes
rollback_branch(log, ["send_notice:4471"])                 # revoke -> stays ESCAPED

# Branch B's "ensure notice" step must now refuse to re-emit.
try:
    emit_non_idempotent(log, "send_notice:4471", branch="B")
except SpeculativeRollbackError as e:
    print(f"blocked duplicate: {e}")

log.commit("send_notice:4471", branch="A")                 # single committed owner
assert log.entries["send_notice:4471"] == EffectState.COMMITTED
