# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-rollback-divergence-in-speculatively-executed-agent-subplans.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-rollback-divergence-in-speculatively-executed-agent-subplans.warrant.json
# Markdown SHA-256:   f3ab55d1abfbc006bf2acef032dfc9003aa82f3cfb77dffe88982a4f508bd613
# Code AST SHA-256:   62071fe4aee1644d83256020cc4922b0cc4470d8e020125fb94ccd6d13aaa388
# Verified Classes:   RollbackDivergence, SubplanEffect
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field

class RollbackDivergence(RuntimeError):
    """Raised when a mechanically successful rollback leaves memory/world divergence."""
    pass

@dataclass
class SubplanEffect:
    subplan_id: str
    world_hash: str          # hash of the resource the subplan mutated
    episode_claims_done: bool
    declared_effects: set = field(default_factory=set)

def reconcile_rollback(effect: SubplanEffect, world_hash_now: str,
                       compensating_episode_present: bool,
                       shared_index_orphans: int) -> None:
    # 1. Effect closure: undeclared effects cannot be trusted to have been reversed.
    if not effect.declared_effects:
        raise RollbackDivergence(
            f"subplan {effect.subplan_id}: empty effect set; rollback unverifiable"
        )
    # 2. World must match pre-fan-out hash after rollback.
    if world_hash_now != effect.world_hash:
        raise RollbackDivergence(
            f"subplan {effect.subplan_id}: world hash {world_hash_now} != "
            f"expected {effect.world_hash} after rollback"
        )
    # 3. Memory asymmetry: a rolled-back subplan must not still claim completion.
    if effect.episode_claims_done and not compensating_episode_present:
        raise RollbackDivergence(
            f"subplan {effect.subplan_id}: episode claims done but no "
            f"compensating rollback episode; next-turn retrieval will be poisoned"
        )
    # 4. Shared-resource orphan check must run post-rollback, not per-subplan.
    if shared_index_orphans > 0:
        raise RollbackDivergence(
            f"subplan {effect.subplan_id}: {shared_index_orphans} orphaned "
            f"index entries survive rollback"
        )

def commit_winner(winner_id: str, effects: list[SubplanEffect],
                  world_hashes: dict, compensating: dict,
                  orphans: int) -> str:
    for e in effects:
        if e.subplan_id == winner_id:
            continue
        reconcile_rollback(e, world_hashes[e.subplan_id],
                           compensating.get(e.subplan_id, False), orphans)
    return f"committed {winner_id}"
