Reproducible CPU Lab · PYTHON

Streaming measurement

Companion Writing
Measuring Streaming Systems Without Fooling Yourself →

Separate first-event latency, inter-event gaps, completion time, and failures. Build a small measurement tool whose arithmetic can be checked against known timelines.

Run from the repository root (the directory containing labs). After downloading the archive, extract it and run from the extracted root.

sh
python3 -m unittest discover -s labs/python/streaming -p "test_*.py" -v
python3 labs/python/streaming/measure.py

Go requires 1.24 or newer. Python requires 3.11 or newer. The two LLM labs additionally require CPU-capable PyTorch in labs/.venv; see the collection instructions.

Tests use deterministic substitutes or synthetic tensors. No paid API, cloud service, model-weight download, GPU, or external project checkout is required. A failed test is a correctness issue to investigate; raw timing changes alone do not fail the tests.

Read the source and tests together. The article's code excerpts are extracted from marked regions in these files during the website build.

Source & Verification Files

Primary implementation expanded · Click any file header to toggle
Implementationmeasure.py
100 lines
/labs/python/streaming/measure.pyRaw file ↓
python
"""Measure stream events, not unobserved model tokens. Standard library only."""

from __future__ import annotations
import json
import math
import time
from collections.abc import AsyncIterator, Callable
from dataclasses import dataclass
from typing import Iterable


@dataclass(frozen=True)
class StreamRecord:
    start: float
    events: tuple[float, ...]
    end: float
    error: str | None = None

    def __post_init__(self) -> None:
        times = (self.start, *self.events, self.end)
        if not all(math.isfinite(t) for t in times):
            raise ValueError("timestamps must be finite")
        if any(b < a for a, b in zip(times, times[1:])):
            raise ValueError("timestamps must be monotonic")


# region:metrics
def summarize(record: StreamRecord) -> dict:
    gaps = [b - a for a, b in zip(record.events, record.events[1:])]
    return {
        "event_count": len(record.events),
        "first_event_seconds": record.events[0] - record.start
        if record.events
        else None,
        "event_gaps_seconds": gaps,
        "mean_gap_seconds": sum(gaps) / len(gaps) if gaps else None,
        "duration_seconds": record.end - record.start,
        "error": record.error,
    }


def percentile(values: Iterable[float], q: float) -> float | None:
    ordered = sorted(values)
    if not 0 <= q <= 1:
        raise ValueError("quantile must be between zero and one")
    if not all(math.isfinite(v) for v in ordered):
        raise ValueError("samples must be finite")
    if not ordered:
        return None
    position = (len(ordered) - 1) * q
    low = math.floor(position)
    high = math.ceil(position)
    return ordered[low] + (ordered[high] - ordered[low]) * (position - low)


# endregion:metrics


async def record_stream(
    stream: AsyncIterator[object], clock: Callable[[], float] = time.perf_counter
) -> StreamRecord:
    """Collect one timestamp per yielded event. Caller owns iterator cleanup."""
    start = clock()
    events: list[float] = []
    error = None
    try:
        async for _ in stream:
            events.append(clock())
    except Exception as exc:
        error = type(exc).__name__
    return StreamRecord(start, tuple(events), clock(), error)


def report(records: list[StreamRecord]) -> dict:
    successful = [r for r in records if r.error is None]
    durations = [r.end - r.start for r in successful]
    first = [r.events[0] - r.start for r in successful if r.events]
    return {
        "requests": len(records),
        "errors": len(records) - len(successful),
        "empty_successes": sum(not r.events for r in successful),
        "success_duration_p50": percentile(durations, 0.5),
        "success_duration_p95": percentile(durations, 0.95),
        "success_first_event_p95": percentile(first, 0.95),
        "records": [summarize(r) for r in records],
    }


