# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branches-when-an-optimistic-tool-invocation-commits-an-irreversible-side-effect-before-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branches-when-an-optimistic-tool-invocation-commits-an-irreversible-side-effect-before-rollback.warrant.json
# Markdown SHA-256:   009b89419f58b009471163f68c264fa30544854cac96b694d7cd2f9f047b7460
# Code AST SHA-256:   376aa948043eef41cf9af01dfd2357ff5b76c40bc9181f6ac472ca46c9ad2428
# Verified Classes:   OrphanedEffectError, EffectLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class OrphanedEffectError(RuntimeError):
    """Raised when a rolled-back branch left a live external effect
    that no surviving branch owns and no compensation has cleared."""
    pass


class EffectLedger:
    def __init__(self):
        # branch_id -> list of effect records; NEVER pruned on rollback
        self._effects = {}
        self._compensated = set()

    def record(self, branch_id, effect_id, tool, resource, lease_seconds, reversible):
        self._effects.setdefault(branch_id, []).append({
            "effect_id": effect_id,
            "tool": tool,
            "resource": resource,
            "lease_seconds": lease_seconds,
            "reversible": reversible,
            "orphaned": False,
        })

    def orphan(self, branch_id):
        for rec in self._effects.get(branch_id, []):
            rec["orphaned"] = True

    def live_orphans(self):
        return [
            rec
            for recs in self._effects.values()
            for rec in recs
            if rec["orphaned"] and rec["effect_id"] not in self._compensated
        ]

    def compensate(self, effect_id):
        self._compensated.add(effect_id)


def reconcile_before_commit(ledger, winner_branch, reconciliation_window_s):
    """Must run before a winning branch commits any plan that reasons
    over external resources. Fails closed if ghosts cannot be cleared."""
    orphans = ledger.live_orphans()
    for rec in orphans:
        if not rec["reversible"]:
            raise OrphanedEffectError(
                f"Branch left irreversible effect {rec['effect_id']} on "
                f"{rec['resource']} via {rec['tool']}; cannot compensate, "
                f"winner {winner_branch} must not commit over contaminated state."
            )
        if rec["lease_seconds"] > reconciliation_window_s:
            raise OrphanedEffectError(
                f"Effect {rec['effect_id']} lease {rec['lease_seconds']}s exceeds "
                f"reconciliation window {reconciliation_window_s}s; ghost constraint "
                f"will outlive reconciliation and poison {winner_branch}."
            )
        ledger.compensate(rec["effect_id"])
    return True
