# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trajectory-level-latency-slos-from-silently-absorbing-tool-error-budget-exhaustion-in-agent-observability-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trajectory-level-latency-slos-from-silently-absorbing-tool-error-budget-exhaustion-in-agent-observability-pipelines.warrant.json
# Markdown SHA-256:   2cbe05d29181b2beace0d26e99fb9178d5fa089816cf8654a49a8a02fff3696a
# Code AST SHA-256:   5bf3f7824dd6e4b99afbe226358e4fff75ad2bab2fe8b5b46b16969513f2807b
# Verified Classes:   SLOAliasingError, TrajectoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SLOAliasingError(RuntimeError):
    """Raised when trajectory latency SLO and tool-error budget are aliased."""
    pass


@dataclass
class TrajectoryRecord:
    trajectory_id: str
    wall_clock_s: float
    retry_backoff_s: float
    tool_invocations: int
    tool_errors: int
    terminal_status: str  # "success" | "degraded" | "failed"
    contains_fabrication: bool


def evaluate_joint_slo(
    records: list[TrajectoryRecord],
    latency_slo_s: float,
    tool_error_budget: float,
    retry_headroom_fraction: float = 0.5,
) -> dict:
    if not records:
        raise SLOAliasingError("no trajectories to evaluate")

    effective_latencies = [r.wall_clock_s - r.retry_backoff_s for r in records]
    total_invocations = sum(r.tool_invocations for r in records)
    total_errors = sum(r.tool_errors for r in records)
    observed_error_rate = total_errors / total_invocations if total_invocations else 0.0

    # Retry-adjusted latency: is wall-clock creep explained by retry backoff?
    mean_backoff = sum(r.retry_backoff_s for r in records) / len(records)
    baseline_p50 = sorted(effective_latencies)[len(effective_latencies) // 2]
    headroom = latency_slo_s - baseline_p50

    if headroom <= 0:
        raise SLOAliasingError(
            f"effective latency p50 {baseline_p50:.1f}s already exceeds SLO {latency_slo_s:.1f}s"
        )

    # Aliasing condition: expected retry cost exceeds fraction of latency headroom.
    if mean_backoff > retry_headroom_fraction * headroom:
        raise SLOAliasingError(
            f"latency SLO aliased with tool-error budget: "
            f"mean retry backoff {mean_backoff:.2f}s > "
            f"{retry_headroom_fraction:.0%} of headroom {headroom:.2f}s; "
            f"per-SLO alerting is invalid, emit joint breach signal"
        )

    # Hallucination rate must include degraded trajectories, not success-only.
    terminal = [r for r in records if r.terminal_status in ("success", "degraded")]
    hallucination_rate = (
        sum(1 for r in terminal if r.contains_fabrication) / len(terminal)
        if terminal else 0.0
    )
    success_only = [r for r in terminal if r.terminal_status == "success"]
    success_only_halluc = (
        sum(1 for r in success_only if r.contains_fabrication) / len(success_only)
        if success_only else 0.0
    )

    return {
        "effective_latency_p50": baseline_p50,
        "observed_tool_error_rate": observed_error_rate,
        "tool_error_budget_exhausted": observed_error_rate > tool_error_budget,
        "hallucination_rate_all_terminal": hallucination_rate,
        "hallucination_rate_success_only": success_only_halluc,
        "denominator_bias": hallucination_rate - success_only_halluc,
    }
