# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-multi-agent-branch-has-crossed-the-commit-ordering-horizon-before-rollback-convergence.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-multi-agent-branch-has-crossed-the-commit-ordering-horizon-before-rollback-convergence.warrant.json
# Markdown SHA-256:   58752ee5be065f8bb5a80597a73d0e3a2726d8ebe6fa7a6aa07cddf4419aeede
# Code AST SHA-256:   c8d0a3d40a5c211de1a4999c8a5f59544625c4a53d0d52f71554c397cc26cc61
# Verified Classes:   SpeculativeOrderingViolation, Branch, SpeculativeOrchestrator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class SpeculativeOrderingViolation(RuntimeError):
    """Raised when a branch escapes its abort domain or a rollback reports
    convergence without enumerating the transitive closure of readers."""
    pass


@dataclass
class Branch:
    id: str
    staged_keys: Set[str] = field(default_factory=set)
    durable_emitted: bool = False
    abort_domain: str = ""          # branches sharing this id abort together
    committed: bool = False
    rolled_back: bool = False
    read_from: Set[str] = field(default_factory=set)  # branch ids read from


class SpeculativeOrchestrator:
    def __init__(self) -> None:
        self.branches: Dict[str, Branch] = {}

    def register(self, b: Branch) -> None:
        self.branches[b.id] = b

    def read_staged(self, reader_id: str, source_id: str) -> None:
        """Enforce the read-time gate: a reader of staged state must share the
        source's abort domain, or the read is refused."""
        reader = self.branches[reader_id]
        source = self.branches[source_id]
        if source.committed:
            reader.read_from.add(source_id)
            return
        if reader.abort_domain != source.abort_domain:
            raise SpeculativeOrderingViolation(
                f"branch {reader_id} attempted to read staged state of "
                f"{source_id} while in a different abort domain "
                f"({reader.abort_domain!r} vs {source.abort_domain!r}); "
                f"reader would outlive source's rollback"
            )
        reader.read_from.add(source_id)

    def emit_durable(self, branch_id: str) -> None:
        b = self.branches[branch_id]
        if b.rolled_back:
            raise SpeculativeOrderingViolation(
                f"branch {branch_id} attempted durable emission after rollback"
            )
        b.durable_emitted = True

    def rollback(self, branch_id: str) -> Set[str]:
        """Roll back a branch and verify convergence over the transitive
        closure of readers. Returns the set of branches aborted."""
        target = self.branches[branch_id]
        domain = target.abort_domain
        aborted = {
            bid for bid, b in self.branches.items()
            if b.abort_domain == domain and not b.committed
        }
        # transitive closure of readers of any aborted branch
        readers: Set[str] = set()
        frontier = set(aborted)
        while frontier:
            nxt = set()
            for bid, b in self.branches.items():
                if bid in readers or bid in aborted:
                    continue
                if b.read_from & frontier:
                    readers.add(bid)
                    nxt.add(bid)
            frontier = nxt
        for rid in readers:
            r = self.branches[rid]
            if r.durable_emitted and rid not in aborted:
                raise SpeculativeOrderingViolation(
                    f"rollback of {branch_id} cannot converge: reader {rid} "
                    f"emitted durable output outside abort domain {domain!r}"
                )
        for bid in aborted:
            self.branches[bid].rolled_back = True
        return aborted
