# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-speculative-agent-branches-have-crossed-the-point-of-no-return-before-rollback-completes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-speculative-agent-branches-have-crossed-the-point-of-no-return-before-rollback-completes.warrant.json
# Markdown SHA-256:   4872437365e3aa7d39b25330d05dbc6fe096219eef07e1198c5c73ad5195f11c
# Code AST SHA-256:   2e158c4780b888728de874fd32ee9b18dc344e07ffcaa3295dbbad30acf21cf7
# Verified Classes:   SpeculativeRollbackIntegrityError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculativeRollbackIntegrityError(RuntimeError):
    """Raised when a speculative branch is rolled back while it still has
    un-compensated external effects, producing orphaned world-state."""
    pass


def verify_branch_reverted(branch_id: str,
                            rollback_ledger: set,
                            observed_world_deltas: set,
                            retained_write_sets: set) -> None:
    """
    Enforce the rollback-safety invariant for a single speculative branch.

    A branch is only legitimately reverted if every observable world-state
    delta in its execution window is accounted for by either a retained
    branch's write-set or an explicit compensation entry in the ledger.
    """
    claimed_clean = branch_id in rollback_ledger
    if not claimed_clean:
        return  # branch was never rolled back; nothing to verify

    accounted = retained_write_sets | {
        d for d in observed_world_deltas if d in rollback_ledger
    }
    orphans = observed_world_deltas - accounted

    if orphans:
        raise SpeculativeRollbackIntegrityError(
            f"Branch {branch_id!r} claims clean rollback but leaked "
            f"{len(orphans)} un-compensated external effect(s): "
            f"{sorted(orphans)}. Provenance gap detected; merge must abort "
            f"and reconcile before the losing branch's context is discarded."
        )


def safe_rollback(branch_id: str,
                  rollback_ledger: set,
                  observed_world_deltas: set,
                  retained_write_sets: set) -> None:
    """Rollback entry point that refuses to silently orphan effects."""
    verify_branch_reverted(
        branch_id, rollback_ledger, observed_world_deltas, retained_write_sets
    )
    rollback_ledger.add(branch_id)
