# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-speculative-side-effects-before-its-federation-warrant-is-co-signed-the-orphaned-effect-invariant-in-cross-org-o.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-speculative-side-effects-before-its-federation-warrant-is-co-signed-the-orphaned-effect-invariant-in-cross-org-o.warrant.json
# Markdown SHA-256:   87baa7a86d03ab86b2375a7eb3e5c0307a32a409ae28ce44dec9578b0927a605
# Code AST SHA-256:   d3c4840970f91eadb6f3e716d6f76b28adcc7b5ba0772d358ad4a911ec190902
# Verified Classes:   LineageConflictError, Warrant, Resolver
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class LineageConflictError(RuntimeError):
    """Raised when a compensating write would land on a resource whose
    co-signed lineage has split away from the compensating instance."""
    pass


@dataclass
class Warrant:
    lineage_id: str
    resource_id: str
    cosigned: bool = False


@dataclass
class Resolver:
    # resource_id -> set of lineage_ids co-signed since speculation began
    cosigned_lineages: dict[str, set[str]] = field(default_factory=dict)
    # resource_id -> authoritative counter value
    counters: dict[str, int] = field(default_factory=dict)
    # monotonic sequence authority lives at the resolver, never the requester
    _seq: int = 0

    def next_seq(self) -> int:
        self._seq += 1
        return self._seq

    def cosign(self, w: Warrant) -> None:
        w.cosigned = True
        self.cosigned_lineages.setdefault(w.resource_id, set()).add(w.lineage_id)

    def apply_compensation(self, w: Warrant, restore_to: int) -> None:
        # The currency guard: compensation is only legal if this lineage is
        # the *sole* co-signed lineage for the resource right now.
        live = self.cosigned_lineages.get(w.resource_id, set())
        if live - {w.lineage_id}:
            raise LineageConflictError(
                f"compensation by lineage {w.lineage_id} on {w.resource_id} "
                f"rejected: competing co-signed lineages {sorted(live - {w.lineage_id})} "
                f"are live; local pre-state is untrustworthy"
            )
        self.counters[w.resource_id] = restore_to


def speculate_and_maybe_compensate(
    resolver: Resolver,
    resource_id: str,
    lineage_id: str,
    speculative_delta: int,
    competing_lineage: Optional[str] = None,
) -> None:
    """Models the observed failure: A1 speculates, A2 is co-signed first,
    then A1 attempts to compensate against a stale pre-state."""
    pre_state = resolver.counters.get(resource_id, 12)  # A1's local belief
    resolver.counters[resource_id] = pre_state + speculative_delta  # speculative write

    # A2 is co-signed during the speculation window (sequence authority at resolver)
    if competing_lineage is not None:
        resolver.cosign(Warrant(competing_lineage, resource_id))
        resolver.counters[resource_id] = pre_state + 1  # A2's committed effect

    # A1's co-sign is rejected; it attempts compensation back to its stale pre_state
    w = Warrant(lineage_id, resource_id)
    resolver.apply_compensation(w, restore_to=pre_state)  # raises LineageConflictError


if __name__ == "__main__":
    r = Resolver()
    r.counters["R-7"] = 12
    try:
        speculate_and_maybe_compensate(
            r, "R-7", lineage_id="A1", speculative_delta=-3, competing_lineage="A2"
        )
    except LineageConflictError as e:
        print(f"bounded: {e}")
        print(f"authoritative counter preserved at {r.counters['R-7']}")
