# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-context-budget-routing-collapse-between-rag-and-persistent-memory-tiers-under-latency-slo-pressure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-context-budget-routing-collapse-between-rag-and-persistent-memory-tiers-under-latency-slo-pressure.warrant.json
# Markdown SHA-256:   c2914e95208695f25c11ba94a607f88af08f8de7516278817c432ba7ea93e607
# Code AST SHA-256:   961af04092bfb80313777a3fe63776e9231fea1cddd77b6be2b2be8ed52b7b79
# Verified Classes:   FactClass, RouteDecision, StaleMemoryRoutingError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class FactClass(Enum):
    STABLE = "stable"      # immutable: name, locale, stated preference
    VOLATILE = "volatile"  # epoch-bound: plan tier, entitlement, policy version


@dataclass
class RouteDecision:
    tier: str
    defer: bool


class StaleMemoryRoutingError(RuntimeError):
    """Raised when a volatile-fact query is routed to the memory tier
    without slack to verify, i.e. the router is about to answer from
    superseded state under deadline pressure."""


VERIFY_COST_MS = 700  # cost to confirm a memory hit via cheap RAG check


def route_turn(
    fact_class: FactClass,
    deadline_slack_ms: float,
    memory_call_ms: float = 60.0,
) -> RouteDecision:
    """Mutability-keyed tier eligibility. Memory fallback is legal only for
    STABLE facts, or for VOLATILE facts when slack covers verification."""
    if fact_class is FactClass.STABLE:
        return RouteDecision(tier="memory", defer=False)

    # VOLATILE: memory is only acceptable if we can verify within slack.
    if deadline_slack_ms >= VERIFY_COST_MS:
        return RouteDecision(tier="memory_then_verify", defer=False)

    # No slack to verify a volatile fact. Answering from memory here is the
    # exact failure: fast, confident, and stale.
    raise StaleMemoryRoutingError(
        f"volatile-fact query has {deadline_slack_ms:.0f}ms slack, below "
        f"{VERIFY_COST_MS}ms verification cost; memory-tier fallback would "
        f"return superseded state. Route to RAG or defer the turn."
    )


def safe_route(fact_class, deadline_slack_ms):
    try:
        return route_turn(fact_class, deadline_slack_ms)
    except StaleMemoryRoutingError:
        # Correct degradation: defer rather than answer stale.
        return RouteDecision(tier="rag_or_defer", defer=True)
