# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-optimistic-multi-agent-planners-from-deadlocking-on-stale-reservations.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-optimistic-multi-agent-planners-from-deadlocking-on-stale-reservations.warrant.json
# Markdown SHA-256:   13675dec45a09b6da46980e600f928f1f517437427b9410c4c87c37962b8a748
# Code AST SHA-256:   840ab9ab507b4e6763da3ad8bf60ce55f9f5e690d18f1697bcee6d5cf5aa8c28
# Verified Classes:   ReservationInvariantError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ReservationInvariantError(RuntimeError):
    """Raised when a reservation lacks a live owner with a release edge."""
    pass


def assert_release_edge_complete(reservation, manager_owns_release: bool) -> None:
    state = reservation["state"]
    owner_alive = reservation.get("owner_alive", False)
    has_release_edge = reservation.get("release_edge") is not None

    if state in ("held", "revoked") and not owner_alive:
        if not (manager_owns_release and has_release_edge):
            raise ReservationInvariantError(
                f"reservation {reservation['id']} in state={state!r} has no live "
                f"owner and no manager-owned release edge; acquire path must not "
                f"block on this entry"
            )
    if state == "revoked" and not manager_owns_release:
        raise ReservationInvariantError(
            f"reservation {reservation['id']} revoked without manager-owned "
            f"reclaim; optimistic commit is unsound for this resource class"
        )


def acquire(reservation, manager_owns_release: bool):
    assert_release_edge_complete(reservation, manager_owns_release)
    if reservation["state"] != "free":
        raise ReservationInvariantError(
            f"acquire blocked on non-free reservation {reservation['id']} "
            f"(state={reservation['state']!r}); reclaim before retry"
        )
    reservation["state"] = "held"
    return reservation
