# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-capability-claim-staleness-in-federated-agent-routing-when-latency-aware-matching-silently-binds-to-a-degraded-peer.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-capability-claim-staleness-in-federated-agent-routing-when-latency-aware-matching-silently-binds-to-a-degraded-peer.warrant.json
# Markdown SHA-256:   83d44682dc5d4e7e8e91ea169dc397688a1e1942ee916e945a6dd3108d7c85da
# Code AST SHA-256:   0652432ae4410650f3c2418f948aef75f5fa6b7668d6c9715a3e85f99be5621e
# Verified Classes:   StaleByLoadError, CapabilityClaim, PeerState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class StaleByLoadError(RuntimeError):
    """Raised when a peer's capability claim was issued at a latency
    regime that no longer matches its current measured RTT, making the
    composite capability*latency score incommensurable."""
    pass


@dataclass
class CapabilityClaim:
    peer_id: str
    capability: str
    confidence: float
    issued_at: float          # monotonic seconds
    issue_rtt_ms: float       # RTT at which confidence was measured
    ttl_s: float = 60.0


@dataclass
class PeerState:
    peer_id: str
    claim: CapabilityClaim
    current_rtt_ms: float
    last_bound_task: dict = field(default_factory=dict)


STALENESS_FACTOR = 2.0  # empirical k: current_rtt > issue_rtt * k => stale-by-load


def claim_is_stale_by_load(peer: PeerState, now: float) -> bool:
    claim = peer.claim
    if now - claim.issued_at > claim.ttl_s:
        return True  # ordinary TTL staleness
    if peer.current_rtt_ms > claim.issue_rtt_ms * STALENESS_FACTOR:
        return True  # load-regime staleness: the silent one
    return False


def select_peer(
    peers: list[PeerState],
    capability: str,
    deadline_ms: float,
    now: float,
) -> PeerState:
    eligible = [
        p for p in peers
        if p.claim.capability == capability
        and p.current_rtt_ms <= deadline_ms
        and not claim_is_stale_by_load(p, now)
    ]
    if not eligible:
        # Distinguish hard ineligibility from the load-staleness case so
        # callers can decide to wait for a re-issued claim rather than fail.
        stale = [
            p for p in peers
            if p.claim.capability == capability
            and p.current_rtt_ms <= deadline_ms
            and claim_is_stale_by_load(p, now)
        ]
        if stale:
            raise StaleByLoadError(
                f"all deadline-eligible peers for {capability!r} have "
                f"capability claims issued at a stale latency regime: "
                f"{[(p.peer_id, p.claim.issue_rtt_ms, p.current_rtt_ms) for p in stale]}"
            )
        raise StaleByLoadError(
            f"no peer satisfies capability={capability!r} within deadline={deadline_ms}ms"
        )

    # Stable tie-break: do NOT rank by latency-discounted confidence, which
    # oscillates when fresh RTT crosses stale issue_rtt. Rank by a stable
    # hash of peer_id so a recovering peer does not reclaim traffic until
    # its claim is re-issued at the new latency.
    def stable_key(p: PeerState) -> str:
        return hashlib.sha256(p.peer_id.encode()).hexdigest()

    eligible.sort(key=stable_key)
    return eligible[0]


def bind_task(
    peers: list[PeerState],
    capability: str,
    task_id: str,
    deadline_ms: float,
    now: float,
) -> PeerState:
    chosen = select_peer(peers, capability, deadline_ms, now)
    # Binding-churn detection: if this task was previously bound to a
    # different peer within the same capability, record churn. Churn on a
    # task class that should be stable is the pre-duplicate-write signal.
    for p in peers:
        prev = p.last_bound_task.get(task_id)
        if prev is not None and prev != chosen.peer_id:
            raise StaleByLoadError(
                f"binding churn for task {task_id!r}: {prev} -> {chosen.peer_id} "
                f"within oscillation window; suppress rebind until claim refresh"
            )
    chosen.last_bound_task[task_id] = chosen.peer_id
    return chosen
