# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-speculative-branch-abandonment-from-rollback-failure-in-cost-aware-agent-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-speculative-branch-abandonment-from-rollback-failure-in-cost-aware-agent-pipelines.warrant.json
# Markdown SHA-256:   c8b4842050e82671532f31ed06761a53d61527bb6fb299a182a3a494f647ddab
# Code AST SHA-256:   464b5870e1cfc55015c551a2d1a3f2180d70999dd67f9589127509559fc3b672
# Verified Classes:   SpeculativeBranchError, EffectLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SpeculativeBranchError(RuntimeError):
    """Raised when a speculative branch cannot be safely terminated."""
    pass


class EffectLedger:
    def __init__(self):
        self.entries = []  # each: {"action": str, "reversible": bool, "executed": bool}

    def record(self, action, reversible, executed=False):
        self.entries.append({"action": action, "reversible": reversible, "executed": executed})

    def executed_irreversible(self):
        return [e for e in self.entries if e["executed"] and not e["reversible"]]

    def executed_reversible(self):
        return [e for e in self.entries if e["executed"] and e["reversible"]]


def terminate_branch(branch_id, exit_reason, ledger, apply_inverse, escalate):
    """
    Decide whether a terminating speculative branch is abandoned (safe discard)
    or unrolled (compensation required), based on the effect ledger -- never on
    the exit reason alone.
    """
    if ledger is None:
        raise SpeculativeBranchError(
            f"branch {branch_id}: effect ledger unavailable; cannot prove branch "
            f"is below effect horizon (exit_reason={exit_reason}). Refusing to "
            f"discard state without compensation."
        )

    irreversible = ledger.executed_irreversible()
    if irreversible:
        # Branch has crossed the effect horizon irreversibly; it is not abandonable.
        escalate(branch_id, irreversible)
        raise SpeculativeBranchError(
            f"branch {branch_id}: {len(irreversible)} executed irreversible effect(s) "
            f"present; abandonment would leak side effects. Escalated to reconciliation."
        )

    reversible = ledger.executed_reversible()
    for entry in reversed(reversible):
        if not apply_inverse(entry["action"]):
            raise SpeculativeBranchError(
                f"branch {branch_id}: failed to apply inverse for reversible "
                f"effect {entry['action']!r}; branch is in an unrolled-but-dirty state."
            )

    return "abandoned_unrolled" if reversible else "abandoned_clean"
