# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-re-plan-around-a-capability-it-can-no-longer-see-phantom-capability-persistence-in-peer-discovery-under-partial-observability.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-re-plan-around-a-capability-it-can-no-longer-see-phantom-capability-persistence-in-peer-discovery-under-partial-observability.warrant.json
# Markdown SHA-256:   ca5f871ee513fd9c4da47136a87d718e1cb63e50edad2fb556ca43ea1a0a9c52
# Code AST SHA-256:   58417e2c71062f04102d4df18c0c18dd990d25d652586136dab3a55b0810f8c6
# Verified Classes:   PhantomCapabilityError, CapabilityAssertion, PlanNode, CapabilityCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class PhantomCapabilityError(RuntimeError):
    """Raised when a plan dispatches against a capability assertion whose
    freshness witness does not cover the dispatch instant, and no conditional
    fallback branch was retained."""
    pass


@dataclass
class CapabilityAssertion:
    peer_id: str
    capability: str
    observed_at: float          # monotonic seconds
    observed_by: str
    ttl: float                  # seconds the assertion is considered fresh
    issuer_signature: Optional[str] = None

    def is_fresh_at(self, instant: float) -> bool:
        return (instant - self.observed_at) <= self.ttl

    def covers(self, execution_window: float) -> bool:
        # usable for plan-time binding only if it outlives the plan
        return self.ttl >= execution_window


@dataclass
class PlanNode:
    capability: str
    bound_peer: str
    assertion: CapabilityAssertion
    fallback: Optional[Callable[[], str]] = None


class CapabilityCache:
    def __init__(self) -> None:
        self._store: Dict[tuple, CapabilityAssertion] = {}

    def put(self, a: CapabilityAssertion) -> None:
        if a.observed_at <= 0 or a.observed_by == "":
            raise PhantomCapabilityError(
                f"refusing to cache unstamped assertion for {a.peer_id}:{a.capability}"
            )
        self._store[(a.peer_id, a.capability)] = a

    def get(self, peer_id: str, capability: str) -> Optional[CapabilityAssertion]:
        return self._store.get((peer_id, capability))

    def invalidate(self, peer_id: str, capability: str) -> None:
        self._store.pop((peer_id, capability), None)


def dispatch(
    node: PlanNode,
    cache: CapabilityCache,
    now: float,
    execute: Callable[[str, str], str],
) -> str:
    """Dispatch a plan node, enforcing the freshness invariant at dispatch time."""
    assertion = cache.get(node.bound_peer, node.capability)
    if assertion is None:
        raise PhantomCapabilityError(
            f"no live assertion for {node.bound_peer}:{node.capability}"
        )

    if not assertion.is_fresh_at(now):
        # stale: must not dispatch unless a conditional fallback was retained
        if node.fallback is None:
            raise PhantomCapabilityError(
                f"stale assertion for {node.bound_peer}:{node.capability} "
                f"(age={now - assertion.observed_at:.1f}s > ttl={assertion.ttl}s) "
                f"and no fallback branch retained"
            )
        return node.fallback()

    try:
        return execute(node.bound_peer, node.capability)
    except LookupError as unsupported:
        # typed UNSUPPORTED_CAPABILITY from peer: invalidate this specific assertion
        cache.invalidate(node.bound_peer, node.capability)
        if node.fallback is None:
            raise PhantomCapabilityError(
                f"peer {node.bound_peer} rejected {node.capability} at dispatch; "
                f"fallback was pruned during planning"
            ) from unsupported
        return node.fallback()
