# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branches-before-committing-shared-state-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branches-before-committing-shared-state-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   85b7ed5d2d7149557805b369d93c30c654558648e18aa9d332d79e9c9ea3a5af
# Code AST SHA-256:   2cfea57928a127bee20a883ef74f6317b32b597c4fce2e9281fc57773d69a5e9
# Verified Classes:   SpeculativeReconciliationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SpeculativeReconciliationError(RuntimeError):
    """Raised when a speculative branch's effects cannot be admitted to the commit set."""


def reconcile_branch_effects(branch, shared_stores):
    """
    Admit a selected branch's effects into the commit set, or refuse.
    Enforces: effect-confined AND snapshot-isolated AND compensation-backed.
    """
    if not branch.snapshot_isolated:
        # Branch read a sibling's mutation; its reasoning is contaminated.
        raise SpeculativeReconciliationError(
            f"branch {branch.id} is snapshot-contaminated: read shared state "
            f"mutated after S0; cannot admit as independent vote"
        )

    for effect in branch.emitted_effects:
        store = shared_stores.get(effect.store_name)

        if store is None:
            raise SpeculativeReconciliationError(
                f"branch {branch.id} emitted effect to unknown store "
                f"{effect.store_name!r}"
            )

        if store.is_branch_namespaced(effect):
            # Effect is confined; namespace drop on rollback is sufficient.
            continue

        # Effect escaped the branch namespace. It is admissible only if the
        # branch is committed AND the effect carries a compensation handle.
        if not branch.committed:
            raise SpeculativeReconciliationError(
                f"branch {branch.id} is not committed but emitted un-namespaced "
                f"effect {effect.id} to shared store {effect.store_name!r}; "
                f"rollback by namespace drop cannot revert it"
            )

        if effect.compensation_handle is None:
            # Unreconcilable: surface as debt, never silently retain.
            raise SpeculativeReconciliationError(
                f"branch {branch.id} committed un-namespaced effect {effect.id} "
                f"with no compensation handle; state is unreconcilable and must "
                f"be quarantined as explicit debt, not committed"
            )

        effect.apply_compensation_guard()

    return branch.commit_set()
