# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-execution-when-peer-agents-hold-conflicting-plans-and-rollback-is-not-idempotent.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-execution-when-peer-agents-hold-conflicting-plans-and-rollback-is-not-idempotent.warrant.json
# Markdown SHA-256:   8608882aa1d72f6b71ca39a2f90a815c338f033c8f770803fc580cece771ad45
# Code AST SHA-256:   557738881b88d3786d32cfc4868feb128135dbc9a7b4e66efb0dd7355533e5aa
# Verified Classes:   UnsafeRollbackError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnsafeRollbackError(RuntimeError):
    """Raised when a speculative branch must be aborted but its effects are not
    fully invertible, or an inverse is not idempotent, or the survivor cannot
    re-validate after abort. Signals that quiesce-and-reconcile is required."""


def resolve_conflict(
    survivor_effects: list[dict],
    loser_effects: list[dict],
    resource_claims: dict[str, set[str]],
    effects_visible: bool,
) -> str:
    # 1. Disjointness check: overlapping claims invalidate effect speculation.
    for res, owners in resource_claims.items():
        if len(owners) > 1:
            raise UnsafeRollbackError(
                f"overlapping speculative claims on resource {res!r}: {owners}"
            )

    # 2. Invertibility check: every loser effect must carry an idempotent inverse.
    for eff in loser_effects:
        if not eff.get("inverse_idempotent", False):
            raise UnsafeRollbackError(
                f"loser effect {eff.get('id')!r} has no idempotent inverse; "
                "abort would create an unowned intermediate state"
            )

    # 3. Visibility barrier: aborting after effects are live is unsafe unless
    #    the survivor can re-validate against the post-abort state.
    if effects_visible and not all(e.get("revalidatable", False) for e in survivor_effects):
        raise UnsafeRollbackError(
            "effects already visible and survivor cannot re-validate; "
            "must quiesce and reconcile, not abort"
        )

    return "abort_loser_and_revalidate_survivor"