if __name__ == "__main__":
    fixtures = [
        StreamRecord(0.0, (0.2, 0.3, 0.5), 0.6),
        StreamRecord(0.0, (), 0.4, "upstream timeout"),
        StreamRecord(0.0, (0.1,), 0.25),
    ]
    print(
        json.dumps(
            {"measurement_kind": "synthetic timestamp fixture", **report(fixtures)},
            indent=2,
        )
    )
Verification Suitetest_measure.py
65 lines
/labs/python/streaming/test_measure.pyRaw file ↓
python
import unittest
from measure import StreamRecord, summarize, percentile, report, record_stream


class MeasurementTests(unittest.TestCase):
    def test_known_timeline(self):
        actual = summarize(StreamRecord(10.0, (10.2, 10.3, 10.5), 10.6))
        self.assertAlmostEqual(actual["first_event_seconds"], 0.2)
        self.assertAlmostEqual(actual["mean_gap_seconds"], 0.15)
        self.assertAlmostEqual(actual["duration_seconds"], 0.6)

    def test_empty_and_single(self):
        self.assertIsNone(summarize(StreamRecord(0, (), 1))["first_event_seconds"])
        self.assertIsNone(summarize(StreamRecord(0, (0.5,), 1))["mean_gap_seconds"])
        self.assertIsNone(percentile([], 0.95))

    def test_bad_timestamps(self):
        for args in [
            (0, (2,), 1),
            (2, (), 1),
            (0, (float("nan"),), 2),
            (0, (), float("inf")),
        ]:
            with self.assertRaises(ValueError):
                StreamRecord(*args)

    def test_percentile_definition(self):
        self.assertEqual(percentile([4, 1, 2, 3], 0.5), 2.5)
        self.assertAlmostEqual(percentile([1, 2, 3, 4], 0.95), 3.85)
        with self.assertRaises(ValueError):
            percentile([1], 2)

    def test_failures_not_disguised_as_fast_success(self):
        actual = report([StreamRecord(0, (1,), 2), StreamRecord(0, (), 0.1, "error")])
        self.assertEqual(actual["errors"], 1)
        self.assertEqual(actual["success_duration_p50"], 2)
        self.assertEqual(report([])["requests"], 0)


class RecorderTests(unittest.IsolatedAsyncioTestCase):
    async def test_events_and_failure_use_injected_clock(self):
        async def events():
            yield "first"
            yield "second"
            raise RuntimeError("upstream")

        ticks = iter([10.0, 10.2, 10.5, 10.6])
        record = await record_stream(events(), lambda: next(ticks))
        self.assertEqual(record.events, (10.2, 10.5))
        self.assertEqual(record.error, "RuntimeError")
        self.assertAlmostEqual(summarize(record)["duration_seconds"], 0.6)

    async def test_cancellation_is_not_converted_to_success(self):
        import asyncio

        async def events():
            raise asyncio.CancelledError()
            yield  # retain async iterator type

        with self.assertRaises(asyncio.CancelledError):
            await record_stream(events())


if __name__ == "__main__":
    unittest.main()
Recorded Outputstream-fixture.json
38 lines
/labs/results/stream-fixture.jsonRaw file ↓
json
{
  "measurement_kind": "synthetic timestamp fixture",
  "requests": 3,
  "errors": 1,
  "empty_successes": 0,
  "success_duration_p50": 0.425,
  "success_duration_p95": 0.5825,
  "success_first_event_p95": 0.195,
  "records": [
    {
      "event_count": 3,
      "first_event_seconds": 0.2,
      "event_gaps_seconds": [
        0.09999999999999998,
        0.2
      ],
      "mean_gap_seconds": 0.15,
      "duration_seconds": 0.6,
      "error": null
    },
    {
      "event_count": 0,
      "first_event_seconds": null,
      "event_gaps_seconds": [],
      "mean_gap_seconds": null,
      "duration_seconds": 0.4,
      "error": "upstream timeout"
    },
    {
      "event_count": 1,
      "first_event_seconds": 0.1,
      "event_gaps_seconds": [],
      "mean_gap_seconds": null,
      "duration_seconds": 0.25,
      "error": null
    }
  ]
}