# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-irreversible-divergence-in-speculative-multi-agent-rollback-checkpoint-lineage-collisions-during-parallel-branch-reco.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-irreversible-divergence-in-speculative-multi-agent-rollback-checkpoint-lineage-collisions-during-parallel-branch-reco.warrant.json
# Markdown SHA-256:   729dffe64739e2cefaa544c5d3a99a1ad079e5c3a8ce28c1646b5caf248d800f
# Code AST SHA-256:   4b603777ce553559fe29fdf1ee26a6aaf8a4b67b2a1fed877aa3839d99aec6bf
# Verified Classes:   LineageCollisionError, UnrecoverableForkWindowError, Checkpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class LineageCollisionError(RuntimeError):
    """Raised when a speculative branch mutates a resource the checkpoint aliased as immutable."""


class UnrecoverableForkWindowError(RuntimeError):
    """Raised when the ancestor cannot be reconstructed and reconciliation must be abandoned."""


@dataclass
class Checkpoint:
    checkpoint_id: str
    resources: dict[str, Any]          # name -> live handle or value
    resource_hashes: dict[str, str]    # name -> hash at fork time
    classification: dict[str, str]     # name -> "immutable" | "volatile"
    pre_fork_trace: list[dict] = field(default_factory=list)


def _hash(value: Any) -> str:
    return hashlib.sha256(repr(value).encode()).hexdigest()[:16]


def fork_branch(cp: Checkpoint, branch_id: str) -> dict[str, Any]:
    """Materialize a branch namespace. Immutable resources are deep-copied;
    volatile resources are aliased. Returns the branch's private resource map."""
    branch_resources: dict[str, Any] = {}
    for name, handle in cp.resources.items():
        if cp.classification.get(name) == "immutable":
            # Deep-copy via repr round-trip; real systems use structured clone.
            branch_resources[name] = eval(repr(handle))  # noqa: S307 - controlled repr
        else:
            branch_resources[name] = handle  # aliased, mutation permitted
    return branch_resources


def validate_branch_mutation(cp: Checkpoint, name: str, new_value: Any) -> None:
    if cp.classification.get(name) == "immutable":
        if _hash(new_value) != cp.resource_hashes.get(name):
            raise LineageCollisionError(
                f"branch mutated immutable resource {name!r}: "
                f"expected {cp.resource_hashes.get(name)}, got {_hash(new_value)}"
            )


def reconcile(cp: Checkpoint, branches: dict[str, dict[str, Any]],
              trace_deterministic: bool) -> str:
    # Test 1: hash closure over the live ancestor.
    for name, expected in cp.resource_hashes.items():
        if cp.classification.get(name) != "immutable":
            continue
        live = cp.resources.get(name)
        if _hash(live) != expected:
            raise UnrecoverableForkWindowError(
                f"ancestor drifted on {name!r}: {expected} -> {_hash(live)}; "
                f"fork window {cp.checkpoint_id} is lost"
            )
    # Test 2: replay determinism.
    if not trace_deterministic:
        raise UnrecoverableForkWindowError(
            f"pre-fork trace for {cp.checkpoint_id} is non-deterministic; "
            f"ancestor unreproducible, branch outputs incomparable"
        )
    # Selection proceeds only past both tests.
    return max(branches, key=lambda b: len(branches[b]))
