fix(api): time the rate-limit window on the monotonic clock and make three flaky tests deterministic

This commit is contained in:
imSp4rky
2026-12-02 18:41:23 -07:00
parent e4940df438
commit d23324e27b
3 changed files with 14 additions and 5 deletions
+10 -2
View File
@@ -4,6 +4,7 @@ run that never failed, and the second run fetches and decrypts only what the fir
from __future__ import annotations from __future__ import annotations
import importlib import importlib
import threading
from collections import Counter from collections import Counter
from functools import partial from functools import partial
from pathlib import Path from pathlib import Path
@@ -134,10 +135,15 @@ def part(parser, index: int) -> str:
def fail_once(server, parser, make, ctx) -> None: def fail_once(server, parser, make, ctx) -> None:
"""Run a download that fails on segment FAIL_AT.""" """Run a download that fails on segment FAIL_AT, and wait for the pool workers its failure leaves running."""
body = server.routes.pop(part(parser, FAIL_AT)) body = server.routes.pop(part(parser, FAIL_AT))
before = set(threading.enumerate())
with pytest.raises(requests.HTTPError): with pytest.raises(requests.HTTPError):
parser.download_track(make(), ctx) parser.download_track(make(), ctx)
leaked = [thread for thread in set(threading.enumerate()) - before if thread.name.startswith("ThreadPoolExecutor")]
for thread in leaked:
thread.join(10)
assert not any(thread.is_alive() for thread in leaked)
server.routes[part(parser, FAIL_AT)] = body server.routes[part(parser, FAIL_AT)] = body
DOWNLOAD_CANCELLED.clear() DOWNLOAD_CANCELLED.clear()
@@ -258,7 +264,9 @@ def test_kept_decrypted_segments_past_the_checkpoint_are_merged_without_a_reques
ctx = context(tmp_path, "resumed.mp4", KEY_A) ctx = context(tmp_path, "resumed.mp4", KEY_A)
probes = Counter({path: hits - 1 for path, hits in routes.hits.items()}) probes = Counter({path: hits - 1 for path, hits in routes.hits.items()})
decrypted.clear()
fail_once(server, DASH, make, ctx) fail_once(server, DASH, make, ctx)
first = segment_indices(decrypted)
# segment 4 finished before the failure: its decrypt replaced it, but a lock kept the downloaded file # segment 4 finished before the failure: its decrypt replaced it, but a lock kept the downloaded file
raw = routes[part(DASH, 4)] raw = routes[part(DASH, 4)]
(ctx.save_dir / "4.clear").write_bytes(b"[aa]" + raw) (ctx.save_dir / "4.clear").write_bytes(b"[aa]" + raw)
@@ -274,7 +282,7 @@ def test_kept_decrypted_segments_past_the_checkpoint_are_merged_without_a_reques
assert {path for path, hits in routes.hits.items() if path.startswith("/part") and hits > probes[path]} == { assert {path for path, hits in routes.hits.items() if path.startswith("/part") and hits > probes[path]} == {
part(DASH, FAIL_AT) part(DASH, FAIL_AT)
} }
assert [name for name in decrypted if name[0].isdigit()] == ["3.mp4"] assert sorted(first + segment_indices(decrypted)) == list(range(FAIL_AT + 1))
def test_a_rolling_output_crosses_the_run_boundary_in_the_stash(server, routes, tmp_path, monkeypatch, decrypted): def test_a_rolling_output_crosses_the_run_boundary_in_the_stash(server, routes, tmp_path, monkeypatch, decrypted):
@@ -239,6 +239,7 @@ def test_a_remote_session_runs_end_to_end_over_http(
) -> None: ) -> None:
"""A client that does not open the channel, or whose upgrade is refused or fails, polls with the same replies.""" """A client that does not open the channel, or whose upgrade is refused or fails, polls with the same replies."""
caplog.set_level(logging.DEBUG) caplog.set_level(logging.DEBUG)
monkeypatch.setattr(session_store.SessionStore, "_expired", lambda self, entry: False)
if channel == "none": if channel == "none":
monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False) monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False)
if channel == "failed": if channel == "failed":
+3 -3
View File
@@ -77,7 +77,7 @@ class KeyStats:
rejected: int = 0 rejected: int = 0
bytes_out: int = 0 bytes_out: int = 0
last_seen: float = 0.0 last_seen: float = 0.0
window_start: float = 0.0 window_start: float = -RATE_LIMIT_WINDOW
window_used: int = 0 window_used: int = 0
@@ -121,7 +121,7 @@ class ServerStats:
if limit is None: if limit is None:
return None return None
entry = self.key_stats(key) entry = self.key_stats(key)
now = time.time() now = time.monotonic()
if now - entry.window_start >= RATE_LIMIT_WINDOW: if now - entry.window_start >= RATE_LIMIT_WINDOW:
entry.window_start = now entry.window_start = now
entry.window_used = 0 entry.window_used = 0
@@ -139,7 +139,7 @@ class ServerStats:
return { return {
"X-RateLimit-Limit": str(limit), "X-RateLimit-Limit": str(limit),
"X-RateLimit-Remaining": str(max(0, limit - entry.window_used)), "X-RateLimit-Remaining": str(max(0, limit - entry.window_used)),
"X-RateLimit-Reset": str(max(0, int(entry.window_start + RATE_LIMIT_WINDOW - time.time()))), "X-RateLimit-Reset": str(max(0, int(entry.window_start + RATE_LIMIT_WINDOW - time.monotonic()))),
} }
def to_dict(self) -> dict[str, Any]: def to_dict(self) -> dict[str, Any]: