# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-own-rolled-back-branch-after-speculative-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-own-rolled-back-branch-after-speculative-multi-agent-execution.warrant.json
# Markdown SHA-256:   87775e95964a050674e8fafefdb0943be4507e036913e44f81f7d3ae8474718c
# Code AST SHA-256:   0594e9f54ae10f10d1e8c2e900a68b960585cc68d2f22ea2cffba11706915edc
# Verified Classes:   BranchMemorySkewError, InstanceState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class BranchMemorySkewError(RuntimeError):
    """Raised when a rolled-back instance retains derived state not present
    in the committed branch, i.e. a rollback that was actually a silent merge."""


@dataclass
class InstanceState:
    instance_id: str
    checkpoint_id: str
    known_facts: FrozenSet[str] = field(default_factory=frozenset)
    tool_cache: dict = field(default_factory=dict)
    progress_counter: int = 0


def reconcile_after_rollback(
    instance: InstanceState,
    committed_facts: FrozenSet[str],
    committed_checkpoint_id: str,
) -> InstanceState:
    """Reconcile a speculatively-executed instance against the committed branch.

    A safe reconciliation requires that every derived-state channel be reset to
    the committed branch. If any in-context fact survives that the committed
    branch does not contain, the instance is skewed and must be replaced.
    """
    if instance.checkpoint_id != committed_checkpoint_id:
        raise BranchMemorySkewError(
            f"instance {instance.instance_id} is anchored to checkpoint "
            f"{instance.checkpoint_id!r}, but commit is {committed_checkpoint_id!r}; "
            "context restore did not match the authoritative branch"
        )

    skew = instance.known_facts - committed_facts
    if skew:
        # Instruction-based overwrite would hide this; we refuse it instead.
        raise BranchMemorySkewError(
            f"instance {instance.instance_id} retains {len(skew)} derived fact(s) "
            f"absent from committed branch {committed_checkpoint_id!r}: "
            f"{sorted(skew)}. Rollback was a silent merge; replace the instance."
        )

    if instance.tool_cache:
        raise BranchMemorySkewError(
            f"instance {instance.instance_id} still holds {len(instance.tool_cache)} "
            "cached tool result(s) from the discarded branch; cache is not "
            "covered by the checkpoint and must be cleared atomically with restore"
        )

    # Only reached when every derived channel is provably reset.
    return InstanceState(
        instance_id=instance.instance_id,
        checkpoint_id=committed_checkpoint_id,
        known_facts=committed_facts,
        tool_cache={},
        progress_counter=0,
    )
