rohitg00/ai-engineering-from-scratch · error · ValueError

probability must be between zero and one

Error message

probability must be between zero and one

What it means

Raised in percentile when the probability argument is outside [0, 1]. The rank formula ceil(probability * n) - 1 indexes into sorted traces, so a percentage-style input (like 95) would index past the end of the list.

Solutions

  1. Pass fractional probabilities: 0.5 for the median, 0.95 for p95
  2. Divide percentage inputs by 100 before calling summarize
  3. Validate the SLO configuration's percentile fields once at load time
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at certifications/claude/lessons/26-production-observability-latency-and-cost/code/main.py:34 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of rohitg00/ai-engineering-from-scratch@39ea8a1c6d (2026-08-26). Data as JSON: /api/errors/db5d185862534776. Report an issue: GitHub.

Appendix: source

Thrown at certifications/claude/lessons/26-production-observability-latency-and-cost/code/main.py:34

@dataclass(frozen=True)
class Trace:
    trace_id: str
    variant: str
    duration_ms: int
    input_tokens: int
    output_tokens: int
    cost_usd: float
    task_success: bool
    system_ok: bool
    cache_read: bool = False
    error_category: str | None = None


def percentile(values: list[int], probability: float) -> float:
    if not values:
        return 0.0
    if not 0 <= probability <= 1:
        raise ValueError("probability must be between zero and one")
    ordered = sorted(values)
    rank = max(0, math.ceil(probability * len(ordered)) - 1)
    return float(ordered[rank])


def summarize(traces: list[Trace]) -> dict[str, object]:
    if not traces:
        return {
            "requests": 0,
            "system_success_rate": 0.0,
            "task_success_rate": 0.0,
            "p50_ms": 0.0,
            "p95_ms": 0.0,
            "total_cost_usd": 0.0,
            "cost_per_task_success_usd": None,
            "cache_read_rate": 0.0,
            "errors": {},
        }

View on GitHub (pinned to 39ea8a1c6d)