# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-speculative-branch-and-verify-graph-silently-commit-orphaned-side-effects-when-its-rollback-witness-is-invalidated-by-a-conc.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-speculative-branch-and-verify-graph-silently-commit-orphaned-side-effects-when-its-rollback-witness-is-invalidated-by-a-conc.warrant.json
# Markdown SHA-256:   559d087bf8a912ff5f22074494de4629c7b07eb6a787a585c38c8bbdf4ee158f
# Code AST SHA-256:   ff6fced3038f4c2a81b66c0fc5da0c4b977b10a8568441c8f453fb15737c19af
# Verified Classes:   OrphanedEffectError, EffectLog
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class OrphanedEffectError(RuntimeError):
    """Raised when a speculative branch is rolled back while it holds
    un-compensated external effects, or committed against a stale witness."""
    pass


class EffectLog:
    def __init__(self):
        self.entries = []  # (branch_id, effect_id, compensator)

    def register(self, branch_id, effect_id, compensator):
        # MUST be called BEFORE the external effect executes.
        self.entries.append((branch_id, effect_id, compensator))

    def for_branch(self, branch_id):
        return [e for e in self.entries if e[0] == branch_id]

    def compensate(self, branch_id):
        for _, effect_id, compensator in self.for_branch(branch_id):
            compensator(effect_id)


def verify_and_resolve(branch, witness_ledger, effect_log, merge_lock):
    with merge_lock:
        current = witness_ledger.current()
        if branch.witness == current:
            # Witness valid under lock: commit is safe.
            branch.commit()
            return "committed"

        effects = effect_log.for_branch(branch.id)
        if not effects:
            branch.rollback_context()
            return "rolled_back_clean"

        # Witness invalidated but branch holds external effects.
        # Rollback of context alone would orphan them.
        effect_log.compensate(branch.id)
        if effect_log.for_branch(branch.id):
            raise OrphanedEffectError(
                f"branch {branch.id}: witness {branch.witness} != {current} "
                f"and compensation incomplete; {len(effect_log.for_branch(branch.id))} "
                f"effects still live"
            )
        branch.rollback_context()
        return "compensated"
