Files
karaoke-gen/backend/tests/api/test_client_errors.py
T
Andrew Beveridge ☄️andClaude Opus 4.8 d6361ca7ad fix(error-monitor): stop transient-capacity + bot crashes from paging (#897)
## Why

Two alert-channel noise sources surfaced during the flacfetch download
incident. Neither was a real production problem, but both page — so we
fix the **monitor's signal quality** rather than mute them.

### 1. Transient encoding-worker capacity retries
`[job:…] Encoding worker start failed, aborting retries: VM … 503 —
SERVICE UNAVAILABLE` is a transient GCP zonal-capacity event.
`render_video_worker` catches `EncodingWorkerStartError` and **parks the
job for auto-retry** (`_park_job_for_capacity_retry`) — the job is *not*
lost, and a genuine give-up fails the job via a separate ERROR. Added a
`known_issues` suppression **scoped to the transient signal only** (503
/ `SERVICE UNAVAILABLE` or a capacity code:
`ZONE_RESOURCE_POOL_EXHAUSTED` / `STOCKOUT` / `QUOTA_EXCEEDED`). A
non-transient `EncodingWorkerStartError` (other/unknown code) shares the
prefix but **still pages**.

### 2. One incident → N alerts (normalizer gap)
The same failure produced *two* alerts (same job, two preview-render
IDs). `preview_<jobid>_<renderid>` is underscore-joined, and the generic
hex normalizer is `\b`-anchored (`_` is a word char), so every preview
render hashed to a distinct "new pattern." Added a normalizer rule that
collapses `preview_<hex>_<hex>` → `preview_<ID>`.

### 3. Bot/crawler browser crashes
`NotFoundError: removeChild` on `/en/r/` came from **bingbot** running
headless Chrome — a React DOM-reconciliation error no real user hits (0
real-user occurrences in 7d). Reports from bot/crawler user-agents are
now dropped at the `/client-errors` ingestion edge (still `202` so the
client won't retry), instead of being persisted/alerted.

## Tests
- `known_issues`: transient 503 **and** capacity-code variants
suppressed; non-transient start failure + genuine job failure still
alert.
- `normalizer`: preview-ID collapse; two renders of one job → same hash.
- `is_bot_user_agent`: crawler matrix true, real-browser/empty/None
false.
- API: a bingbot report is accepted (`202`, `is_new=false`) but **not
upserted**.

`133 passed`. Local CodeRabbit review completed and its two findings
(scope the capacity regex; sanitize the logged bot URL) were addressed;
a confirming re-review was blocked by the free-tier rate limit, so
leaving the bot review on.

## Notes
The actual outage in this incident (daily E2E download failure) was a
**flacfetch** bug, fixed + deployed separately (flacfetch #36). This PR
only removes the alert noise those investigations surfaced.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Bug Fixes**
- Bot and crawler error reports are acknowledged without being persisted
or triggering alerts.
- Transient encoding-worker capacity failures are filtered as retryable
infrastructure noise.
- Preview render job identifiers are normalized consistently for
improved error grouping.

- **Maintenance**
  - Updated the application version to 0.192.2.
- Expanded validation for bot detection, error filtering, and preview
error normalization.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-07 10:20:47 +02:00

105 lines
3.7 KiB
Python

"""API tests for POST /api/client-errors."""
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from backend.api.routes.client_errors import router as client_errors_router
@pytest.fixture
def client(monkeypatch):
# reset the module-level limiter between tests
import backend.api.routes.client_errors as mod
mod._limiter = mod.RateLimiter(max_per_minute=60)
fake_adapter = MagicMock()
fake_adapter.upsert_pattern.return_value = MagicMock(
pattern_id="deadbeef", is_new=True, previous_status=None
)
monkeypatch.setattr(mod, "_get_adapter", lambda: fake_adapter)
app = FastAPI()
app.include_router(client_errors_router, prefix="/api")
client = TestClient(app)
client.fake_adapter = fake_adapter # type: ignore[attr-defined]
return client
def _payload(**overrides):
base = {
"message": "TypeError: Cannot read properties of null",
"stack": "TypeError: Cannot read properties of null\n at x (app.js:1:2)",
"url": "https://gen.nomadkaraoke.com/en/app/jobs/#/abc/review",
"user_agent": "Mozilla/5.0 (Android 14; Mobile; rv:138.0) Gecko/138.0 Firefox/138.0",
"release": "abc1234",
"user_email": None,
"viewport": {"w": 412, "h": 915},
"locale": "en",
"source": "window.onerror",
}
base.update(overrides)
return base
def test_accepts_valid_report_and_upserts(client):
resp = client.post("/api/client-errors", json=_payload())
assert resp.status_code == 202
assert resp.json()["pattern_id"] == "deadbeef"
client.fake_adapter.upsert_pattern.assert_called_once()
(pd,), _ = client.fake_adapter.upsert_pattern.call_args
assert pd.service == "frontend"
assert pd.resource_type == "browser"
def test_bot_report_is_accepted_but_not_persisted(client):
bot_ua = (
"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; "
"bingbot/2.0; +http://www.bing.com/bingbot.htm) Chrome/136.0.0.0 Safari/537.36"
)
resp = client.post("/api/client-errors", json=_payload(user_agent=bot_ua))
# Accepted (so the bot won't retry) but never upserted / alerted.
assert resp.status_code == 202
assert resp.json()["is_new"] is False
client.fake_adapter.upsert_pattern.assert_not_called()
def test_rejects_missing_message(client):
resp = client.post("/api/client-errors", json=_payload(message=""))
assert resp.status_code == 422
def test_caps_oversized_payload(client):
huge = "x" * 200_000
resp = client.post("/api/client-errors", json=_payload(stack=huge))
# server accepts but truncates — sample_message must be <= MAX
assert resp.status_code == 202
(pd,), _ = client.fake_adapter.upsert_pattern.call_args
from backend.services.error_monitor.frontend_ingestion import (
MAX_SAMPLE_MESSAGE_CHARS,
)
assert len(pd.sample_message) <= MAX_SAMPLE_MESSAGE_CHARS
def test_rate_limit_returns_429(client, monkeypatch):
import backend.api.routes.client_errors as mod
mod._limiter = mod.RateLimiter(max_per_minute=2)
assert client.post("/api/client-errors", json=_payload()).status_code == 202
assert client.post("/api/client-errors", json=_payload()).status_code == 202
r3 = client.post("/api/client-errors", json=_payload())
assert r3.status_code == 429
def test_strips_sensitive_query_string(client):
resp = client.post(
"/api/client-errors",
json=_payload(url="https://gen.nomadkaraoke.com/en/app/jobs/?token=SECRET#/abc/review"),
)
assert resp.status_code == 202
(pd,), _ = client.fake_adapter.upsert_pattern.call_args
assert "SECRET" not in pd.sample_message
assert "token=" not in pd.sample_message