# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-reconcile-a-speculative-branch-after-an-optimistic-tool-invocation-has-produced-an-irreversible-exter.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-reconcile-a-speculative-branch-after-an-optimistic-tool-invocation-has-produced-an-irreversible-exter.warrant.json
# Markdown SHA-256:   cce0974a9f687ba9f9a2a364acb6e421346ee8a3108690c616f5226729ea8cf5
# Code AST SHA-256:   a532d20b1e5d1d6a4b2ec293a4598afdcbf4a3bfd2f649ea06c6238cb63c0283
# Verified Classes:   IrreversibleSpeculativeEffect, BranchEffect
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class IrreversibleSpeculativeEffect(RuntimeError):
    """Raised when a branch to be discarded has emitted an externally visible,
    non-compensable effect, making rollback impossible."""
    pass


class BranchEffect:
    def __init__(self, tool, reversible, visibility, compensation_token=None):
        self.tool = tool
        self.reversible = reversible
        self.visibility = visibility  # "immediate" | "eventual_bounded" | "eventual_unbounded"
        self.compensation_token = compensation_token


def reconcile_branch(branch_id, effects, commit_target):
    """Attempt to discard a speculative branch. Refuses if any effect is
    irreversible and externally visible with no pre-reserved compensation."""
    for e in effects:
        if e.reversible:
            if e.compensation_token is None:
                raise IrreversibleSpeculativeEffect(
                    f"branch {branch_id}: reversible effect on {e.tool} lacks "
                    f"compensation token; cannot guarantee inverse"
                )
            continue

        # Irreversible effect: only safe if visibility is bounded and
        # compensation was reserved at invocation time.
        if e.visibility == "immediate":
            raise IrreversibleSpeculativeEffect(
                f"branch {branch_id}: irreversible effect on {e.tool} is "
                f"immediately visible; branch is not discardable, must "
                f"escalate to reconciliation-as-merge"
            )
        if e.visibility == "eventual_unbounded":
            raise IrreversibleSpeculativeEffect(
                f"branch {branch_id}: irreversible effect on {e.tool} has "
                f"unbounded eventual visibility; treating as immediate"
            )
        if e.visibility == "eventual_bounded" and e.compensation_token is None:
            raise IrreversibleSpeculativeEffect(
                f"branch {branch_id}: irreversible effect on {e.tool} has no "
                f"pre-reserved compensation; window may have closed"
            )

    return {"branch": branch_id, "status": "discarded_clean", "commit": commit_target}
