# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branches-before-committing-when-parallel-plans-have-already-mutated-the-same-external-resource.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branches-before-committing-when-parallel-plans-have-already-mutated-the-same-external-resource.warrant.json
# Markdown SHA-256:   ff3ab4711be7a8c8af7e6f42ba1575142ee2ea787c8ebb49152fb0b9e1524553
# Code AST SHA-256:   0dd5f19d884145092943de966202ba9535d06b9bb40c3b6dbb7128e57f9090e5
# Verified Classes:   StaleReadSetError, VersionLog, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class StaleReadSetError(RuntimeError):
    """Raised when a speculative branch's read-set was mutated by a committed peer."""


@dataclass
class VersionLog:
    """Content-addressed head per resource; the source of truth for read-set currency."""
    heads: dict[str, str] = field(default_factory=dict)

    def snapshot(self, resource: str, content: bytes) -> str:
        digest = hashlib.sha256(content).hexdigest()
        self.heads[resource] = digest
        return digest


@dataclass
class Branch:
    name: str
    read_set: dict[str, str]          # resource -> version observed at read time
    write_set: dict[str, bytes]       # resource -> new content
    transform: Callable[[dict[str, bytes]], dict[str, bytes]] | None = None
    non_deterministic: bool = False   # LLM judgment not captured in read-set


def reconcile(branches: list[Branch], log: VersionLog) -> list[str]:
    """Two-phase merge: validate all read-sets against head, then apply.

    Raises StaleReadSetError if any branch's pre-image is no longer current.
    Caller must re-run or re-derive the offending branch and retry.
    """
    # Phase 1: validate every read-set against the *current* head.
    stale: list[Branch] = []
    for b in branches:
        for resource, observed in b.read_set.items():
            current = log.heads.get(resource)
            if current is not None and current != observed:
                stale.append(b)
                break
    if stale:
        names = ", ".join(b.name for b in stale)
        raise StaleReadSetError(
            f"branches [{names}] derived from stale pre-images; "
            f"re-run if non_deterministic, else re-derive against current head"
        )

    # Phase 2: apply writes and advance the log.
    applied: list[str] = []
    for b in branches:
        for resource, content in b.write_set.items():
            log.snapshot(resource, content)
        applied.append(b.name)
    return applied


def commit_or_repair(branches: list[Branch], log: VersionLog) -> list[str]:
    """Drive reconciliation to a fixed point; re-derive deterministic branches."""
    for _ in range(len(branches) + 1):  # bounded fixed-point iteration
        try:
            return reconcile(branches, log)
        except StaleReadSetError:
            repaired: list[Branch] = []
            for b in branches:
                is_stale = any(
                    log.heads.get(r) not in (None, v) for r, v in b.read_set.items()
                )
                if not is_stale:
                    repaired.append(b)
                elif b.non_deterministic or b.transform is None:
                    raise  # cannot safely re-derive; escalate to caller for re-run
                else:
                    new_pre = {
                        r: log.heads.get(r, "") for r in b.read_set
                    }
                    new_writes = b.transform(new_pre)
                    repaired.append(
                        Branch(
                            name=b.name,
                            read_set={r: log.heads.get(r, "") for r in b.read_set},
                            write_set=new_writes,
                            transform=b.transform,
                            non_deterministic=False,
                        )
                    )
            branches = repaired
    raise StaleReadSetError("reconciliation did not converge within iteration bound")
