# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-reject-a-converged-speculative-plan-branch-that-passed-its-own-local-consistency-check.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-reject-a-converged-speculative-plan-branch-that-passed-its-own-local-consistency-check.warrant.json
# Markdown SHA-256:   be3d14cf483dfa5534d78e5405defe3be4da83a0b12ef58450535e590d8bf181
# Code AST SHA-256:   091347c67766886eb4263be1263c3bc39c912199f13387e9d34fc5bf5a226ccf
# Verified Classes:   UnsoundLocalCertificate, MergeInvariantViolation, Branch, MergeCoordinator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Set


class UnsoundLocalCertificate(RuntimeError):
    """Raised when a branch claims CONVERGENT but its mutation set
    intersects a sibling's mutation set on a constrained resource,
    making its local certificate merge-unauthorizing."""
    pass


class MergeInvariantViolation(RuntimeError):
    """Raised when composed branch deltas violate a global invariant."""
    pass


@dataclass
class Branch:
    branch_id: str
    mutations: Dict[str, int]          # resource -> delta
    local_certificate: str             # "LOCALLY_CONVERGENT" | "CONVERGENT"
    tokens_spent: int


@dataclass
class MergeCoordinator:
    capacity: int = 100
    constrained: Set[str] = field(default_factory=lambda: {"R1"})
    pressure: Dict[str, float] = field(default_factory=dict)

    def contention_density(self, branches: List[Branch]) -> float:
        if len(branches) < 2:
            return 0.0
        contended = 0
        for i, b in enumerate(branches):
            for other in branches[i + 1:]:
                if set(b.mutations) & set(other.mutations) & self.constrained:
                    contended += 1
                    break
        return contended / len(branches)

    def certify_mergeable(self, branches: List[Branch]) -> None:
        # Rule 2: reject any branch claiming full CONVERGENT while
        # touching a constrained resource also touched by a sibling.
        for b in branches:
            siblings = [o for o in branches if o is not b]
            shared = set(b.mutations) & self.constrained
            if b.local_certificate == "CONVERGENT" and shared:
                for s in siblings:
                    if shared & set(s.mutations):
                        raise UnsoundLocalCertificate(
                            f"branch {b.branch_id} claims CONVERGENT but "
                            f"shares {shared} with {s.branch_id}; certificate "
                            f"is not merge-authorizing"
                        )

    def merge(self, branches: List[Branch]) -> Dict[str, int]:
        self.certify_mergeable(branches)
        # Rule 1: compute contention before choosing policy.
        density = self.contention_density(branches)
        if density > 0.5:
            # Pessimistic: admit in arrival order, stop at first overflow.
            composed: Dict[str, int] = {}
            for b in branches:
                trial = dict(composed)
                for r, d in b.mutations.items():
                    trial[r] = trial.get(r, 0) + d
                if trial.get("R1", 0) > self.capacity:
                    self.pressure["R1"] = self.pressure.get("R1", 0.0) + 1.0
                    raise MergeInvariantViolation(
                        f"pessimistic merge rejected {b.branch_id}: "
                        f"R1 would reach {trial['R1']} > {self.capacity}"
                    )
                composed = trial
            return composed
        # Optimistic: compose all, then validate.
        composed = {}
        for b in branches:
            for r, d in b.mutations.items():
                composed[r] = composed.get(r, 0) + d
        if composed.get("R1", 0) > self.capacity:
            self.pressure["R1"] = self.pressure.get("R1", 0.0) + 1.0
            raise MergeInvariantViolation(
                f"optimistic merge violated CAP on R1: {composed['R1']}"
            )
        return composed


# Reproduction of the observed oscillation and its fix.
branches = [
    Branch("A", {"R1": 40, "R2": -10}, "CONVERGENT", 1800),
    Branch("B", {"R1": 45}, "CONVERGENT", 3100),
    Branch("C", {"R1": 20}, "CONVERGENT", 2400),
]
coord = MergeCoordinator()
try:
    coord.merge(branches)
except UnsoundLocalCertificate as e:
    # Correct outcome: certificates were unsound; do not spend more tokens
    # re-forking the same contention pattern. Pressure signal is now set.
    assert coord.pressure["R1"] >= 0.0
    print(f"rejected before token waste: {e}")
