Files
karaoke-gen/scripts/query-error-patterns.py
T
Andrew Beveridge ☄️andClaude Opus 4.8 e806616408 fix: idempotent session revoke, error-pattern script crash, mobile header overlap (#798)
## Summary
Three independent fixes bundled together:

1. **`revoke_session` idempotency** — stops the recurring `Error
revoking session` prod error on `karaoke-backend`. Firestore
`document.update()` raises `NotFound` (404) when a session doc is
already gone (logged out / expired / cleaned up); logout against an
already-absent session now succeeds instead of erroring.
2. **`query-error-patterns.py` crash** — `last_seen`/`first_seen` are
stored as ISO-8601 strings in Firestore, but the sort key and `--hours`
filter did `float(value)`, raising `ValueError` and breaking the
`--json` path that `/prod-investigate` relies on. Added a `_to_epoch()`
helper handling datetime objects, ISO strings, and numeric epochs.
3. **Mobile header overlap** — `AppHeader` was `position: fixed` and
each consumer cleared it with a hardcoded top padding. On narrow
viewports the header wraps to 3 rows (149px on a 412px Pixel), exceeding
the 112px offset, hiding the "Create Karaoke Video" heading and the top
of the form behind it (worse across locales with longer button labels).
Switched `AppHeader` to `position: sticky` (matching the already-working
jobs-page header) so content always clears it at any height, and removed
the now-redundant magic-number offsets.

## Changes
- `backend/services/user_service.py` — catch
`google_exceptions.NotFound` in `revoke_session`, return `True`
- `backend/tests/test_revoke_session.py` — new unit tests (existing /
missing / unexpected-error paths)
- `scripts/query-error-patterns.py` — `_to_epoch()` helper for sort +
`--hours` filter
- `frontend/components/app-header.tsx` — `fixed` → `sticky`
- `frontend/app/[locale]/app/page.tsx`,
`frontend/app/[locale]/app/referrals/page.tsx` — drop hardcoded top
padding
- `pyproject.toml` — bump to 0.174.17

## Testing
- [x] Backend tests pass locally (47 passed incl. 3 new `revoke_session`
tests)
- [x] `query-error-patterns.py --json` and `--hours` verified against
live Firestore
- [x] Mobile header fix verified in Playwright at 412px (Pixel) and
1280px — overlap eliminated (title moves from 12px behind the header to
a clear gap below it)
- [x] CodeRabbit CLI review: 0 findings

## Review
- [x] Local CodeRabbit review completed
- [x] Review feedback addressed (none)

@coderabbitai ignore

---
🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 23:24:21 -04:00

211 lines
6.0 KiB
Python
Executable File

#!/usr/bin/env python3
"""
Query error patterns from Firestore.
Usage:
python scripts/query-error-patterns.py # All active
python scripts/query-error-patterns.py --status new # Only new
python scripts/query-error-patterns.py --service karaoke-backend
python scripts/query-error-patterns.py --hours 24 # Last 24h
python scripts/query-error-patterns.py --json # JSON output
Requires:
- google-cloud-firestore
- GOOGLE_APPLICATION_CREDENTIALS or gcloud auth application-default login
"""
import argparse
import json
import sys
from datetime import datetime, timedelta, timezone
from typing import Any, Optional
from google.cloud import firestore
from google.cloud.firestore_v1 import FieldFilter
ACTIVE_STATUSES = ["new", "acknowledged", "known"]
def _to_epoch(value: Any) -> Optional[float]:
"""Convert a Firestore timestamp value to epoch seconds.
Handles the three shapes ``last_seen``/``first_seen`` can take:
- Firestore/datetime objects (have ``.timestamp()``)
- ISO-8601 strings (the error-monitor writes these), e.g.
``'2026-06-04T18:31:59.086317+00:00'``
- numeric epoch seconds
Returns None if the value is missing or unparseable.
"""
if value is None:
return None
if hasattr(value, "timestamp"):
return value.timestamp()
if isinstance(value, str):
try:
return datetime.fromisoformat(value).timestamp()
except ValueError:
return None
try:
return float(value)
except (TypeError, ValueError):
return None
def query_error_patterns(
status: Optional[str] = None,
service: Optional[str] = None,
hours: Optional[int] = None,
output_json: bool = False,
project: str = "nomadkaraoke",
) -> list[dict[str, Any]]:
"""
Query error patterns from Firestore.
Args:
status: Filter by status (new/acknowledged/known/fixed). Default: active (new/acknowledged/known).
service: Filter by service name.
hours: Only return patterns last seen within this many hours.
output_json: Print JSON output instead of a table.
project: GCP project ID.
Returns:
List of pattern dicts.
"""
db = firestore.Client(project=project)
query = db.collection("error_patterns")
# Status filter
if status:
query = query.where(filter=FieldFilter("status", "==", status))
else:
query = query.where(filter=FieldFilter("status", "in", ACTIVE_STATUSES))
# Service filter
if service:
query = query.where(filter=FieldFilter("service", "==", service))
# Fetch all matching docs (streaming)
patterns = []
for doc in query.stream():
data = doc.to_dict()
data["_id"] = doc.id
patterns.append(data)
# Hours filter (applied in Python — Firestore requires composite index for multi-field filters)
if hours is not None:
cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
filtered = []
for p in patterns:
ts = _to_epoch(p.get("last_seen"))
if ts is not None and ts >= cutoff.timestamp():
filtered.append(p)
patterns = filtered
# Sort by last_seen descending (most recent first)
patterns.sort(key=lambda p: _to_epoch(p.get("last_seen")) or 0.0, reverse=True)
if output_json:
print(json.dumps(patterns, indent=2, default=str))
else:
_print_table(patterns)
return patterns
def _fmt_last_seen(value) -> str:
"""Return first 19 chars of ISO timestamp, or empty string."""
if value is None:
return ""
if hasattr(value, "isoformat"):
return value.isoformat()[:19]
return str(value)[:19]
def _print_table(patterns: list[dict[str, Any]]) -> None:
"""Print patterns as a human-readable table."""
if not patterns:
print("No error patterns found.")
return
# Column widths
col_status = 14
col_service = 24
col_count = 6
col_last_seen = 19
col_message = 50
header = (
f"{'Status':<{col_status}} "
f"{'Service':<{col_service}} "
f"{'Count':>{col_count}} "
f"{'Last Seen':<{col_last_seen}} "
f"{'Message':<{col_message}}"
)
separator = "-" * len(header)
print(separator)
print(header)
print(separator)
for p in patterns:
status = str(p.get("status", ""))[:col_status]
service = str(p.get("service", ""))[:col_service]
count = p.get("total_count", p.get("occurrence_count", p.get("count", 0)))
last_seen = _fmt_last_seen(p.get("last_seen"))
message = str(p.get("normalized_message", p.get("error_message", p.get("message", ""))))[:col_message]
print(
f"{status:<{col_status}} "
f"{service:<{col_service}} "
f"{count:>{col_count}} "
f"{last_seen:<{col_last_seen}} "
f"{message:<{col_message}}"
)
print(separator)
print(f"Total: {len(patterns)} pattern(s)")
def main():
parser = argparse.ArgumentParser(
description="Query error patterns from Firestore"
)
parser.add_argument(
"--status",
help="Filter by status (new/acknowledged/known/fixed). Default: active patterns.",
)
parser.add_argument(
"--service",
help="Filter by service name (e.g. karaoke-backend).",
)
parser.add_argument(
"--hours",
type=int,
help="Only show patterns last seen within this many hours.",
)
parser.add_argument(
"--json",
action="store_true",
dest="output_json",
help="Output as JSON.",
)
parser.add_argument(
"--project",
default="nomadkaraoke",
help="GCP project ID (default: nomadkaraoke).",
)
args = parser.parse_args()
query_error_patterns(
status=args.status,
service=args.service,
hours=args.hours,
output_json=args.output_json,
project=args.project,
)
if __name__ == "__main__":
main()