# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-a-cheap-heuristic-stop-being-trusted-the-cost-model-inversion-boundary-in-query-planning.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-a-cheap-heuristic-stop-being-trusted-the-cost-model-inversion-boundary-in-query-planning.warrant.json
# Markdown SHA-256:   d934a8f721d326b15de9b2edb3d5b7a337b1d01d873449ea05bc18b82f655813
# Code AST SHA-256:   a3cdafcb8c050d70824b642ee73de0fee9ad880261129df6bec303076faad93c
# Verified Classes:   MarginViolationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class MarginViolationError(RuntimeError):
    """Raised when a cheap-heuristic decision is made below its error bound."""
    pass


def select_candidate(candidates, proxy, error_bound, measure=None):
    """
    candidates: list of candidate strategy ids
    proxy: callable(id) -> float (lower is better)
    error_bound: relative error of the proxy, e.g. 0.05 for 5%
    measure: optional callable(id) -> float, true cost via bounded measurement
    """
    ranked = sorted(candidates, key=proxy)
    if len(ranked) == 1:
        return ranked[0]

    c1, c2 = ranked[0], ranked[1]
    p1, p2 = proxy(c1), proxy(c2)
    denom = max(p1, p2) or 1.0
    margin = abs(p1 - p2) / denom

    if margin > error_bound:
        return c1  # proxy ordering is entitled to be trusted

    # Margin collapsed below the proxy's own error: ordering is noise.
    if measure is not None:
        m1, m2 = measure(c1), measure(c2)
        if abs(m1 - m2) / (max(m1, m2) or 1.0) > error_bound:
            return c1 if m1 < m2 else c2
        raise MarginViolationError(
            f"candidates {c1!r} and {c2!r} indistinguishable under both "
            f"proxy (margin={margin:.4f}) and measurement "
            f"(true={m1:.4f} vs {m2:.4f}); refusing to commit a plan"
        )

    raise MarginViolationError(
        f"proxy margin {margin:.4f} <= error bound {error_bound:.4f} for "
        f"{c1!r} vs {c2!r}; no decorrelated signal available, escalate"
    )
