# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-tool-invocation-when-a-concurrent-sibling-commits-a-conflicting-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-tool-invocation-when-a-concurrent-sibling-commits-a-conflicting-effect.warrant.json
# Markdown SHA-256:   f6d7ad9210077d1fcfffe42321c0150a0caec06d286a1fef49807d393ede1b33
# Code AST SHA-256:   168121757d694c176ffcf1278b2e179024845df0cbc697b43df4c45d9f7ed08d
# Verified Classes:   SpeculativeConflictError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculativeConflictError(RuntimeError):
    """Raised when a speculative branch cannot safely commit after a sibling commit."""
    pass


def resolve_speculative_commit(
    branch_read_set: dict,      # field -> value observed at speculation start
    branch_predicates: dict,    # field -> predicate fn evaluated on current state
    current_state: dict,        # committed state at commit time
    sibling_committed: bool,
    effect_is_idempotent: bool,
    can_recompute: bool,
) -> str:
    """
    Returns 'commit', 'recompute', or raises SpeculativeConflictError.
    The mandatory-abort zone is: sibling committed AND a consumed predicate
    no longer holds AND no compensation path exists.
    """
    predicate_broken = False
    for field, pred in branch_predicates.items():
        if field not in current_state:
            continue
        if not pred(current_state[field]):
            predicate_broken = True
            break

    if not sibling_committed:
        return "commit"

    if not predicate_broken:
        # Predicate-stable conflict: proceed. Aborting here is over-conservative.
        return "commit"

    if can_recompute and not effect_is_idempotent:
        # Predicate-breaking but compensable: recompute within deadline.
        return "recompute"

    if effect_is_idempotent:
        # Idempotent effects can be re-emitted safely after re-read.
        return "recompute"

    # Mandatory abort zone: predicate broken, no compensation, non-idempotent.
    raise SpeculativeConflictError(
        f"Speculative branch read-set invalidated by sibling commit; "
        f"predicate broken on {field!r} and no compensation path exists. "
        f"observed={branch_read_set.get(field)!r} "
        f"current={current_state.get(field)!r}"
    )
