# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-rollback-when-branch-reconciliation-exceeds-the-checkpoint-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-rollback-when-branch-reconciliation-exceeds-the-checkpoint-horizon.warrant.json
# Markdown SHA-256:   f0a73503bf3f8d8710ebd79b9b785c9562ed25fda132844204d7ee8b693b0998
# Code AST SHA-256:   24e2b69c137d7965403b90b33663e308a32b8a1177f8eda5ba24d1bc983947c8
# Verified Classes:   CheckpointHorizonViolation, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CheckpointHorizonViolation(RuntimeError):
    """Raised when a speculative rollback targets a checkpoint that is no longer
    the head, meaning escaped side effects cannot be undone by restore alone."""
    pass


class Branch:
    def __init__(self, branch_id, fork_checkpoint, escaped_effects=None):
        self.branch_id = branch_id
        self.fork_checkpoint = fork_checkpoint
        self.escaped_effects = escaped_effects or []


def reconcile_and_rollback(loser: Branch, head_checkpoint: str, effect_log_reader):
    """
    Enforce the checkpoint-horizon invariant before rolling back a losing
    speculative branch. Restore is only sound when the horizon has not
    advanced past the fork; otherwise we must compensate, not restore.
    """
    if head_checkpoint != loser.fork_checkpoint:
        # Horizon advanced: restore would silently no-op or downgrade.
        escaped = effect_log_reader(loser.branch_id)
        if escaped:
            raise CheckpointHorizonViolation(
                f"branch {loser.branch_id} forked at {loser.fork_checkpoint} "
                f"but head is {head_checkpoint}; {len(escaped)} escaped "
                f"side effect(s) require compensation, not checkpoint restore"
            )
        # No escaped effects: re-fork from head and re-run is the only sound path.
        raise CheckpointHorizonViolation(
            f"branch {loser.branch_id}: horizon advanced to {head_checkpoint} "
            f"with no effect log; rollback target is stale, must re-fork"
        )

    # Sound path: horizon frozen at fork, restore is valid.
    return {"action": "restore", "target": loser.fork_checkpoint}
