chore(release): promote 6.0.0 to main

This commit is contained in:
imSp4rky
2026-11-23 18:11:04 -07:00
425 changed files with 52275 additions and 12006 deletions
+80
View File
@@ -0,0 +1,80 @@
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_1.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_2.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_3.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_4.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_5.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_6.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_7.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_8.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_9.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_10.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_11.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_12.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_13.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_14.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_15.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_16.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_17.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_18.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_19.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_20.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_21.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_22.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_23.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_24.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_25.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_26.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_27.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_28.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_29.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_30.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_31.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_32.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_33.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_34.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_35.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_36.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_37.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_38.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_39.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_40.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_41.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_42.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_43.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_44.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_45.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_46.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_47.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_48.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_49.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_50.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_51.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_52.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_53.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_54.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_55.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_56.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_57.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_58.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_59.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_60.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_61.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_62.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_63.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_64.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_65.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_66.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_67.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_68.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_69.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_70.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_71.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_72.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_73.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_74.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_75.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_76.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_77.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_78.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_79.m4v
https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps_3840x2160_12000k/bbb_30fps_3840x2160_12000k_80.m4v
@@ -0,0 +1,4 @@
https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v9/main.mp4?cb=0
https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v9/main.mp4?cb=1
https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v9/main.mp4?cb=2
https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/v9/main.mp4?cb=3
+702
View File
@@ -0,0 +1,702 @@
#!/usr/bin/env python3
"""
Benchmark the unified downloader (``unshackle.core.downloaders.requests.requests``)
throughput against worker count, to baseline the current downloader and later
validate an adaptive worker controller.
Default (synthetic) mode spins up a loopback HTTP server serving deterministic
segments, feeds them through the real download code path, and reports
workers -> seconds -> MB/s plus a tail-droop metric. Optional response shaping
(``--latency``, ``--rate``) and fault injection (``--fault-*``) approximate a
misbehaving CDN. ``--urls-file`` swaps in real URLs (only mode that hits the
network; fault flags are ignored there).
Fault modes (synthetic only) exercise the downloader's timeout / retry / hedge
paths. Because the real read timeout is 30s, pair them with ``--fast-timeouts``
(bench-only monkeypatch of READ_TIMEOUT/RETRY_WAIT/HEDGE_MIN_WAIT to a few
seconds) so fault runs finish quickly. A ``--fault-stall`` run is expected to
FAIL its completeness check (the stall never resolves) and exit non-zero.
Usage:
uv run python scripts/bench_downloader.py --segments 64 --workers 1,2,4,8,16
uv run python scripts/bench_downloader.py --rate 2048 --latency 50
uv run python scripts/bench_downloader.py --fault-503 2 --fast-timeouts --segments 8
uv run python scripts/bench_downloader.py --urls-file urls.txt --impersonate Chrome131
"""
from __future__ import annotations
import http.server
import importlib
import math
import multiprocessing
import os
import socket
import socketserver
import statistics
import struct
import tempfile
import threading
import time
from pathlib import Path
from shutil import rmtree
from typing import Any, Optional
import click
import fault_server
from rich.console import Console
from rich.table import Table
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.downloaders.requests import requests as download_batch
dl_mod = importlib.import_module("unshackle.core.downloaders.requests")
MIB = 1024 * 1024
TAIL_FRACTION = 0.25
TAIL_SLOW_KIB = 256
console = Console()
class SegmentServer(socketserver.ThreadingTCPServer):
"""Loopback server serving a shared synthetic buffer with optional shaping + faults."""
allow_reuse_address = True
daemon_threads = True
request_queue_size = 128
def __init__(
self, buffer: bytes, latency_ms: int, rate_kib: int, faults: dict[str, int], total_segments: int
) -> None:
self.buffer = buffer
self.latency_ms = latency_ms
self.rate_kib = rate_kib
self.faults = faults
self.total_segments = total_segments
self.attempts: dict[int, int] = {}
self.lock = threading.Lock()
self.stall_event = threading.Event()
super().__init__(("127.0.0.1", 0), SegmentHandler)
def reset(self) -> None:
with self.lock:
self.attempts.clear()
def handle_error(self, request: Any, client_address: Any) -> None:
pass
class SegmentHandler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *_: Any) -> None:
pass
def _parse_range(self, total: int) -> Optional[tuple[int, int]]:
header = self.headers.get("Range")
if not header or not header.startswith("bytes="):
return None
start_s, _, end_s = header[len("bytes=") :].partition("-")
start = int(start_s) if start_s else 0
end = int(end_s) if end_s else total - 1
return start, min(end, total - 1)
def do_GET(self) -> None:
server: SegmentServer = self.server # type: ignore[assignment]
if not self.path.startswith("/seg/"):
self.send_error(404)
return
try:
idx = int(self.path.rsplit("/", 1)[-1])
except ValueError:
self.send_error(404)
return
with server.lock:
server.attempts[idx] = server.attempts.get(idx, 0) + 1
attempt = server.attempts[idx]
f = server.faults
if idx < f["stall"]:
self._serve(stall=True)
return
if attempt == 1 and idx < f["reset"]:
self._serve(reset=True)
return
if attempt == 1 and idx < f["http503"]:
self.send_response(503)
self.send_header("Content-Length", "0")
self.end_headers()
return
rate = server.rate_kib
if f["tail_slow"] and idx >= server.total_segments - f["tail_slow"]:
rate = TAIL_SLOW_KIB
if f["tail_slow_once"] and attempt == 1 and idx >= server.total_segments - f["tail_slow_once"]:
rate = TAIL_SLOW_KIB
self._serve(rate=rate)
def _serve(self, rate: int = 0, stall: bool = False, reset: bool = False) -> None:
server: SegmentServer = self.server # type: ignore[assignment]
full = server.buffer
rng = self._parse_range(len(full))
if rng is not None and rng[0] >= len(full):
self.send_response(416)
self.send_header("Content-Range", f"bytes */{len(full)}")
self.send_header("Content-Length", "0")
self.end_headers()
return
if rng is not None:
start, end = rng
body = full[start : end + 1]
self.send_response(206)
self.send_header("Content-Range", f"bytes {start}-{end}/{len(full)}")
else:
start = 0
body = full
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Type", "application/octet-stream")
self.end_headers()
if server.latency_ms:
time.sleep(server.latency_ms / 1000)
try:
if stall:
stall_point = len(full) // 2
chunk = full[start:stall_point]
if chunk:
self.wfile.write(chunk)
self.wfile.flush()
server.stall_event.wait(120)
elif reset:
half = max(1, len(body) // 2)
self.wfile.write(body[:half])
self.wfile.flush()
sock = self.connection
sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
sock.close()
self.close_connection = True
else:
self._write_body(body, rate)
except (BrokenPipeError, ConnectionError, OSError):
self.close_connection = True
def _write_body(self, body: bytes, rate_kib: int) -> None:
if rate_kib <= 0:
self.wfile.write(body)
return
chunk = 64 * 1024
per_chunk = chunk / (rate_kib * 1024)
for off in range(0, len(body), chunk):
self.wfile.write(body[off : off + chunk])
time.sleep(per_chunk)
def run_batch(
urls: list[str], out_dir: Path, workers: int, session: Optional[Any], adaptive: bool = False, procs: int = 1
) -> tuple[float, list[float], Optional[BaseException]]:
"""Download one batch through the real code path.
Returns (wall seconds, completion timestamps relative to start, error-or-None).
Clears the process-global cancel flag first so a prior failed run can't poison this one.
"""
DOWNLOAD_CANCELLED.clear()
completions: list[float] = []
err: Optional[BaseException] = None
start = time.perf_counter()
try:
for event in download_batch(
urls=urls,
output_dir=out_dir,
filename="seg_{i}.bin",
max_workers=workers,
session=session,
**({"adaptive": True} if adaptive else {}),
**({"processes": procs} if procs > 1 else {}),
):
if "file_downloaded" in event:
completions.append(time.perf_counter() - start)
except BaseException as exc: # noqa: BLE001 - bench records failure, keeps sweeping
err = exc
wall = time.perf_counter() - start
if err is not None:
deadline = time.monotonic() + dl_mod.READ_TIMEOUT + dl_mod.RETRY_WAIT + 2
while time.monotonic() < deadline and (
any(t.name.startswith("ThreadPoolExecutor") for t in threading.enumerate())
or multiprocessing.active_children()
):
time.sleep(0.1)
strays, locked = sweep_strays(out_dir)
pool_threads = sum(1 for t in threading.enumerate() if t.name.startswith("ThreadPoolExecutor"))
return wall, completions, err, strays, locked, pool_threads
def incomplete_segments(out_dir: Path, expected: int, expected_bytes: Optional[bytes]) -> list[int]:
"""Segment indexes that are missing, empty, or (synthetic mode) not byte-identical.
Content compare (not just size) is required: on a mid-body interruption the downloader
can finalize a full-size but zero-padded segment (the tmp is pre-truncated to content_length
and the exception path skips the truncate-back), so only a byte compare catches it. Real-URL
mode has no reference bytes, so it falls back to a nonzero check.
"""
bad: list[int] = []
for i in range(expected):
p = out_dir / f"seg_{i}.bin"
if not p.exists():
bad.append(i)
continue
if expected_bytes is not None:
if p.read_bytes() != expected_bytes:
bad.append(i)
elif p.stat().st_size == 0:
bad.append(i)
return bad
def downloaded_mib(out_dir: Path) -> float:
return sum(f.stat().st_size for f in out_dir.glob("seg_*.bin")) / MIB
def sweep_strays(out_dir: Path) -> tuple[int, int]:
"""Emulate the manifest merge's stray sweep (glob('*.!dev') unlink) at batch completion.
Returns (strays, locked). locked > 0 is the WinError 32 crash: a superseded hedge
racer still holds its file handle when merge deletes strays. POSIX deletes open
files silently, so there /proc/self/fd is checked to catch the same leak.
"""
strays = list(out_dir.glob("*.!dev"))
locked = 0
fd_dir = Path("/proc/self/fd")
if fd_dir.exists():
open_targets = set()
for fd in fd_dir.iterdir():
try:
open_targets.add(os.readlink(fd))
except OSError:
continue
locked = sum(1 for s in strays if str(s) in open_targets)
for s in strays:
try:
s.unlink()
except OSError:
locked += 1
return len(strays), locked
def tail_droop(completions: list[float], wall: float) -> tuple[int, float, float]:
"""Return (bucket size, seconds the last TAIL_FRACTION took, that as % of wall)."""
n = len(completions)
if n == 0 or wall <= 0:
return 0, 0.0, 0.0
c = sorted(completions)
bucket = max(1, math.ceil(n * TAIL_FRACTION))
boundary = c[n - bucket - 1] if n - bucket - 1 >= 0 else 0.0
tail_time = wall - boundary
return bucket, tail_time, tail_time / wall * 100
Row = tuple[int, float, float, int, float, float, list[int], bool, int, int, int]
def sweep(
urls: list[str],
workers: list[int],
runs: int,
session: Optional[Any],
server: Optional[SegmentServer],
expected_bytes: Optional[bytes],
adaptive: bool = False,
procs: int = 1,
) -> list[Row]:
rows: list[Row] = []
with tempfile.TemporaryDirectory(prefix="dlbench_") as root_str:
root = Path(root_str)
for w in workers:
samples: list[tuple[float, list[float], float, list[int], bool]] = []
for _ in range(runs):
if server is not None:
server.reset()
out_dir = Path(tempfile.mkdtemp(prefix="run_", dir=root))
secs, comps, err, strays, locked, pool_threads = run_batch(urls, out_dir, w, session, adaptive, procs)
bad = incomplete_segments(out_dir, len(urls), expected_bytes)
samples.append(
(secs, comps, downloaded_mib(out_dir), bad, err is not None, strays, locked, pool_threads)
)
rmtree(out_dir, ignore_errors=True)
median_s = statistics.median(s[0] for s in samples)
best = min(samples, key=lambda s: abs(s[0] - median_s))
bucket, tail_s, tail_pct = tail_droop(best[1], best[0])
mbps = best[2] / best[0] if best[0] else 0.0
rows.append(
(
w,
median_s,
mbps,
bucket,
tail_s,
tail_pct,
best[3],
best[4],
max(s[5] for s in samples),
max(s[6] for s in samples),
max(s[7] for s in samples),
)
)
return rows
def print_report(rows: list[Row], runs: int, total_segments: int) -> None:
table = Table(title=f"downloader throughput (median of {runs} run{'s' if runs != 1 else ''})")
table.add_column("workers", justify="right")
table.add_column("seconds", justify="right")
table.add_column("MB/s", justify="right")
table.add_column("status", justify="left")
table.add_column("sweep", justify="left")
for w, secs, mbps, _bucket, _ts, _tp, missing, raised, strays, locked, threads in rows:
if missing:
status = f"[red]FAIL {len(missing)} incomplete[/]"
elif raised:
status = "[yellow]raised (all present)[/]"
else:
status = "[green]ok[/]"
if locked:
sweep_status = f"[red]{locked} LOCKED (WinError 32)[/]"
elif threads:
sweep_status = f"[yellow]{threads} pool threads live[/]"
elif strays:
sweep_status = f"{strays} strays"
else:
sweep_status = "[green]clean[/]"
table.add_row(str(w), f"{secs:.3f}", f"{mbps:.1f}", status, sweep_status)
console.print(table)
for w, secs, _mbps, bucket, tail_s, tail_pct, *_rest in rows:
console.print(
f"tail-droop workers={w:<3} wall={secs:.3f}s "
f"last {int(TAIL_FRACTION * 100)}% ({bucket} of {total_segments} segs) "
f"took {tail_pct:.1f}% of wall ({tail_s:.3f}s)"
)
def fault_integrity(out_dir: Path, segments: int, seg_size: int) -> tuple[list[int], list[int]]:
"""Verify every output file byte-for-byte against its seeded expected payload.
Returns (missing, corrupt). ``corrupt`` (present but not byte-identical) is the loud
CORRUPTION signal: a fault path that finalizes wrong bytes must fail the run, not pass.
"""
missing: list[int] = []
corrupt: list[int] = []
for i in range(segments):
p = out_dir / f"seg_{i}.bin"
if not p.exists():
missing.append(i)
continue
if p.read_bytes() != fault_server.segment_payload(f"/seg/{i}", seg_size):
corrupt.append(i)
return missing, corrupt
FaultRow = tuple[int, float, float, list[int], list[int], bool, int, float, int, dict[int, int], int, int, int]
def print_fault_report(rows: list[FaultRow], runs: int, segments: int, profile: str) -> None:
plural = "s" if runs != 1 else ""
table = Table(title=f"fault profile '{profile}': {segments} segments (median of {runs} run{plural})")
table.add_column("workers", justify="right")
table.add_column("seconds", justify="right")
table.add_column("MB/s", justify="right")
table.add_column("status", justify="left")
table.add_column("requests", justify="right")
table.add_column("amp", justify="right")
table.add_column("sweep", justify="left")
for w, secs, mbps, missing, corrupt, raised, requests_seen, amp, _retries, _codes, strays, locked, threads in rows:
if corrupt:
status = f"[red]CORRUPTION {len(corrupt)} segs[/]"
elif missing:
status = f"[red]FAIL {len(missing)} incomplete[/]"
elif raised:
status = "[yellow]raised (all present)[/]"
else:
status = "[green]ok[/]"
if locked:
sweep_status = f"[red]{locked} LOCKED (WinError 32)[/]"
elif threads:
sweep_status = f"[yellow]{threads} pool threads live[/]"
elif strays:
sweep_status = f"{strays} strays"
else:
sweep_status = "[green]clean[/]"
table.add_row(str(w), f"{secs:.3f}", f"{mbps:.1f}", status, str(requests_seen), f"{amp:.2f}x", sweep_status)
console.print(table)
for w, _secs, _mbps, _missing, _corrupt, _raised, requests_seen, amp, retries, codes, *_rest in rows:
code_str = ", ".join(f"{c}:{n}" for c, n in codes.items()) or "none"
console.print(
f"amplification workers={w:<3} {requests_seen} requests for {segments} segments "
f"({amp:.2f}x, {retries} excess requests (retries/hedges/probes/parts)), statuses [{code_str}]"
)
def _procs_notice(procs: int, n_urls: int, session: Optional[Any]) -> None:
"""Warn loudly when --procs cannot engage, so a run is never mistaken for a multiprocess test."""
if procs <= 1:
return
if n_urls < dl_mod.MP_MIN_SEGMENTS:
console.print(
f"[yellow]--procs {procs} will NOT engage: {n_urls} segments < MP_MIN_SEGMENTS "
f"({dl_mod.MP_MIN_SEGMENTS}); the single-process path runs instead[/]"
)
elif dl_mod.build_session_spec(session) is None:
console.print(
f"[yellow]--procs {procs} will NOT engage: session not rebuildable in child processes; "
f"the single-process path runs instead[/]"
)
def run_fault_mode(
profile_name: str,
segments: int,
seg_size: int,
worker_counts: list[int],
runs: int,
session: Optional[Any],
adaptive: bool,
procs: int,
seed: int,
) -> None:
"""Start a FaultServer in-process, sweep worker counts, and report reliability + overhead.
Reuses run_batch/tail_droop/sweep_strays (via run_batch) and the report conventions, adding
request amplification and byte-exact integrity, the metrics that catch retry/hedge storms
and silent corruption against a misbehaving host.
"""
profile = fault_server.resolve_profile(profile_name)
server = fault_server.FaultServer(profile, seg_size, segments, seed)
threading.Thread(target=server.serve_forever, daemon=True).start()
host, port = str(server.server_address[0]), int(server.server_address[1])
urls = [f"http://{host}:{port}/seg/{i}" for i in range(segments)]
console.print(
f"[cyan]Fault mode:[/] profile={profile_name} seed={seed} "
f"{segments} x {seg_size / MIB:.2f} MiB, impersonate={getattr(session, 'impersonate_name', None) or 'none'}"
)
rows: list[FaultRow] = []
try:
with tempfile.TemporaryDirectory(prefix="faultbench_") as root_str:
root = Path(root_str)
for w in worker_counts:
samples: list[tuple[float, float, list[int], list[int], bool, int, dict[int, int], int, int, int]] = []
for _ in range(runs):
server.reset_counters()
out_dir = Path(tempfile.mkdtemp(prefix="run_", dir=root))
secs, _comps, err, strays, locked, pool_threads = run_batch(
urls, out_dir, w, session, adaptive, procs
)
missing, corrupt = fault_integrity(out_dir, segments, seg_size)
stats = server.stats()
samples.append(
(
secs,
downloaded_mib(out_dir),
missing,
corrupt,
err is not None,
stats["requests"],
stats["status_counts"],
strays,
locked,
pool_threads,
)
)
rmtree(out_dir, ignore_errors=True)
median_s = statistics.median(s[0] for s in samples)
best = min(samples, key=lambda s: abs(s[0] - median_s))
mbps = best[1] / best[0] if best[0] else 0.0
requests_seen = best[5]
amp = requests_seen / segments if segments else 0.0
retries = max(0, requests_seen - segments)
rows.append(
(
w,
median_s,
mbps,
best[2],
best[3],
best[4],
requests_seen,
amp,
retries,
best[6],
max(s[7] for s in samples),
max(s[8] for s in samples),
max(s[9] for s in samples),
)
)
finally:
server.stall_event.set()
server.shutdown()
print_fault_report(rows, runs, segments, profile_name)
broken = {row[0]: (row[3], row[4]) for row in rows if row[3] or row[4]}
if broken:
detail = "; ".join(f"workers={w}: missing {miss} corrupt {corr}" for w, (miss, corr) in broken.items())
raise click.ClickException(f"incomplete/corrupt downloads under fault profile: {detail}")
@click.command(context_settings={"help_option_names": ["-h", "--help"]})
@click.option("--segments", default=64, show_default=True, help="Synthetic segment count.")
@click.option("--seg-size", default=2 * MIB, show_default=True, help="Bytes per synthetic segment.")
@click.option("--workers", default="1,2,4,8,16", show_default=True, help="Comma list of max_workers to sweep.")
@click.option("--runs", default=1, show_default=True, help="Runs per worker count; median reported.")
@click.option(
"--latency", "latency_ms", default=0, show_default=True, help="Per-response delay before first byte (ms)."
)
@click.option(
"--rate", "rate_kib", default=0, show_default=True, help="Per-response throttle in KiB/s (0 = unthrottled)."
)
@click.option("--fault-stall", default=0, show_default=True, help="First N segments stall forever mid-body.")
@click.option("--fault-reset", default=0, show_default=True, help="First N segments RST mid-body on attempt 1.")
@click.option(
"--fault-503", "fault_503", default=0, show_default=True, help="First N segments return 503 on attempt 1."
)
@click.option(
"--fault-tail-slow", default=0, show_default=True, help=f"Last N segments throttled to {TAIL_SLOW_KIB} KiB/s."
)
@click.option(
"--fault-tail-slow-once",
default=0,
show_default=True,
help=f"Last N segments throttled to {TAIL_SLOW_KIB} KiB/s on attempt 1 only; a hedge/retry runs full speed.",
)
@click.option(
"--fast-timeouts",
is_flag=True,
help="Bench-only: shrink READ_TIMEOUT/RETRY_WAIT/HEDGE_MIN_WAIT so fault runs finish fast.",
)
@click.option(
"--urls-file",
type=click.Path(exists=True, dir_okay=False),
help="Real URLs, one per line (network mode; faults ignored).",
)
@click.option("--impersonate", help="rnet browser preset (e.g. Chrome131); uses RnetSession in either mode.")
@click.option("--adaptive", is_flag=True, help="Use the adaptive worker controller (max_workers becomes the cap).")
@click.option("--procs", default=1, show_default=True, help="Fan segments across N processes (multiprocess path).")
@click.option(
"--no-read1", is_flag=True, help="A/B: force racers back to blocking full-chunk reads (pre-fix behavior)."
)
@click.option(
"--fault-profile",
type=click.Choice(sorted(fault_server.PROFILES)),
help="Reliability mode: serve via the fault-injection server (fault_server.py) and verify integrity + amplification.",
)
@click.option("--seed", default=fault_server.DEFAULT_SEED, show_default=True, help="Fault RNG seed (--fault-profile).")
def main(
segments: int,
seg_size: int,
workers: str,
runs: int,
latency_ms: int,
rate_kib: int,
fault_stall: int,
fault_reset: int,
fault_503: int,
fault_tail_slow: int,
fault_tail_slow_once: int,
fast_timeouts: bool,
urls_file: Optional[str],
impersonate: Optional[str],
adaptive: bool,
procs: int,
no_read1: bool,
fault_profile: Optional[str],
seed: int,
) -> None:
"""Benchmark downloader throughput vs worker count, with optional fault injection."""
worker_counts = [int(w) for w in workers.split(",") if w.strip()]
faults = {
"stall": fault_stall,
"reset": fault_reset,
"http503": fault_503,
"tail_slow": fault_tail_slow,
"tail_slow_once": fault_tail_slow_once,
}
server: Optional[SegmentServer] = None
session: Optional[Any] = None
saved: dict[str, Any] = {}
total = segments
expected_bytes: Optional[bytes] = None
if fast_timeouts:
fast = {"READ_TIMEOUT": 2, "RETRY_WAIT": 1, "HEDGE_MIN_WAIT": 1.0}
saved = {k: getattr(dl_mod, k) for k in fast}
for k, v in fast.items():
setattr(dl_mod, k, v)
os.environ["UNSHACKLE_DL_TIMING_OVERRIDES"] = ",".join(f"{k}={v}" for k, v in fast.items())
if no_read1:
if hasattr(dl_mod, "RACER_READ1"):
saved["RACER_READ1"] = dl_mod.RACER_READ1
dl_mod.RACER_READ1 = False
else:
console.print("[yellow]--no-read1 ignored: only applies to older checkouts that still have RACER_READ1[/]")
if impersonate:
from unshackle.core.session import session as make_session
session = make_session(impersonate)
try:
if fault_profile:
if urls_file:
console.print("[yellow]--urls-file ignored in --fault-profile mode[/]")
if any(faults.values()):
console.print("[yellow]--fault-* flags ignored in --fault-profile mode (use the profile knobs)[/]")
_procs_notice(procs, segments, session)
run_fault_mode(fault_profile, segments, seg_size, worker_counts, runs, session, adaptive, procs, seed)
return
if urls_file:
if any(faults.values()):
console.print("[yellow]fault flags ignored in --urls-file mode[/]")
urls = [ln.strip() for ln in Path(urls_file).read_text().splitlines() if ln.strip()]
if not urls:
raise click.ClickException("--urls-file contained no URLs")
total = len(urls)
_procs_notice(procs, len(urls), session)
console.print(f"[cyan]URL-file mode:[/] {len(urls)} URLs, impersonate={impersonate or 'none'}")
else:
buffer = (b"unshackle-bench-" * (seg_size // 16 + 1))[:seg_size]
expected_bytes = buffer
server = SegmentServer(buffer, latency_ms, rate_kib, faults, segments)
threading.Thread(target=server.serve_forever, daemon=True).start()
host, port = str(server.server_address[0]), int(server.server_address[1])
urls = [f"http://{host}:{port}/seg/{i}" for i in range(segments)]
active = {k: v for k, v in faults.items() if v}
_procs_notice(procs, segments, session)
console.print(
f"[cyan]Synthetic mode:[/] {segments} x {seg_size / MIB:.2f} MiB "
f"(latency={latency_ms}ms, rate={rate_kib or 'unbounded'} KiB/s, "
f"faults={active or 'none'}, fast_timeouts={fast_timeouts}, impersonate={impersonate or 'none'})"
)
rows = sweep(urls, worker_counts, runs, session, server, expected_bytes, adaptive, procs)
print_report(rows, runs, total)
failed = {row[0]: row[6] for row in rows if row[6]}
if failed:
detail = "; ".join(f"workers={w}: segments {miss}" for w, miss in failed.items())
raise click.ClickException(f"incomplete/corrupt downloads: {detail}")
except KeyboardInterrupt:
console.print("[yellow]interrupted[/]")
raise SystemExit(130) from None
finally:
if server is not None:
server.stall_event.set()
server.shutdown()
for k, v in saved.items():
setattr(dl_mod, k, v)
os.environ.pop("UNSHACKLE_DL_TIMING_OVERRIDES", None)
if __name__ == "__main__":
main()
+12
View File
@@ -0,0 +1,12 @@
@echo off
REM Run the downloader benchmark suite and save a readable report for comparison.
REM Offline synthetic + fault runs by default; --live also hits public test CDNs
REM (needs network + ffprobe on PATH).
REM scripts\bench_suite.bat (offline suite)
REM scripts\bench_suite.bat --live (+ live/network tests)
REM Output: scripts\bench-results\<host>_<timestamp>.txt
setlocal
cd /d "%~dp0.."
if not exist "scripts\bench-results" mkdir "scripts\bench-results"
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0bench_suite.ps1" %*
endlocal
+111
View File
@@ -0,0 +1,111 @@
# Run the downloader benchmark suite and save a readable report for comparison.
# Offline synthetic + fault runs by default; -live also hits public test CDNs
# (needs network + ffprobe on PATH). Usually launched via bench_suite.bat.
# powershell -File scripts\bench_suite.ps1 # offline
# powershell -File scripts\bench_suite.ps1 --live # + live/network tests
param([string]$mode = "offline")
$ErrorActionPreference = "Continue"
Set-Location (Join-Path $PSScriptRoot "..")
$live = ($mode -eq "--live" -or $mode -eq "-live" -or $mode -eq "live")
$stamp = Get-Date -Format "yyyyMMdd-HHmmss"
$out = "scripts\bench-results\$($env:COMPUTERNAME)_$stamp.txt"
if (-not (Test-Path "scripts\bench-results")) { New-Item -ItemType Directory -Path "scripts\bench-results" | Out-Null }
function Run($a) {
Write-Output ""
Write-Output ("==================== python " + ($a -join " ") + " ====================")
# stringify the merged stream: PS 5.1 wraps native stderr lines in ErrorRecords,
# which render as NativeCommandError blocks (expected-fail runs looked like crashes)
& uv run python @a 2>&1 | ForEach-Object { "$_" }
if ($LASTEXITCODE -ne 0) {
Write-Output ("(exit code: " + $LASTEXITCODE + ")")
}
}
# collect everything, then tee to the report so tables land in the file too
& {
Write-Output "# unshackle downloader benchmark"
Write-Output ("host: " + $env:COMPUTERNAME)
Write-Output ("date: " + (Get-Date -Format "yyyy-MM-dd HH:mm:ss"))
Write-Output ("git: " + (git rev-parse --abbrev-ref HEAD) + " @ " + (git rev-parse --short HEAD))
$cpu = Get-CimInstance Win32_Processor | Select-Object -First 1
Write-Output ("cpu: " + $cpu.Name + " (" + $cpu.NumberOfCores + "c/" + $cpu.NumberOfLogicalProcessors + "t)")
$mem = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB)
$os = Get-CimInstance Win32_OperatingSystem
Write-Output ("mem: " + $mem + " GiB")
Write-Output ("os: " + $os.Caption + " " + $os.Version)
Write-Output ("python: " + (& uv run python -V 2>&1 | ForEach-Object { "$_" }))
Write-Output ("mode: " + $(if ($live) { "live" } else { "offline" }))
# negotiated link speed per NIC; shows the physical ceiling before the throughput run
Write-Output ""
Write-Output "==================== nic link speed ===================="
Get-NetAdapter | Where-Object Status -eq 'Up' |
ForEach-Object { Write-Output ("{0}: {1} ({2})" -f $_.Name, $_.LinkSpeed, $_.InterfaceDescription) }
# link baseline: max line speed, so downloader numbers can be read against it
# (e.g. "2Gbe -> ~1900 Mbps expected ceiling"). Uses whatever CLI exists.
Write-Output ""
Write-Output "==================== speedtest baseline ===================="
$global:LASTEXITCODE = 0
if (Get-Command speedtest -ErrorAction SilentlyContinue) {
& speedtest --accept-license --accept-gdpr 2>&1 | ForEach-Object { "$_" }
} elseif (Get-Command npx -ErrorAction SilentlyContinue) {
# Netflix fast.com; download + upload + latency + server, clean when piped
& npx --yes fast-cli --upload --verbose 2>&1 | ForEach-Object { "$_" }
} elseif (Get-Command speedtest-cli -ErrorAction SilentlyContinue) {
& speedtest-cli --simple 2>&1 | ForEach-Object { "$_" }
} else {
Write-Output "no speedtest CLI found (install Ookla 'speedtest', have npx, or 'pip install speedtest-cli') - skipping"
}
if ($LASTEXITCODE -ne 0) {
Write-Output ("(speedtest CLI failed - exit code " + $LASTEXITCODE + "; numbers above may be missing)")
}
# 1. Synthetic downloader benchmark (offline, deterministic)
Run @("scripts/bench_downloader.py", "--segments", "64", "--workers", "1,2,4,8,16", "--runs", "3")
Run @("scripts/bench_downloader.py", "--segments", "64", "--workers", "1,2,4,8,16", "--adaptive")
Run @("scripts/bench_downloader.py", "--workers", "4,8,16", "--no-read1")
# 2. Fault paths (--fault-stall is EXPECTED to fail + exit non-zero)
Run @("scripts/bench_downloader.py", "--fault-503", "2", "--fast-timeouts", "--segments", "8")
Run @("scripts/bench_downloader.py", "--fault-reset", "2", "--fast-timeouts", "--segments", "8")
Run @("scripts/bench_downloader.py", "--fault-stall", "1", "--fast-timeouts", "--segments", "8")
# 3. Multiprocess path (>=24 segments engages spawned children; strided chunk split).
# big batch: at small sizes the fixed spawn cost drowns the throughput signal
Run @("scripts/bench_downloader.py", "--segments", "128", "--workers", "8", "--procs", "2")
Run @("scripts/bench_downloader.py", "--segments", "128", "--workers", "8", "--procs", "4")
Run @("scripts/bench_downloader.py", "--fault-stall", "1", "--fast-timeouts", "--segments", "32", "--workers", "8", "--procs", "2")
# 4. Hedge + slow tail (last segments crawl; hedging and striding bound the tail)
Run @("scripts/bench_downloader.py", "--fault-tail-slow", "4", "--fast-timeouts", "--segments", "32", "--workers", "8")
Run @("scripts/bench_downloader.py", "--fault-tail-slow", "4", "--fast-timeouts", "--segments", "32", "--workers", "8", "--procs", "4")
Run @("scripts/bench_downloader.py", "--fault-tail-slow", "2", "--fast-timeouts", "--adaptive", "--segments", "16", "--workers", "8")
# 5. rnet session path (loopback through the TLS-fingerprint client's own read loop)
Run @("scripts/bench_downloader.py", "--segments", "32", "--workers", "8", "--impersonate", "Chrome131")
# 6. Leak regression tests (locked handles / leaked workers; unlink checks bite on Windows)
Write-Output ""
Write-Output "==================== pytest tests/test_downloader_leaks.py ===================="
& uv run pytest tests/test_downloader_leaks.py -q 2>&1 | ForEach-Object { "$_" }
if ($LASTEXITCODE -ne 0) {
Write-Output "(pytest failed or missing - run 'uv sync' to install dev deps)"
}
# 7. Live network tests (opt-in)
if ($live) {
Run @("scripts/live_manifest_test.py", "--workers", "16", "--track", "largest")
Run @("scripts/live_segmentbase_ab.py", "--track", "largest")
Run @("scripts/bench_downloader.py", "--urls-file", "scripts/bench-urls/apple_sustained_4x585mb.txt", "--impersonate", "Chrome131")
Run @("scripts/bench_downloader.py", "--urls-file", "scripts/bench-urls/akamai_4k_segments.txt", "--impersonate", "Chrome131")
}
Write-Output ""
Write-Output ("report saved: " + $out)
} | Tee-Object -FilePath $out
# progressive tee keeps a partial report if the run dies; rewrite as utf8 at the end
# (Tee-Object only writes utf16) so reports diff and grep cleanly across machines
(Get-Content $out) | Out-File -FilePath $out -Encoding utf8
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env bash
# Run the downloader benchmark suite and save a readable report for comparison.
# Offline synthetic + fault runs by default; --live also hits public test CDNs
# (needs network + ffprobe on PATH).
# ./scripts/bench_suite.sh # offline suite
# ./scripts/bench_suite.sh --live # + live/network tests
# Output: scripts/bench-results/<host>_<utc-timestamp>.txt
set -uo pipefail
cd "$(dirname "$0")/.."
OUT_DIR="scripts/bench-results"
mkdir -p "$OUT_DIR"
STAMP="$(date -u +%Y%m%d-%H%M%S)"
OUT="$OUT_DIR/$(hostname)_${STAMP}.txt"
# tee everything (stdout+stderr) to the report so tables land in the file too
exec > >(tee "$OUT") 2>&1
echo "# unshackle downloader benchmark"
echo "host: $(hostname)"
echo "date: $(date -u '+%Y-%m-%d %H:%M:%S') UTC"
echo "git: $(git rev-parse --abbrev-ref HEAD) @ $(git rev-parse --short HEAD)"
echo "cpu: $(grep -m1 'model name' /proc/cpuinfo | cut -d: -f2- | sed 's/^ *//') ($(nproc) threads)"
echo "mem: $(free -h --si 2>/dev/null | awk '/^Mem:/{print $2}')"
echo "os: $(uname -sr)"
echo "python: $(uv run python -V 2>&1)"
echo "mode: ${1:-offline}"
run() { echo; echo "==================== $* ===================="; uv run python "$@"; }
# link baseline: establishes the max line speed so downloader numbers can be read
# against it (e.g. "2Gbe -> ~1900 Mbps expected ceiling"). Uses whatever CLI exists.
# negotiated link speed per NIC (from sysfs); shows the physical ceiling, e.g. 2500 = 2.5GbE
nic_link_speed() {
echo; echo "==================== nic link speed ===================="
local found=0
for d in /sys/class/net/*; do
local n state spd
n=$(basename "$d")
[ "$n" = "lo" ] && continue
state=$(cat "$d/operstate" 2>/dev/null)
[ "$state" = "up" ] || continue
spd=$(cat "$d/speed" 2>/dev/null)
echo "$n: ${spd:-?} Mbps"
found=1
done
[ "$found" = 1 ] || echo "no up interfaces with readable speed (virtual/WSL/wifi report -1)"
}
nic_link_speed
speedtest_baseline() {
echo; echo "==================== speedtest baseline ===================="
if command -v speedtest >/dev/null 2>&1; then
speedtest --accept-license --accept-gdpr 2>&1 || echo "speedtest failed"
elif command -v npx >/dev/null 2>&1; then
# Netflix fast.com; download + upload + latency + server, clean when piped
npx --yes fast-cli --upload --verbose 2>&1 || echo "npx fast-cli failed"
elif command -v speedtest-cli >/dev/null 2>&1; then
speedtest-cli --simple 2>&1 || echo "speedtest-cli failed"
else
echo "no speedtest CLI found (install Ookla 'speedtest', have npx, or 'pipx install speedtest-cli') - skipping"
fi
}
speedtest_baseline
# 1. Synthetic downloader benchmark (offline, deterministic)
run scripts/bench_downloader.py --segments 64 --workers 1,2,4,8,16 --runs 3
run scripts/bench_downloader.py --segments 64 --workers 1,2,4,8,16 --adaptive
run scripts/bench_downloader.py --workers 4,8,16 --no-read1
# 2. Fault paths (fast timeouts; --fault-stall is EXPECTED to fail + exit non-zero)
run scripts/bench_downloader.py --fault-503 2 --fast-timeouts --segments 8
run scripts/bench_downloader.py --fault-reset 2 --fast-timeouts --segments 8
run scripts/bench_downloader.py --fault-stall 1 --fast-timeouts --segments 8 || true
# 2b. Fault-injection reliability + request amplification (fault_server.py; every run is
# byte-integrity verified, so a CORRUPTION line here is a real finalize-wrong-bytes bug).
# loopback is the zero-fault python-overhead ceiling; the rest exercise retry/hedge/tail paths.
run scripts/bench_downloader.py --fault-profile loopback --segments 64 --workers 8,16 --runs 3
run scripts/bench_downloader.py --fault-profile rate-limit --segments 32 --workers 8
run scripts/bench_downloader.py --fault-profile flaky-first --segments 16 --workers 8 --fast-timeouts
run scripts/bench_downloader.py --fault-profile reset --segments 16 --workers 8 --fast-timeouts
run scripts/bench_downloader.py --fault-profile stall --segments 16 --workers 8 --fast-timeouts
run scripts/bench_downloader.py --fault-profile tail-slow --segments 32 --workers 8 --adaptive --fast-timeouts
# 3. Multiprocess path (>=24 segments engages spawned children; strided chunk split).
# big batch: at small sizes the fixed spawn cost drowns the throughput signal
run scripts/bench_downloader.py --segments 128 --workers 8 --procs 2
run scripts/bench_downloader.py --segments 128 --workers 8 --procs 4
run scripts/bench_downloader.py --fault-stall 1 --fast-timeouts --segments 32 --workers 8 --procs 2 || true
# 4. Hedge + slow tail (last segments crawl; hedging and striding bound the tail)
run scripts/bench_downloader.py --fault-tail-slow 4 --fast-timeouts --segments 32 --workers 8
run scripts/bench_downloader.py --fault-tail-slow 4 --fast-timeouts --segments 32 --workers 8 --procs 4
run scripts/bench_downloader.py --fault-tail-slow 2 --fast-timeouts --adaptive --segments 16 --workers 8
# 5. rnet session path (loopback through the TLS-fingerprint client's own read loop)
run scripts/bench_downloader.py --segments 32 --workers 8 --impersonate Chrome131 || true
# 6. Leak regression tests (locked handles / leaked workers; unlink checks bite on Windows)
echo; echo "==================== pytest tests/test_downloader_leaks.py ===================="
uv run pytest tests/test_downloader_leaks.py -q || echo "(pytest failed or missing - run 'uv sync' to install dev deps)"
# 6b. Low-core variant: pin to two cores to emulate a small box, so the python-overhead
# ceiling and one fault profile can be read against the full-core numbers above. taskset is
# util-linux (Linux only); skipped cleanly elsewhere.
if command -v taskset >/dev/null 2>&1 && taskset -c 0-1 true 2>/dev/null; then
echo; echo "==================== low-core variant (taskset -c 0-1, 2 cores) ===================="
run_lowcore() { echo; echo "-------------------- taskset -c 0-1 $* --------------------"; taskset -c 0-1 uv run python "$@"; }
run_lowcore scripts/bench_downloader.py --fault-profile loopback --segments 64 --workers 8,16 --runs 3
run_lowcore scripts/bench_downloader.py --fault-profile rate-limit --segments 32 --workers 8
else
echo; echo "==================== low-core variant skipped (taskset missing or CPUs 0-1 not schedulable) ===================="
fi
# 7. Live network tests (opt-in)
if [[ "${1:-}" == "--live" ]]; then
run scripts/live_manifest_test.py --workers 16 --track largest
run scripts/live_segmentbase_ab.py --track largest
run scripts/bench_downloader.py --urls-file scripts/bench-urls/apple_sustained_4x585mb.txt --impersonate Chrome131
run scripts/bench_downloader.py --urls-file scripts/bench-urls/akamai_4k_segments.txt --impersonate Chrome131
fi
echo; echo "report saved: $OUT"
+435
View File
@@ -0,0 +1,435 @@
#!/usr/bin/env python3
"""
Localhost fault-injection HTTP server for downloader reliability benchmarking.
Serves deterministic pseudo-random segment payloads (seeded per URL path, so the
bytes are reproducible and any output file can be hashed against them to prove
integrity) and applies a configurable *fault profile* to those responses. Stall
and reset faults are decided deterministically from a printed seed keyed on
(path, attempt), so a retry can recover instead of failing forever; rate-limit
windows are wall-clock relative to run start, so their timing is not seed-bound.
Fault profiles:
stall sleep N seconds mid-body on X% of (path, attempt)s
reset RST the connection mid-body on X% of (path, attempt)s
rate-limit reply 429 + Retry-After during recurring throttle windows
(window_open seconds serving / window_closed seconds throttled)
tail-slow heavily throttle the last K segments' bodies
throttle-cut throttle every body and close it (FIN) after N seconds or N bytes
flaky-first fail attempt 1 per path (503), succeed on retry
deny reply 403 to every request (a permanent error no retry can fix)
loopback no faults; payloads served from memory (overhead ceiling)
Range requests are honored (206 + Content-Range) so byte-range / hedge / tail-boost
download paths exercise correctly, and an unsatisfiable resume gets a 416.
Standalone:
uv run python scripts/fault_server.py --profile rate-limit --segments 32
uv run python scripts/fault_server.py --profile stall --stall-secs 4 --port 8080
uv run python scripts/fault_server.py --profile throttle-cut --segments 1 --seg-size 71303168
uv run python scripts/fault_server.py --profile deny --deny-after 1
Importable: build a ``FaultServer``, serve it on a thread, and hash output against
``segment_payload(path, size)``.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import random
import socket
import struct
import threading
import time
from dataclasses import asdict, dataclass
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Optional
MIB = 1024 * 1024
DEFAULT_SEED = 1729
def segment_payload(path: str, size: int) -> bytes:
"""Deterministic pseudo-random body for ``path``.
Pure and seed-stable: the bench regenerates this to byte-compare every output
file, so it must never depend on the fault seed, request order, or attempt.
"""
seed = int.from_bytes(hashlib.sha256(path.encode("utf-8")).digest()[:8], "big")
return random.Random(seed).randbytes(size)
@dataclass
class FaultProfile:
"""A named set of deterministic response faults. Presets live in ``PROFILES``."""
name: str
stall_pct: float = 0.0
stall_secs: float = 3.0
reset_pct: float = 0.0
rate_limit: bool = False
retry_after: int = 1
window_open: float = 5.0
window_closed: float = 5.0
body_rate_kib: int = 0
tail_slow: int = 0
tail_rate_kib: int = 256
flaky_first: bool = False
flaky_status: int = 503
cut_secs: float = 0.0
cut_bytes: int = 0
deny: bool = False
deny_status: int = 403
deny_after: int = 0
PROFILES: dict[str, FaultProfile] = {
"loopback": FaultProfile("loopback"),
"stall": FaultProfile("stall", stall_pct=25.0, stall_secs=3.0),
"reset": FaultProfile("reset", reset_pct=25.0),
"rate-limit": FaultProfile(
"rate-limit", rate_limit=True, retry_after=1, window_open=1.0, window_closed=1.0, body_rate_kib=2048
),
"tail-slow": FaultProfile("tail-slow", tail_slow=4, tail_rate_kib=256),
"flaky-first": FaultProfile("flaky-first", flaky_first=True, flaky_status=503),
"throttle-cut": FaultProfile("throttle-cut", body_rate_kib=480, cut_secs=6.5, cut_bytes=5 * MIB // 2),
"deny": FaultProfile("deny", deny=True),
}
class FaultServer(ThreadingHTTPServer):
"""Threaded loopback server serving seeded payloads under a ``FaultProfile``.
Counters (total requests, per-status, per-path attempts) are the request-amplification
signal the bench reads: a retry/hedge storm against a throttled host shows up as
requests >> segment count. ``reset_counters`` re-baselines between benchmark runs.
"""
allow_reuse_address = True
daemon_threads = True
request_queue_size = 128
def __init__(
self,
profile: FaultProfile,
seg_size: int,
total_segments: int,
seed: int = DEFAULT_SEED,
host: str = "127.0.0.1",
port: int = 0,
) -> None:
self.profile = profile
self.seg_size = seg_size
self.total_segments = total_segments
self.seed = seed
self.stall_event = threading.Event()
self._lock = threading.Lock()
self._request_count = 0
self._status_counts: dict[int, int] = {}
self._attempts: dict[str, int] = {}
self._window_origin = time.monotonic()
self._payloads: dict[str, bytes] = {
f"/seg/{i}": segment_payload(f"/seg/{i}", seg_size) for i in range(total_segments)
}
super().__init__((host, port), FaultHandler)
def handle_error(self, request: Any, client_address: Any) -> None:
pass
def payload(self, path: str) -> bytes:
cached = self._payloads.get(path)
if cached is not None:
return cached
with self._lock:
body = self._payloads.get(path)
if body is None:
body = segment_payload(path, self.seg_size)
self._payloads[path] = body
return body
def note_request(self) -> None:
with self._lock:
self._request_count += 1
def note_status(self, code: int) -> None:
with self._lock:
self._status_counts[code] = self._status_counts.get(code, 0) + 1
def note_attempt(self, path: str) -> int:
with self._lock:
n = self._attempts.get(path, 0) + 1
self._attempts[path] = n
return n
def in_throttle_window(self) -> bool:
p = self.profile
period = p.window_open + p.window_closed
if period <= 0:
return False
phase = (time.monotonic() - self._window_origin) % period
return phase >= p.window_open
def decides(self, kind: str, path: str, attempt: int, pct: float) -> bool:
"""Deterministic per-(path, attempt) fault gate: fires for ``pct`` percent of them."""
if pct <= 0:
return False
digest = hashlib.sha256(f"{self.seed}:{kind}:{path}:{attempt}".encode("utf-8")).digest()
return (int.from_bytes(digest[:4], "big") / 0xFFFFFFFF) * 100.0 < pct
def reset_counters(self) -> None:
with self._lock:
self._request_count = 0
self._status_counts.clear()
self._attempts.clear()
self._window_origin = time.monotonic()
def stats(self) -> dict[str, Any]:
with self._lock:
max_attempts = max(self._attempts.values(), default=0)
return {
"requests": self._request_count,
"status_counts": dict(sorted(self._status_counts.items())),
"max_attempts": max_attempts,
}
class FaultHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *_: Any) -> None:
pass
def _parse_range(self, total: int) -> Optional[tuple[int, int]]:
header = self.headers.get("Range")
if not header or not header.startswith("bytes="):
return None
start_s, _, end_s = header[len("bytes=") :].partition("-")
if not start_s:
return max(0, total - int(end_s)), total - 1
start = int(start_s)
end = int(end_s) if end_s else total - 1
if start > end:
return total, total - 1
return start, min(end, total - 1)
def do_GET(self) -> None:
server: FaultServer = self.server # type: ignore[assignment]
server.note_request()
if not self.path.startswith("/seg/"):
self.send_error(404)
return
try:
idx = int(self.path.rsplit("/", 1)[-1])
except ValueError:
self.send_error(404)
return
attempt = server.note_attempt(self.path)
prof = server.profile
if prof.deny and attempt > prof.deny_after:
self._send_status(prof.deny_status)
return
if prof.flaky_first and attempt == 1:
self._send_status(prof.flaky_status)
return
if prof.rate_limit and server.in_throttle_window():
self._send_429(prof.retry_after)
return
rate = prof.body_rate_kib
if prof.tail_slow and idx >= server.total_segments - prof.tail_slow:
rate = prof.tail_rate_kib
stall = server.decides("stall", self.path, attempt, prof.stall_pct)
reset = server.decides("reset", self.path, attempt, prof.reset_pct)
self._serve(
server.payload(self.path),
stall=stall,
reset=reset,
rate_kib=rate,
cut_secs=prof.cut_secs,
cut_bytes=prof.cut_bytes,
)
def _send_status(self, code: int) -> None:
server: FaultServer = self.server # type: ignore[assignment]
server.note_status(code)
self.send_response(code)
self.send_header("Content-Length", "0")
self.end_headers()
def _send_429(self, retry_after: int) -> None:
server: FaultServer = self.server # type: ignore[assignment]
server.note_status(429)
self.send_response(429)
self.send_header("Retry-After", str(retry_after))
self.send_header("Content-Length", "0")
self.end_headers()
def _serve(
self,
full: bytes,
stall: bool = False,
reset: bool = False,
rate_kib: int = 0,
cut_secs: float = 0.0,
cut_bytes: int = 0,
) -> None:
server: FaultServer = self.server # type: ignore[assignment]
rng = self._parse_range(len(full))
if rng is not None and rng[0] >= len(full):
server.note_status(416)
self.send_response(416)
self.send_header("Content-Range", f"bytes */{len(full)}")
self.send_header("Content-Length", "0")
self.end_headers()
return
if rng is not None:
start, end = rng
body = full[start : end + 1]
server.note_status(206)
self.send_response(206)
self.send_header("Content-Range", f"bytes {start}-{end}/{len(full)}")
else:
body = full
server.note_status(200)
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Type", "application/octet-stream")
self.end_headers()
try:
if reset:
half = max(1, len(body) // 2)
self.wfile.write(body[:half])
self.wfile.flush()
sock = self.connection
sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
sock.close()
self.close_connection = True
elif stall:
half = max(1, len(body) // 2)
self.wfile.write(body[:half])
self.wfile.flush()
server.stall_event.wait(server.profile.stall_secs)
self.wfile.write(body[half:])
self.wfile.flush()
else:
self._write_body(body, rate_kib, cut_secs, cut_bytes)
except (BrokenPipeError, ConnectionError, OSError):
self.close_connection = True
def _cut(self) -> None:
"""End the body early with a clean half-close.
FIN rather than RST: the client reads fewer bytes than Content-Length promised and
raises IncompleteRead, which is the resumable short read a throttling CDN produces.
An RST (see the reset fault) is a different error class on the client side.
"""
try:
self.wfile.flush()
self.connection.shutdown(socket.SHUT_WR)
except OSError:
pass
self.close_connection = True
def _write_body(self, body: bytes, rate_kib: int, cut_secs: float = 0.0, cut_bytes: int = 0) -> None:
if rate_kib <= 0 and cut_secs <= 0 and cut_bytes <= 0:
self.wfile.write(body)
return
chunk = 64 * 1024
per_chunk = chunk / (rate_kib * 1024) if rate_kib > 0 else 0.0
deadline = time.monotonic() + cut_secs if cut_secs > 0 else None
sent = 0
for off in range(0, len(body), chunk):
size = min(chunk, len(body) - off)
if cut_bytes > 0:
size = min(size, cut_bytes - sent)
self.wfile.write(body[off : off + size])
self.wfile.flush()
sent += size
if cut_bytes > 0 and sent >= cut_bytes:
self._cut()
return
if deadline is not None and time.monotonic() >= deadline:
self._cut()
return
if per_chunk:
time.sleep(per_chunk)
def resolve_profile(name: str, overrides: Optional[dict[str, Any]] = None) -> FaultProfile:
"""Return a copy of the named preset with any non-None ``overrides`` applied."""
if name not in PROFILES:
raise KeyError(f"unknown profile {name!r}; choices: {', '.join(sorted(PROFILES))}")
base = asdict(PROFILES[name])
for key, value in (overrides or {}).items():
if value is not None and key in base:
base[key] = value
return FaultProfile(**base)
def _build_arg_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--port", type=int, default=0, help="Listen port (0 = auto).")
p.add_argument("--profile", choices=sorted(PROFILES), default="loopback", help="Fault profile to apply.")
p.add_argument("--segments", type=int, default=32, help="Number of /seg/i payloads to precompute.")
p.add_argument("--seg-size", type=int, default=2 * MIB, help="Bytes per segment payload.")
p.add_argument("--seed", type=int, default=DEFAULT_SEED, help="Fault RNG seed (printed for reproducibility).")
p.add_argument("--stall-pct", type=float, help="Override: %% of (path, attempt)s that stall.")
p.add_argument("--stall-secs", type=float, help="Override: seconds a stall holds.")
p.add_argument("--reset-pct", type=float, help="Override: %% of (path, attempt)s that RST.")
p.add_argument("--retry-after", type=int, help="Override: Retry-After seconds on a 429.")
p.add_argument("--window-open", type=float, help="Override: seconds serving before a throttle window.")
p.add_argument("--window-closed", type=float, help="Override: seconds replying 429 during a window.")
p.add_argument("--body-rate-kib", type=int, help="Override: throttle every body to this KiB/s (0 = off).")
p.add_argument("--tail-slow", type=int, help="Override: throttle the last K segments.")
p.add_argument("--tail-rate-kib", type=int, help="Override: tail-slow throttle rate (KiB/s).")
p.add_argument("--deny-after", type=int, help="Override: serve this many attempts per path before denying.")
p.add_argument("--cut-secs", type=float, help="Override: close each body (FIN) after this long (0 = never).")
p.add_argument("--cut-bytes", type=int, help="Override: close each body (FIN) after this many bytes (0 = never).")
return p
def main() -> None:
args = _build_arg_parser().parse_args()
overrides = {
"stall_pct": args.stall_pct,
"stall_secs": args.stall_secs,
"reset_pct": args.reset_pct,
"retry_after": args.retry_after,
"window_open": args.window_open,
"window_closed": args.window_closed,
"body_rate_kib": args.body_rate_kib,
"tail_slow": args.tail_slow,
"tail_rate_kib": args.tail_rate_kib,
"cut_secs": args.cut_secs,
"cut_bytes": args.cut_bytes,
"deny_after": args.deny_after,
}
profile = resolve_profile(args.profile, overrides)
server = FaultServer(profile, args.seg_size, args.segments, args.seed, port=args.port)
host, port = server.server_address[0], server.server_address[1]
config = {
"listen": f"http://{host}:{port}",
"seed": args.seed,
"segments": args.segments,
"seg_size": args.seg_size,
"base_url": f"http://{host}:{port}/seg/{{i}}",
"profile": asdict(profile),
}
print(json.dumps(config, indent=2), flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.stall_event.set()
server.shutdown()
if __name__ == "__main__":
main()
+192
View File
@@ -0,0 +1,192 @@
"""Live full-flow test over public DASH/HLS/ISM manifests on several CDNs.
Drives the real pipeline for each stream: <PARSER>.from_url().to_tracks() picks a
video track, then the parser's own download_track() runs the unified downloader
with the adaptive worker controller enabled (adaptive_workers=True, max_workers=16).
The controller logs its worker-target changes to a JSON-lines debug log; this script
reads them back and prints the scaling sequence per stream, so you can see whether the
downloader ramps workers up against each CDN or finishes before the controller acts.
STREAMS carries a public 4K/HDR/Dolby-Vision tier (labels uhd-hevc, dv-atmos, hevc-hls,
h265-cmaf) for exercising large high-bitrate tracks; filter it with --only uhd / dv / hevc / h265.
Throwaway-ish operational tool: it makes real network requests to public test assets.
Run: uv run python scripts/live_manifest_test.py [--workers N] [--track smallest|largest]
"""
from __future__ import annotations
import json
import shutil
import sys
import time
from pathlib import Path
from tempfile import mkdtemp
from typing import Any, Optional
import click
from requests import Session
from unshackle.core.manifests import DASH, HLS, ISM
from unshackle.core.tracks.track import DownloadContext
from unshackle.core.utilities import close_debug_logger, init_debug_logger
STREAMS: list[tuple[str, Any, str, str]] = [
("HLS", HLS, "mux", "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8"),
(
"HLS",
HLS,
"unified",
"https://demo.unified-streaming.com/k8s/features/stable/video/tears-of-steel/tears-of-steel.ism/.m3u8",
),
("DASH", DASH, "akamai", "https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps.mpd"),
(
"DASH",
DASH,
"unified",
"https://demo.unified-streaming.com/k8s/features/stable/video/tears-of-steel/tears-of-steel.ism/.mpd",
),
("DASH", DASH, "dashif", "https://livesim2.dashif.org/vod/testpic_2s/Manifest.mpd"),
(
"ISM",
ISM,
"unified",
"https://demo.unified-streaming.com/k8s/features/stable/video/tears-of-steel/tears-of-steel.ism/Manifest",
),
(
"HLS",
HLS,
"apple",
"https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8",
),
("HLS", HLS, "gcs", "https://storage.googleapis.com/shaka-demo-assets/angel-one-hls/hls.m3u8"),
("DASH", DASH, "gcs", "https://storage.googleapis.com/shaka-demo-assets/angel-one/dash.mpd"),
("DASH", DASH, "axinom", "https://media.axprod.net/TestVectors/v7-Clear/Manifest_1080p.mpd"),
(
"ISM",
ISM,
"dtaps",
"https://playready.directtaps.net/smoothstreaming/SSWSS720H264/SuperSpeedway_720.ism/Manifest",
),
("DASH", DASH, "uhd-hevc", "https://dash.akamaized.net/dash264/TestCasesUHD/2b/11/MultiRate.mpd"),
("HLS", HLS, "dv-atmos", "https://devstreaming-cdn.apple.com/videos/streaming/examples/adv_dv_atmos/main.m3u8"),
(
"HLS",
HLS,
"hevc-hls",
"https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_adv_example_hevc/master.m3u8",
),
("DASH", DASH, "h265-cmaf", "https://media.axprod.net/TestVectors/H265/clear_cmaf_1080p_h265/manifest.mpd"),
]
class Counter:
"""Collects downloader progress events in place of the rich progress callable."""
def __init__(self) -> None:
self.files = 0
def __call__(self, **ev: Any) -> None:
if "file_downloaded" in ev:
self.files += 1
def pick_track(tracks: object, which: str) -> Optional[Any]:
vids = list(getattr(tracks, "videos", []))
if not vids:
auds = list(getattr(tracks, "audio", []))
return auds[0] if auds else None
key = lambda t: getattr(t, "bitrate", 0) or 0 # noqa: E731
return min(vids, key=key) if which == "smallest" else max(vids, key=key)
def read_new_transitions(log_path: Path, start_line: int) -> tuple[list[str], int]:
"""Return (worker-target transitions since start_line, new line count)."""
if not log_path.exists():
return [], start_line
lines = log_path.read_text(encoding="utf-8").splitlines()
moves = []
for raw in lines[start_line:]:
try:
rec = json.loads(raw)
except ValueError:
continue
if rec.get("operation") == "adaptive_workers":
ctx = rec.get("context", {})
moves.append(f"{ctx.get('old')}->{ctx.get('new')}({ctx.get('reason')})")
return moves, len(lines)
def run_one(label: str, parser: Any, cdn: str, url: str, workers: int, which: str, log_path: Path, line0: int) -> str:
session = Session()
try:
tracks = parser.from_url(url=url, session=session).to_tracks(language="en")
except Exception as e: # noqa: BLE001
return f"{label:5} {cdn:8} PARSE ERROR {type(e).__name__}: {e}"
track = pick_track(tracks, which)
if track is None:
return f"{label:5} {cdn:8} NO TRACK"
work = Path(mkdtemp(prefix="live_"))
save_path = work / "out.mp4"
counter = Counter()
extra = (
{"adaptive_workers": True} if "adaptive_workers" in getattr(DownloadContext, "__dataclass_fields__", {}) else {}
)
ctx = DownloadContext(
save_path=save_path,
save_dir=work / "segs",
progress=counter,
session=session,
proxy=None,
max_workers=workers,
**extra,
)
track.drm = None
t0 = time.time()
err = ""
try:
parser.download_track(track=track, ctx=ctx)
except Exception as e: # noqa: BLE001
err = f" ERROR {type(e).__name__}: {e}"
dt = time.time() - t0
size = save_path.stat().st_size if save_path.exists() else 0
mbps = (size / 1e6 / dt) if dt > 0 and size else 0.0
shutil.rmtree(work, ignore_errors=True)
moves, _ = read_new_transitions(log_path, line0)
scaling = " ".join(moves) if moves else "none (finished under controller tick)"
res = f"{getattr(track, 'width', '?')}x{getattr(track, 'height', '?')}"
return f"{label:5} {cdn:8} {dt:6.1f}s {size / 1e6:7.1f}MB {mbps:6.1f}MB/s [{res}] workers: {scaling}{err}"
@click.command()
@click.option("--workers", default=16, help="max workers (the adaptive ceiling)")
@click.option("--track", "which", type=click.Choice(["smallest", "largest"]), default="largest")
@click.option("--only", default="", help="substring filter on CDN/format labels (e.g. 'apple' or 'ISM')")
def main(workers: int, which: str, only: str) -> None:
HLS.get_drm = staticmethod(lambda *a, **k: None) # type: ignore[assignment]
log_path = Path(mkdtemp(prefix="live_dbg_")) / "debug.jsonl"
init_debug_logger(log_path=log_path, enabled=True)
print(f"debug log: {log_path}\ntrack: {which}, max_workers: {workers}\n")
rows = []
line0 = 0
try:
streams = [s for s in STREAMS if only.lower() in s[0].lower() or only.lower() in s[2].lower()]
for label, parser, cdn, url in streams:
_, line0 = read_new_transitions(log_path, line0)
row = run_one(label, parser, cdn, url, workers, which, log_path, line0)
print(row)
rows.append(row)
finally:
close_debug_logger()
ok = sum(1 for r in rows if "MB/s" in r and "ERROR" not in r and "NO TRACK" not in r)
ramped = sum(1 for r in rows if "->" in r)
print(f"\n{ok}/{len(rows)} streams downloaded; {ramped} showed live worker scaling")
sys.exit(0 if ok == len(rows) else 1)
if __name__ == "__main__":
main()
+137
View File
@@ -0,0 +1,137 @@
"""Live A/B test for SegmentBase (byte-range) DASH downloads.
Drives the real DASH pipeline against public SegmentBase test manifests and reports
wall time, size, throughput and output validity (ffprobe). On branches that have the
single-URL collapse (DASH.collapsible_single_url) it also reports whether the
collapse fired; on checkouts without it (e.g. dev) the same script runs the classic
per-segment + merge path, so running it from both checkouts gives an A/B comparison:
uv run python scripts/live_segmentbase_ab.py --track largest
/path/to/dev/.venv/bin/python scripts/live_segmentbase_ab.py --track largest
Throwaway-ish operational tool: it makes real network requests to public test assets.
"""
from __future__ import annotations
import shutil
import subprocess
import time
from pathlib import Path
from tempfile import mkdtemp
from typing import Any, Optional
import click
from requests import Session
from unshackle.core.manifests import DASH
from unshackle.core.tracks.track import DownloadContext
STREAMS: list[tuple[str, str]] = [
("netflix-1a", "https://dash.akamaized.net/dash264/TestCases/1a/netflix/exMPD_BIP_TC1.mpd"),
("sony-1a", "https://dash.akamaized.net/dash264/TestCases/1a/sony/SNE_DASH_SD_CASE1A_REVISED.mpd"),
]
guard_results: list[bool] = []
def install_guard_spy() -> bool:
"""Record collapse decisions when this checkout has the guard; no-op otherwise."""
orig = getattr(DASH, "collapsible_single_url", None)
if orig is None:
return False
def spy(is_subtitle: bool, segments: Any, init_len: Optional[int]) -> bool:
result = orig(is_subtitle, segments, init_len)
guard_results.append(result)
return result
DASH.collapsible_single_url = staticmethod(spy) # type: ignore[method-assign]
return True
def _major_brand(path: Path) -> str:
with open(path, "rb") as f:
head = f.read(12)
return head[8:12].decode("latin-1") if head[4:8] == b"ftyp" else ""
def ffprobe(path: Path) -> str:
if not path.exists() or not shutil.which("ffprobe"):
return "n/a"
r = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)],
capture_output=True,
text=True,
)
if r.stdout.strip():
return f"{float(r.stdout.strip()):.0f}s"
if _major_brand(path) == "senv":
return f"senv ok ({path.stat().st_size} B)"
return "INVALID"
def run_one(label: str, url: str, which: str, workers: int, has_guard: bool) -> str:
guard_results.clear()
session = Session()
try:
tracks = DASH.from_url(url=url, session=session).to_tracks(language="en")
except Exception as e: # noqa: BLE001
return f"{label:12} PARSE ERROR {type(e).__name__}: {e}"
vids = list(tracks.videos)
if not vids:
return f"{label:12} NO VIDEO TRACKS"
key = lambda t: t.bitrate or 0 # noqa: E731
track = min(vids, key=key) if which == "smallest" else max(vids, key=key)
work = Path(mkdtemp(prefix="segbase_ab_"))
save_path = work / "out.mp4"
extra = {"adaptive_workers": True} if "adaptive_workers" in DownloadContext.__dataclass_fields__ else {}
ctx = DownloadContext(
save_path=save_path,
save_dir=work / "segs",
progress=lambda **ev: None,
session=session,
proxy=None,
max_workers=workers,
**extra,
)
t0 = time.time()
err = ""
try:
DASH.download_track(track=track, ctx=ctx)
except Exception as e: # noqa: BLE001
err = f" ERROR {type(e).__name__}: {e}"
dt = time.time() - t0
size = save_path.stat().st_size if save_path.exists() else 0
mbps = (size / 1e6 / dt) if dt > 0 and size else 0.0
probe = ffprobe(save_path)
shutil.rmtree(work, ignore_errors=True)
if has_guard:
collapse = "yes" if guard_results and guard_results[0] else "no"
else:
collapse = "unsupported"
res = f"{getattr(track, 'width', '?')}x{getattr(track, 'height', '?')}"
return (
f"{label:12} {dt:6.1f}s {size / 1e6:8.1f}MB {mbps:6.1f}MB/s [{res}] "
f"collapse: {collapse:11} duration: {probe}{err}"
)
@click.command()
@click.option("--workers", default=16, show_default=True, help="max workers (adaptive cap where supported)")
@click.option("--track", "which", type=click.Choice(["smallest", "largest"]), default="smallest", show_default=True)
@click.option("--only", default="", help="substring filter on stream labels")
def main(workers: int, which: str, only: str) -> None:
has_guard = install_guard_spy()
print(f"track: {which}, max_workers: {workers}, collapse guard present: {has_guard}\n")
for label, url in STREAMS:
if only and only.lower() not in label.lower():
continue
print(run_one(label, url, which, workers, has_guard))
if __name__ == "__main__":
main()