# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-speculative-branch-execution-when-rollback-cannot-guarantee-side-effect-suppression-across-a-shared-external-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-speculative-branch-execution-when-rollback-cannot-guarantee-side-effect-suppression-across-a-shared-external-ledger.warrant.json
# Markdown SHA-256:   7a12d4a65dfa0a65f36e67f2551b8cf4a8c6881cc365872b17c31a368c28dc8a
# Code AST SHA-256:   878060efcafd4bd1711970abf77cb71e87776926ed48a214feac0de15b61d548
# Verified Classes:   NonCanonicalKeyError, UnreconciledCommitError, Branch, ForkContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class NonCanonicalKeyError(RuntimeError):
    """Raised when a speculative branch attempts an external write under a key
    that was not fixed before the fork, breaking duplicate-suppression guarantees."""
    pass


class UnreconciledCommitError(RuntimeError):
    """Raised when rollback is attempted while a branch holds a committed external
    write under a non-canonical key, requiring explicit ledger reconciliation."""
    pass


@dataclass
class Branch:
    branch_id: str
    external_committed: bool = False
    committed_key: Optional[str] = None


@dataclass
class ForkContext:
    task_id: str
    canonical_key: Optional[str]  # fixed before fork; None means branch-derived
    branches: dict = field(default_factory=dict)

    def register_branch(self, branch_id: str) -> Branch:
        b = Branch(branch_id=branch_id)
        self.branches[branch_id] = b
        return b

    def record_external_write(self, branch_id: str, branch_derived_key: str,
                              committed: bool) -> None:
        if self.canonical_key is None:
            raise NonCanonicalKeyError(
                f"Branch {branch_id} issued external write under branch-derived key "
                f"{branch_derived_key[:12]}... but fork {self.task_id} has no "
                f"pre-canonical key; duplicate suppression cannot be guaranteed."
            )
        b = self.branches[branch_id]
        b.external_committed = committed
        b.committed_key = self.canonical_key

    def rollback_losers(self, winning_branch_id: str) -> None:
        for bid, b in self.branches.items():
            if bid == winning_branch_id:
                continue
            if b.external_committed and b.committed_key is None:
                raise UnreconciledCommitError(
                    f"Cannot roll back branch {bid}: external write committed "
                    f"under non-canonical key. Supervisor must query ledger and "
                    f"issue compensating transaction before advancing."
                )
            # safe: either no commit, or commit under canonical key (deduped)
            b.external_committed = False


def canonicalize(task_id: str, logical_action: str) -> str:
    return hashlib.sha256(f"{task_id}::{logical_action}".encode()).hexdigest()
