# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-fence-speculative-branches-before-committing-to-a-shared-blackboard.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-fence-speculative-branches-before-committing-to-a-shared-blackboard.warrant.json
# Markdown SHA-256:   d7e4e642d6a72d928a6c2de8bfec0503a3b7d277584f8dcc09f05332b6e556f2
# Code AST SHA-256:   36c3c3a9756baff9c165a543b0a0c217ad30c77170075c089ddabebf199782ec
# Verified Classes:   PremiseContaminationError, BranchStatus, BlackboardEntry, ReadRecord, Blackboard
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Tuple


class PremiseContaminationError(RuntimeError):
    """Raised when a branch commits having read a speculative entry from an aborted origin."""
    pass


class BranchStatus(Enum):
    RUNNING = "running"
    COMMITTED = "committed"
    ABORTED = "aborted"


@dataclass
class BlackboardEntry:
    key: str
    value: str
    origin: str
    status: str  # "speculative" | "committed"


@dataclass
class ReadRecord:
    reader: str
    key: str
    origin: str
    origin_status_at_read: str


@dataclass
class Blackboard:
    entries: Dict[str, BlackboardEntry] = field(default_factory=dict)
    reads: List[ReadRecord] = field(default_factory=list)
    branches: Dict[str, BranchStatus] = field(default_factory=dict)

    def write(self, branch: str, key: str, value: str) -> None:
        self.branches.setdefault(branch, BranchStatus.RUNNING)
        self.entries[key] = BlackboardEntry(key, value, branch, "speculative")

    def read(self, branch: str, key: str) -> str:
        entry = self.entries[key]
        self.reads.append(ReadRecord(branch, key, entry.origin, entry.status))
        return entry.value

    def commit(self, branch: str) -> None:
        self.branches[branch] = BranchStatus.COMMITTED
        for e in self.entries.values():
            if e.origin == branch:
                e.status = "committed"

    def abort(self, branch: str) -> None:
        self.branches[branch] = BranchStatus.ABORTED
        for k in [k for k, e in self.entries.items() if e.origin == branch]:
            del self.entries[k]


def assert_no_contaminated_commit(bb: Blackboard, branch: str) -> None:
    """Enforce the read-fence invariant before allowing a branch to commit."""
    for r in bb.reads:
        if r.reader != branch:
            continue
        if r.origin_status_at_read != "speculative":
            continue
        if bb.branches.get(r.origin) == BranchStatus.ABORTED:
            raise PremiseContaminationError(
                f"branch {branch!r} committed a conclusion derived from "
                f"speculative entry {r.key!r} of aborted branch {r.origin!r}; "
                f"the inference survives rollback and must be re-verified"
            )


def run_scenario() -> None:
    bb = Blackboard()
    # A speculates, B reads A's speculative write as a premise.
    bb.write("A", "plan.step3", "call refund_api with order_id")
    bb.read("B", "plan.step3")
    bb.write("B", "plan.step4", "verify refund_api response code == 200")
    # Verifier rejects A; rollback deletes step3 but B's inference persists.
    bb.abort("A")
    assert_no_contaminated_commit(bb, "B")  # raises: dangling dependency


if __name__ == "__main__":
    run_scenario()
