# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-a-plan-and-the-rollback-ledger-diverges-from-the-observed-world.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-a-plan-and-the-rollback-ledger-diverges-from-the-observed-world.warrant.json
# Markdown SHA-256:   5a41eca48cc7b14ea0dc036846f4ca992ae2041946b61c2f8520b93391dc6e25
# Code AST SHA-256:   8c490018302eb63cee5f3423ad44e65b576ab198b01aa6906fca192fcad20578
# Verified Classes:   RollbackReconciliationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class RollbackReconciliationError(RuntimeError):
    """Raised when a speculative branch's effects cannot be safely compensated."""


def reconcile_loser_effects(loser_ledger, world, contested_targets, versioned_store):
    """
    Compensate a losing speculative branch's effects, or refuse.
    Returns list of compensated effect_ids; raises on unsafe compensation.
    """
    compensated = []
    for effect in loser_ledger.effects:
        target = effect.target

        # Predicate 1: identity match against observed world.
        current = world.read(target)
        if current != effect.post_state:
            raise RollbackReconciliationError(
                f"effect {effect.effect_id} on {target}: world state {current!r} "
                f"!= recorded post_state {effect.post_state!r}; another writer intervened"
            )

        # Predicate 2: exclusivity / contested target.
        if target in contested_targets:
            if not versioned_store.supports_conditional_write(target):
                raise RollbackReconciliationError(
                    f"effect {effect.effect_id} on contested target {target} "
                    f"without conditional-write support; refusing blind compensation"
                )
            ok = versioned_store.update_where_version(
                target, expected_version=effect.post_version, new_value=effect.pre_state
            )
            if not ok:
                raise RollbackReconciliationError(
                    f"effect {effect.effect_id} on {target}: version guard failed; "
                    f"store moved between read and compensate"
                )
            compensated.append(effect.effect_id)
            continue

        # Predicate 3: idempotency class.
        if effect.idempotency_class != "set_to_value":
            raise RollbackReconciliationError(
                f"effect {effect.effect_id} on {target}: non-idempotent "
                f"({effect.idempotency_class}) cannot be blindly inverted"
            )
        world.write(target, effect.pre_state)
        compensated.append(effect.effect_id)

    return compensated
