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>
This commit is contained in:
Andrew Beveridge ☄️andClaude Opus 4.8 authored and GitHub committed 2026-06-05 23:24:21 -04:00
1 parent 87f36687bf
commit e806616408
7 files changed
+109 -18

No files matched your search

+10 -1
View File
@@ -900,12 +900,21 @@ class UserService:
return False, None, "An error occurred during validation"
def revoke_session(self, token: str) -> bool:
"""Revoke a session (logout)."""
"""Revoke a session (logout).
Idempotent: a session document that no longer exists is already
revoked, so a missing document is treated as success rather than an
error. Firestore's ``update()`` raises NotFound when the document is
absent (e.g. already logged out, or expired/cleaned up).
"""
try:
doc_ref = self.db.collection(SESSIONS_COLLECTION).document(token)
doc_ref.update({'is_active': False})
logger.info("Session revoked")
return True
except google_exceptions.NotFound:
logger.info("Session already absent; treating revoke as success")
return True
except Exception:
logger.exception("Error revoking session")
return False
+65
View File
@@ -0,0 +1,65 @@
"""
Tests for UserService.revoke_session idempotency.
Revoking a session that no longer exists (already logged out, expired, or
cleaned up) should be treated as success rather than logged as an error.
Firestore's document.update() raises NotFound when the document is absent.
"""
from unittest.mock import MagicMock, patch
# Mock Firestore before importing modules that use it
import sys
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
from google.api_core import exceptions as google_exceptions
class TestRevokeSession:
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_revoke_existing_session_succeeds(self, mock_fs, mock_settings):
"""A normal revoke updates is_active and returns True."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
doc_ref = mock_db.collection.return_value.document.return_value
from backend.services.user_service import UserService
service = UserService()
assert service.revoke_session("token-abc") is True
doc_ref.update.assert_called_once_with({'is_active': False})
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_revoke_missing_session_is_idempotent(self, mock_fs, mock_settings):
"""A missing session document is already revoked → return True, no error."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
doc_ref = mock_db.collection.return_value.document.return_value
doc_ref.update.side_effect = google_exceptions.NotFound(
"No document to update: sessions/deadbeef"
)
from backend.services.user_service import UserService
service = UserService()
assert service.revoke_session("missing-token") is True
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_revoke_unexpected_error_returns_false(self, mock_fs, mock_settings):
"""Genuine errors (not NotFound) are swallowed and return False."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
doc_ref = mock_db.collection.return_value.document.return_value
doc_ref.update.side_effect = google_exceptions.DeadlineExceeded("timeout")
from backend.services.user_service import UserService
service = UserService()
assert service.revoke_session("token-abc") is False
+1 -1
View File
@@ -256,7 +256,7 @@ function AppPageContent() {
onClose={() => setShowFeedbackDialog(false)}
/>
<main className="px-4 pt-28 sm:pt-24 pb-8 space-y-6">
<main className="px-4 pt-4 pb-8 space-y-6">
{/* Push notification prompt - shows once when appropriate */}
<PushNotificationPrompt />
+1 -1
View File
@@ -13,7 +13,7 @@ export default function ReferralsPage() {
return (
<div className="min-h-screen" style={{ backgroundColor: 'var(--background)' }}>
<AppHeader />
<main className="container mx-auto max-w-4xl px-4 pt-24 sm:pt-20 pb-6">
<main className="container mx-auto max-w-4xl px-4 pt-6 pb-6">
<Link
href="/app"
className="inline-flex items-center gap-1 text-sm mb-4 hover:underline"
+1 -1
View File
@@ -44,7 +44,7 @@ export function AppHeader({ children }: { children?: ReactNode }) {
useEffect(() => { setMounted(true) }, [])
return (
<header className="fixed top-0 left-0 right-0 z-50 bg-dark-900/80 backdrop-blur-md border-b border-dark-700">
<header className="sticky top-0 z-50 bg-dark-900/80 backdrop-blur-md border-b border-dark-700">
{/* Desktop: single row (sm+) */}
<div className="hidden sm:flex px-4 py-3 items-center justify-between gap-2">
<div className="flex items-center gap-3 min-w-0">
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.174.16"
version = "0.174.17"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
+30 -13
View File
@@ -26,6 +26,32 @@ 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,
@@ -71,22 +97,13 @@ def query_error_patterns(
cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
filtered = []
for p in patterns:
last_seen = p.get("last_seen")
if last_seen is not None:
# Firestore Timestamps have a .timestamp() method
ts = last_seen.timestamp() if hasattr(last_seen, "timestamp") else float(last_seen)
if ts >= cutoff.timestamp():
filtered.append(p)
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)
def sort_key(p):
ls = p.get("last_seen")
if ls is None:
return 0.0
return ls.timestamp() if hasattr(ls, "timestamp") else float(ls)
patterns.sort(key=sort_key, reverse=True)
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))