# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-speculative-fan-out-silently-commit-a-tool-side-effect-that-its-own-rollback-later-disowns.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-speculative-fan-out-silently-commit-a-tool-side-effect-that-its-own-rollback-later-disowns.warrant.json
# Markdown SHA-256:   982eab3e54822017084bd6d334fa6f0854192b2fa359e324984805ebf09ac488
# Code AST SHA-256:   6e244894c34e128d2a6b4f01e9feff9f7828d40491643caa4cb6f7d9dd38ee8c
# Verified Classes:   SpeculationReconciliationError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class SpeculationReconciliationError(RuntimeError):
    """Raised when a speculative branch's rollback cannot be reconciled
    against the realized forward-effect ledger on resolved resource handles."""
    pass


def reconcile_rollback(
    forward_ledger: dict[str, str],   # resolved_handle -> branch_id
    rollback_ledger: dict[str, str],  # resolved_handle -> branch_id
    winner_handle: str,
) -> None:
    # Invariant: every forward effect from a losing branch must have exactly
    # one inverse, keyed on the SAME resolved handle, and no inverse may
    # target the winner's handle.
    for handle, branch in forward_ledger.items():
        if handle == winner_handle:
            continue
        if handle not in rollback_ledger:
            # Forward effect exists with no inverse keyed on resolved handle.
            # This is the aliasing signature: the inverse was keyed on a raw
            # argument that normalized to a different handle.
            raise SpeculationReconciliationError(
                f"orphan forward effect: handle={handle!r} branch={branch!r} "
                f"has no resolved-key inverse; likely raw-arg aliasing"
            )
        if rollback_ledger[handle] != branch:
            raise SpeculationReconciliationError(
                f"inverse misattribution: handle={handle!r} forward_branch={branch!r} "
                f"rollback_branch={rollback_ledger[handle]!r}"
            )

    for handle, branch in rollback_ledger.items():
        if handle == winner_handle:
            raise SpeculationReconciliationError(
                f"rollback targeted winner handle={handle!r} via branch={branch!r}; "
                f"loser inverse aliased onto committed resource"
            )
        if handle not in forward_ledger:
            raise SpeculationReconciliationError(
                f"inverse without forward effect: handle={handle!r} branch={branch!r}; "
                f"treat 404-on-rollback as fault, not no-op"
            )


def reserve_resolved_handle(
    resolved_handle: str,
    branch_id: str,
    reservations: dict[str, str],
) -> None:
    # Called INSIDE the tool layer, after argument normalization, before the
    # effect is applied. Prevents two speculative branches from aliasing.
    if resolved_handle in reservations and reservations[resolved_handle] != branch_id:
        raise SpeculationReconciliationError(
            f"speculation conflict: handle={resolved_handle!r} already reserved by "
            f"live branch={reservations[resolved_handle]!r}; branch={branch_id!r} "
            f"must re-plan with a distinct resolved identity"
        )
    reservations[resolved_handle] = branch_id
