# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-subagents-across-shared-mutable-state-and-rolls-back-on-conflict-reconciling-optimistic-branches-wit.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-subagents-across-shared-mutable-state-and-rolls-back-on-conflict-reconciling-optimistic-branches-wit.warrant.json
# Markdown SHA-256:   752b6af63746b5518b3f8e63a4dacba8b72ad0fdab17ceb326446c0ad6709f89
# Code AST SHA-256:   00174b7c4f39817332eb671ef8c0d55a9938e0f6f3e9ea50b6db87a30ce4768d
# Verified Classes:   SpeculativeBranchError, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class SpeculativeBranchError(RuntimeError):
    """Raised when an optimistic fork violates read/effect isolation invariants."""
    pass


@dataclass
class Branch:
    branch_id: str
    writes: dict[str, Any] = field(default_factory=dict)
    reads: set[str] = field(default_factory=set)
    effect_committed: bool = False
    effect_log: list[dict] = field(default_factory=list)
    inverse_actions: list[dict] = field(default_factory=list)


def reconcile_fork(branches: list[Branch], committed_snapshot: dict[str, Any]) -> dict[str, Any]:
    """Validate write-set AND read-set, cascade invalidation, demand compensation.

    Enforces: a branch that emitted an irreversible effect may not be silently
    rolled back; a committed branch may not depend on a rolled-back read.
    """
    # Phase 1: write-write conflict resolution -> losers.
    losers: set[str] = set()
    owners: dict[str, str] = {}
    for b in branches:
        for key in b.writes:
            if key in owners and owners[key] != b.branch_id:
                losers.add(b.branch_id)
            else:
                owners[key] = b.branch_id

    # Phase 2: cascade read-set invalidation (zombie-read guard).
    loser_write_keys = {k for b in branches if b.branch_id in losers for k in b.writes}
    changed = True
    while changed:
        changed = False
        for b in branches:
            if b.branch_id in losers:
                continue
            if b.reads & loser_write_keys:
                losers.add(b.branch_id)
                loser_write_keys |= set(b.writes)
                changed = True

    # Phase 3: any invalidated branch that already emitted effects must compensate.
    compensations = []
    for b in branches:
        if b.branch_id in losers and b.effect_committed:
            if not b.inverse_actions:
                raise SpeculativeBranchError(
                    f"branch {b.branch_id} emitted irreversible effects "
                    f"{b.effect_log} but registered no inverse action; "
                    f"cannot roll back safely — escalate to human"
                )
            compensations.append({"branch": b.branch_id, "inverse": b.inverse_actions})

    # Phase 4: compute committed state and prove replay reproducibility.
    committed = dict(committed_snapshot)
    for b in branches:
        if b.branch_id not in losers:
            committed.update(b.writes)

    replay_ok = True
    for b in branches:
        if b.branch_id in losers:
            continue
        if b.reads and not b.reads.issubset(set(committed.keys())):
            replay_ok = False

    if compensations and not replay_ok:
        raise SpeculativeBranchError(
            "fork cannot be reconciled: compensations required AND committed "
            "branch has dangling read dependency; committed output not "
            "reproducible from committed state"
        )

    digest = hashlib.sha256(repr(sorted(committed.items())).encode()).hexdigest()[:16]
    return {
        "committed": committed,
        "losers": sorted(losers),
        "compensations": compensations,
        "replay_reproducible": replay_ok,
        "state_digest": digest,
        "status": "SUCCESS" if replay_ok else "UNREPRODUCIBLE",
    }
