# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-speculative-branch-reconciliation-when-rollback-side-effects-are-non-commutative-across-sibling-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-speculative-branch-reconciliation-when-rollback-side-effects-are-non-commutative-across-sibling-agents.warrant.json
# Markdown SHA-256:   822bdeadd6870f0c2f623f4c4ff5e1b38d65c94427a351cb735abd04ba5fed72
# Code AST SHA-256:   f3d234fe292d1fa26b83412c7ef16821998db0fdb4cec0554514cfeddb6c4df7
# Verified Classes:   NonCommutativeRollbackError, ResourceEffectClass
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class NonCommutativeRollbackError(RuntimeError):
    """Raised when inverse rollback is attempted against a resource whose
    sibling effects are neither commutative nor fenced. The orchestrator
    must abandon inverse rollback and switch to forward reconciliation."""
    pass


class ResourceEffectClass:
    COMMUTATIVE = "commutative"   # order-free; inverse rollback sound
    FENCED = "fenced"             # fencing token enforced by resource; inverse sound if fence acked
    NEITHER = "neither"           # order-sensitive, no fence; inverse rollback UNSOUND


def rollback_branch(branch, resource_manifest, fence_acks, landed_state_reader):
    """
    Attempt inverse rollback of a losing speculative branch.
    Refuses if any touched resource is NEITHER and not fenced-acked.
    Returns forward-reconciliation plan instead of inverse effects when unsafe.
    """
    touched = branch.effect_log.resources()
    unsafe = []
    for r in touched:
        cls = resource_manifest.classify(r)
        if cls == ResourceEffectClass.NEITHER:
            unsafe.append(r)
        elif cls == ResourceEffectClass.FENCED and r not in fence_acks:
            unsafe.append(r)

    if unsafe:
        # Do not emit inverse effects. Require read-back and forward plan.
        if not landed_state_reader.available(unsafe):
            raise NonCommutativeRollbackError(
                f"Branch {branch.id} touched non-commutative resources {unsafe} "
                f"without fencing and without read-back; inverse rollback would "
                f"produce ordering-dependent inconsistency. Escalate to "
                f"serialized re-execution or human reconciliation."
            )
        # Forward reconciliation: compute delta from actual landed state to winner target.
        plan = []
        for r in unsafe:
            actual = landed_state_reader.read(r)
            target = branch.winner_target(r)
            if actual != target:
                plan.append(("set_to_target", r, target))
        return ("forward_reconcile", plan)

    # Safe path: commutative or fenced-acked resources; inverse rollback sound.
    inverse = [op.invert() for op in branch.effect_log.acked_effects()]
    return ("inverse_rollback", inverse)


def reconcile(speculative_result, resource_manifest, fence_acks, landed_state_reader):
    winner, losers = speculative_result.winner, speculative_result.losers
    for loser in losers:
        mode, ops = rollback_branch(loser, resource_manifest, fence_acks, landed_state_reader)
        if mode == "forward_reconcile":
            # New epoch: fresh fences, fresh snapshot, forward-only effects.
            apply_forward(ops)
        else:
            apply_inverse(ops)
    # Auditor reports are advisory unless snapshotted at a fenced cut.
    if not speculative_result.auditor.fenced_cut:
        speculative_result.auditor.mark_advisory()
    return speculative_result
