# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fail-to-roll-back-a-speculative-sub-agent-when-the-divergence-is-detected-after-the-branch-has-already-committed-writes-to-shared.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fail-to-roll-back-a-speculative-sub-agent-when-the-divergence-is-detected-after-the-branch-has-already-committed-writes-to-shared.warrant.json
# Markdown SHA-256:   340ae7ff82770b919f808ef9de4a42f68cb487579b0f739deb54cbe4ee6297e6
# Code AST SHA-256:   d38e77ed3f8748539ffd797f11ec4aa9d2425064ba4e4e9370c7440b799aa748
# Verified Classes:   SpeculativeRollbackError, Write, SharedStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any

class SpeculativeRollbackError(RuntimeError):
    """Raised when a branch abort would leave committed state depending on an aborted epoch."""
    pass

@dataclass
class Write:
    branch_id: str
    epoch: int
    key: str
    value: Any
    reversible: bool

@dataclass
class SharedStore:
    committed: dict[str, Any] = field(default_factory=dict)
    # read_edges[(reader_branch, key)] = set of (writer_branch, epoch)
    read_edges: dict[tuple[str, str], set[tuple[str, int]]] = field(default_factory=dict)
    write_log: list[Write] = field(default_factory=list)

    def read(self, branch_id: str, key: str) -> Any:
        # record that this branch read this key, attributing to whoever last wrote it
        writers = {(w.branch_id, w.epoch) for w in self.write_log if w.key == key}
        self.read_edges.setdefault((branch_id, key), set()).update(writers)
        return self.committed.get(key)

def abort_branch(store: SharedStore, branch_id: str, epoch: int) -> None:
    """Roll back a divergent branch. Refuses if dependents or irreversible writes exist."""
    branch_writes = [w for w in store.write_log if w.branch_id == branch_id and w.epoch == epoch]
    if not branch_writes:
        return  # nothing to roll back; context discard is sufficient

    # 1. Irreversible writes cannot be compensated.
    irreversible = [w for w in branch_writes if not w.reversible]
    if irreversible:
        raise SpeculativeRollbackError(
            f"branch {branch_id}@{epoch} has irreversible writes "
            f"{[w.key for w in irreversible]}; quarantine cohort, do not abort"
        )

    # 2. Find every reader that conditioned on this branch's writes.
    doomed_keys = {w.key for w in branch_writes}
    dependents: set[str] = set()
    for (reader, key), writers in store.read_edges.items():
        if key in doomed_keys and (branch_id, epoch) in writers and reader != branch_id:
            dependents.add(reader)

    if dependents:
        raise SpeculativeRollbackError(
            f"branch {branch_id}@{epoch} writes were read by {sorted(dependents)}; "
            f"abort would leave committed state depending on an aborted epoch"
        )

    # 3. Safe: drop the branch's uncommitted writes and its log entries.
    store.write_log = [w for w in store.write_log if not (w.branch_id == branch_id and w.epoch == epoch)]
    for w in branch_writes:
        # restore prior committed value if any; overlay semantics
        store.committed.pop(w.key, None)
