Spaces:
Running on Zero
Running on Zero
fix: make HF analytics writes durable
Browse files- analytics_writer.py +109 -0
- app.py +11 -13
- tests-unit/test_analytics_writer.py +89 -0
analytics_writer.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
import traceback
|
| 7 |
+
from concurrent.futures import Future, ThreadPoolExecutor
|
| 8 |
+
from typing import Any, Callable, Mapping
|
| 9 |
+
from urllib import error as urllib_error
|
| 10 |
+
from urllib import request as urllib_request
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
_DEFAULT_TIMEOUT_SECONDS = float(os.getenv("ANALYTICS_WRITE_TIMEOUT_SECONDS", "10"))
|
| 14 |
+
_DEFAULT_RETRIES = max(1, int(os.getenv("ANALYTICS_WRITE_RETRIES", "3")))
|
| 15 |
+
_DEFAULT_BACKOFF_SECONDS = max(
|
| 16 |
+
0.0, float(os.getenv("ANALYTICS_WRITE_BACKOFF_SECONDS", "0.5"))
|
| 17 |
+
)
|
| 18 |
+
_RETRYABLE_HTTP_CODES = frozenset({408, 425, 429})
|
| 19 |
+
|
| 20 |
+
# Unlike the old daemon threads, executor workers are joined during normal
|
| 21 |
+
# interpreter shutdown. This prevents a completed generation from losing its
|
| 22 |
+
# telemetry simply because the Space process is restarting.
|
| 23 |
+
_EXECUTOR = ThreadPoolExecutor(max_workers=4, thread_name_prefix="analytics-writer")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _error_body(exc: urllib_error.HTTPError) -> str:
|
| 27 |
+
try:
|
| 28 |
+
body = exc.read(1024).decode("utf-8", "replace").strip()
|
| 29 |
+
except Exception:
|
| 30 |
+
body = ""
|
| 31 |
+
return body or "<empty response body>"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _is_retryable_http_status(status: int) -> bool:
|
| 35 |
+
return status in _RETRYABLE_HTTP_CODES or 500 <= status <= 599
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def post_json(
|
| 39 |
+
url: str,
|
| 40 |
+
payload: Mapping[str, Any],
|
| 41 |
+
headers: Mapping[str, str],
|
| 42 |
+
*,
|
| 43 |
+
timeout: float | None = None,
|
| 44 |
+
retries: int | None = None,
|
| 45 |
+
) -> bool:
|
| 46 |
+
"""POST JSON with bounded retry and observable HTTP failures.
|
| 47 |
+
|
| 48 |
+
Returns True only after a 2xx response. Invalid payload/auth/schema errors
|
| 49 |
+
are logged once and returned as False; transient transport/server failures
|
| 50 |
+
are retried with bounded exponential backoff.
|
| 51 |
+
"""
|
| 52 |
+
req = urllib_request.Request(
|
| 53 |
+
url,
|
| 54 |
+
data=json.dumps(payload).encode("utf-8"),
|
| 55 |
+
headers={"Content-Type": "application/json", **dict(headers)},
|
| 56 |
+
method="POST",
|
| 57 |
+
)
|
| 58 |
+
request_timeout = _DEFAULT_TIMEOUT_SECONDS if timeout is None else timeout
|
| 59 |
+
attempts = _DEFAULT_RETRIES if retries is None else max(1, int(retries))
|
| 60 |
+
|
| 61 |
+
for attempt in range(1, attempts + 1):
|
| 62 |
+
retryable = False
|
| 63 |
+
try:
|
| 64 |
+
with urllib_request.urlopen(req, timeout=request_timeout) as response:
|
| 65 |
+
status = getattr(response, "status", None)
|
| 66 |
+
if status is None:
|
| 67 |
+
status = response.getcode()
|
| 68 |
+
if status is None or 200 <= status < 300:
|
| 69 |
+
return True
|
| 70 |
+
retryable = _is_retryable_http_status(int(status))
|
| 71 |
+
print(
|
| 72 |
+
f"[analytics] remote write failed "
|
| 73 |
+
f"(attempt {attempt}/{attempts}, HTTP {status})"
|
| 74 |
+
)
|
| 75 |
+
except urllib_error.HTTPError as exc:
|
| 76 |
+
retryable = _is_retryable_http_status(exc.code)
|
| 77 |
+
print(
|
| 78 |
+
f"[analytics] remote write failed "
|
| 79 |
+
f"(attempt {attempt}/{attempts}, HTTP {exc.code}): {_error_body(exc)}"
|
| 80 |
+
)
|
| 81 |
+
except (urllib_error.URLError, TimeoutError, OSError) as exc:
|
| 82 |
+
retryable = True
|
| 83 |
+
print(
|
| 84 |
+
f"[analytics] remote write failed "
|
| 85 |
+
f"(attempt {attempt}/{attempts}, transport): {exc}"
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
if not retryable or attempt >= attempts:
|
| 89 |
+
return False
|
| 90 |
+
delay = _DEFAULT_BACKOFF_SECONDS * (2 ** (attempt - 1))
|
| 91 |
+
if delay:
|
| 92 |
+
time.sleep(delay)
|
| 93 |
+
|
| 94 |
+
return False
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _run_background_work(
|
| 98 |
+
fn: Callable[..., Any], args: tuple[Any, ...], kwargs: dict[str, Any]
|
| 99 |
+
) -> None:
|
| 100 |
+
try:
|
| 101 |
+
fn(*args, **kwargs)
|
| 102 |
+
except Exception as exc: # pragma: no cover - exercised via log assertion
|
| 103 |
+
print(f"[analytics] background worker failed ({fn.__name__}): {exc}")
|
| 104 |
+
traceback.print_exc()
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def queue_background_work(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Future:
|
| 108 |
+
"""Run analytics work off the UI path without daemon-thread loss."""
|
| 109 |
+
return _EXECUTOR.submit(_run_background_work, fn, args, kwargs)
|
app.py
CHANGED
|
@@ -31,6 +31,10 @@ from huggingface_hub import hf_hub_download
|
|
| 31 |
from PIL import Image
|
| 32 |
import kornia.color # For RGB→HSV conversion in Stable Cascade filter
|
| 33 |
from runtime_config import get_analytics_product
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
from qr_fit import PAYLOAD_TOO_LONG_ERROR_CLASS, auto_fit_qr_dimensions
|
| 35 |
from hf_dashboard import (
|
| 36 |
DashboardError,
|
|
@@ -965,28 +969,21 @@ def _format_exception_message(exc: Exception) -> str:
|
|
| 965 |
|
| 966 |
|
| 967 |
def _queue_background_work(fn, *args, **kwargs) -> None:
|
| 968 |
-
|
| 969 |
-
thread.start()
|
| 970 |
|
| 971 |
|
| 972 |
def _post_json(
|
| 973 |
url: str, payload: Mapping[str, Any], headers: Mapping[str, str]
|
| 974 |
) -> None:
|
| 975 |
-
|
| 976 |
-
url,
|
| 977 |
-
data=json.dumps(payload).encode("utf-8"),
|
| 978 |
-
headers={"Content-Type": "application/json", **dict(headers)},
|
| 979 |
-
method="POST",
|
| 980 |
-
)
|
| 981 |
-
try:
|
| 982 |
-
with urllib_request.urlopen(req, timeout=10):
|
| 983 |
-
pass
|
| 984 |
-
except urllib_error.URLError as exc:
|
| 985 |
-
print(f"[analytics] remote write failed: {exc}")
|
| 986 |
|
| 987 |
|
| 988 |
def _write_supabase_row(table: str, row: Mapping[str, Any]) -> None:
|
| 989 |
if not (SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 990 |
return
|
| 991 |
_post_json(
|
| 992 |
f"{SUPABASE_URL}/rest/v1/{table}",
|
|
@@ -1001,6 +998,7 @@ def _write_supabase_row(table: str, row: Mapping[str, Any]) -> None:
|
|
| 1001 |
|
| 1002 |
def _capture_posthog_event(event: str, properties: Mapping[str, Any]) -> None:
|
| 1003 |
if not POSTHOG_API_KEY:
|
|
|
|
| 1004 |
return
|
| 1005 |
distinct_id = str(
|
| 1006 |
properties.get("anonymous_id")
|
|
|
|
| 31 |
from PIL import Image
|
| 32 |
import kornia.color # For RGB→HSV conversion in Stable Cascade filter
|
| 33 |
from runtime_config import get_analytics_product
|
| 34 |
+
from analytics_writer import (
|
| 35 |
+
post_json as _post_json_impl,
|
| 36 |
+
queue_background_work as _queue_background_work_impl,
|
| 37 |
+
)
|
| 38 |
from qr_fit import PAYLOAD_TOO_LONG_ERROR_CLASS, auto_fit_qr_dimensions
|
| 39 |
from hf_dashboard import (
|
| 40 |
DashboardError,
|
|
|
|
| 969 |
|
| 970 |
|
| 971 |
def _queue_background_work(fn, *args, **kwargs) -> None:
|
| 972 |
+
_queue_background_work_impl(fn, *args, **kwargs)
|
|
|
|
| 973 |
|
| 974 |
|
| 975 |
def _post_json(
|
| 976 |
url: str, payload: Mapping[str, Any], headers: Mapping[str, str]
|
| 977 |
) -> None:
|
| 978 |
+
_post_json_impl(url, payload, headers)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 979 |
|
| 980 |
|
| 981 |
def _write_supabase_row(table: str, row: Mapping[str, Any]) -> None:
|
| 982 |
if not (SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY):
|
| 983 |
+
print(
|
| 984 |
+
"[analytics] Supabase write skipped: missing "
|
| 985 |
+
"SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY"
|
| 986 |
+
)
|
| 987 |
return
|
| 988 |
_post_json(
|
| 989 |
f"{SUPABASE_URL}/rest/v1/{table}",
|
|
|
|
| 998 |
|
| 999 |
def _capture_posthog_event(event: str, properties: Mapping[str, Any]) -> None:
|
| 1000 |
if not POSTHOG_API_KEY:
|
| 1001 |
+
print("[analytics] PostHog write skipped: missing POSTHOG_API_KEY")
|
| 1002 |
return
|
| 1003 |
distinct_id = str(
|
| 1004 |
properties.get("anonymous_id")
|
tests-unit/test_analytics_writer.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
from urllib.error import HTTPError
|
| 5 |
+
|
| 6 |
+
import analytics_writer
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class _Response:
|
| 10 |
+
status = 204
|
| 11 |
+
|
| 12 |
+
def __enter__(self):
|
| 13 |
+
return self
|
| 14 |
+
|
| 15 |
+
def __exit__(self, exc_type, exc, tb):
|
| 16 |
+
return False
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _http_error(code: int, body: bytes) -> HTTPError:
|
| 20 |
+
return HTTPError(
|
| 21 |
+
url="https://example.test/analytics",
|
| 22 |
+
code=code,
|
| 23 |
+
msg="remote failure",
|
| 24 |
+
hdrs=None,
|
| 25 |
+
fp=io.BytesIO(body),
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_post_json_retries_transient_http_errors_and_reports_status(monkeypatch, capsys):
|
| 30 |
+
calls = []
|
| 31 |
+
|
| 32 |
+
def fake_urlopen(request, timeout):
|
| 33 |
+
calls.append((request, timeout))
|
| 34 |
+
if len(calls) == 1:
|
| 35 |
+
raise _http_error(503, b"service unavailable")
|
| 36 |
+
return _Response()
|
| 37 |
+
|
| 38 |
+
monkeypatch.setattr(analytics_writer.urllib_request, "urlopen", fake_urlopen)
|
| 39 |
+
monkeypatch.setattr(analytics_writer.time, "sleep", lambda _: None)
|
| 40 |
+
|
| 41 |
+
assert analytics_writer.post_json(
|
| 42 |
+
"https://example.test/analytics",
|
| 43 |
+
{"generation_id": "g-1"},
|
| 44 |
+
{},
|
| 45 |
+
timeout=2,
|
| 46 |
+
retries=2,
|
| 47 |
+
) is True
|
| 48 |
+
assert len(calls) == 2
|
| 49 |
+
assert all(timeout == 2 for _, timeout in calls)
|
| 50 |
+
assert "503" in capsys.readouterr().out
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_post_json_does_not_retry_invalid_payload_and_logs_response_body(
|
| 54 |
+
monkeypatch, capsys
|
| 55 |
+
):
|
| 56 |
+
calls = []
|
| 57 |
+
|
| 58 |
+
def fake_urlopen(request, timeout):
|
| 59 |
+
calls.append(request)
|
| 60 |
+
raise _http_error(400, b'{"message":"generation_id is required"}')
|
| 61 |
+
|
| 62 |
+
monkeypatch.setattr(analytics_writer.urllib_request, "urlopen", fake_urlopen)
|
| 63 |
+
monkeypatch.setattr(analytics_writer.time, "sleep", lambda _: None)
|
| 64 |
+
|
| 65 |
+
assert analytics_writer.post_json(
|
| 66 |
+
"https://example.test/analytics",
|
| 67 |
+
{"bad": True},
|
| 68 |
+
{},
|
| 69 |
+
retries=3,
|
| 70 |
+
) is False
|
| 71 |
+
assert len(calls) == 1
|
| 72 |
+
output = capsys.readouterr().out
|
| 73 |
+
assert "400" in output
|
| 74 |
+
assert "generation_id is required" in output
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_queue_background_work_runs_and_surfaces_worker_exceptions(monkeypatch, capsys):
|
| 78 |
+
calls = []
|
| 79 |
+
|
| 80 |
+
future = analytics_writer.queue_background_work(calls.append, "done")
|
| 81 |
+
future.result(timeout=2)
|
| 82 |
+
assert calls == ["done"]
|
| 83 |
+
|
| 84 |
+
def fail():
|
| 85 |
+
raise RuntimeError("worker exploded")
|
| 86 |
+
|
| 87 |
+
failed = analytics_writer.queue_background_work(fail)
|
| 88 |
+
failed.result(timeout=2)
|
| 89 |
+
assert "worker exploded" in capsys.readouterr().out
|