# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-rollback-divergence-when-a-peer-agent-s-subgoal-commits-side-effects-the-rollback-log-cannot-see.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-rollback-divergence-when-a-peer-agent-s-subgoal-commits-side-effects-the-rollback-log-cannot-see.warrant.json
# Markdown SHA-256:   2a530aefc424ad1697906cba114fdae0cf996f0951c05ebfb92798ffdd074edf
# Code AST SHA-256:   2df8ca8413174cd21ddf459f92812075b947e9c09d97bd6c13346519b690589a
# Verified Classes:   CompensationGapError, PeerReport, OrchestratorLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CompensationGapError(RuntimeError):
    """Raised when a speculative branch's effects cannot be fully unwound."""


@dataclass
class PeerReport:
    peer_id: str
    compensated: int
    requested: int
    partial_fanout: tuple[int, int] | None  # (reversed, total) for batch tools
    shared_resources_touched: set[str] = field(default_factory=set)


@dataclass
class OrchestratorLedger:
    compensation_registry: set[str]          # tools with registered per-unit inverses
    owned_resources: set[str]               # resources orchestrator can compensate
    residue_check: dict[str, bool]          # resource -> True if clean after rollback


def verify_rollback(report: PeerReport, ledger: OrchestratorLedger,
                    peer_tools: set[str]) -> None:
    # 1. Inverse completeness: every peer tool must have a registered inverse.
    gaps = peer_tools - ledger.compensation_registry
    if gaps:
        raise CompensationGapError(
            f"peer {report.peer_id} used uncompensable tools: {sorted(gaps)}"
        )

    # 2. Per-unit fan-out verification: collapsed counts are not proof.
    if report.partial_fanout is not None:
        reversed_n, total_n = report.partial_fanout
        if reversed_n != total_n:
            raise CompensationGapError(
                f"peer {report.peer_id} reversed {reversed_n}/{total_n} "
                f"sub-requests; batch inverse is incomplete"
            )

    # 3. Authority containment: shared resources must be orchestrator-owned
    #    and re-read clean, not merely reported clean by the peer.
    unowned = report.shared_resources_touched - ledger.owned_resources
    if unowned:
        raise CompensationGapError(
            f"peer {report.peer_id} mutated resources outside orchestrator "
            f"authority: {sorted(unowned)}"
        )
    dirty = [r for r in report.shared_resources_touched
             if not ledger.residue_check.get(r, False)]
    if dirty:
        raise CompensationGapError(
            f"residue detected on shared resources after rollback: {sorted(dirty)}"
        )

    # 4. Only now is ROLLBACK_OK meaningful.
    if report.compensated != report.requested:
        raise CompensationGapError(
            f"peer {report.peer_id} compensated {report.compensated}/"
            f"{report.requested} logged effects"
        )
