#19335·omi

fix(backend): unhandled exceptions and input validation in database/focus_sessions

Author: brandonstensby-dotcomCreated Sep 27, 2026Updated Sep 28, 2026

Problem Summary

In backend/database/focus_sessions.py:

  1. Unhandled 500 on Malformed Date String: get_focus_sessions calls datetime.strptime(date, '%Y-%m-%d'). If an invalid date string (e.g. invalid calendar date such as 2026-02-31, empty/whitespace string, or non-matching format) reaches the database layer, strptime raises ValueError: time data '...' does not match format '%Y-%m-%d'. In the database query path, this crashes as an unhandled 500.
  2. Missing NotFound Guard on Concurrent Deletion: In delete_focus_session, ref.get() is checked for exists, but between the check and ref.delete(), a concurrent delete or prune raises google.api_core.exceptions.NotFound, causing an unhandled server error.
  3. Missing Input Normalization & Missing UID Validation:
    • _user_col(uid, collection) did not validate uid, allowing whitespace or invalid types to propagate into Firestore collection calls.
    • create_focus_session lacked sanitization for invalid status values (should safely default to 'focused'), None app/site (should default to 'Unknown'), and None descriptions.
    • get_focus_sessions and get_focus_stats did not guard against None or blank uids, resulting in unnecessary Firestore round-trips or malformed paths.
    • limit and offset in get_focus_sessions were unclamped, allowing negative offsets or unbounded pagination sizes up to Firestore quota limits.
  4. Router Error Surface: In backend/routers/focus_sessions.py, create_focus_session did not catch ValueError from the database layer, surfacing client validation errors as unhandled 500s rather than clean 400 Bad Request responses.

Proposed Fix

  • Added try...except (ValueError, TypeError) in get_focus_sessions to log a warning and return an empty list gracefully on malformed dates.
  • Clamped limit (1 to 5000) and offset (minimum 0) in get_focus_sessions.
  • Wrapped delete_focus_session in try...except NotFound to handle race conditions cleanly.
  • Added explicit string validation to _user_col raising descriptive ValueError on empty/non-string uid.
  • Sanitized status, app_or_site, and description in create_focus_session.
  • In backend/routers/focus_sessions.py, mapped ValueError in create_focus_session to HTTPException(status_code=400, detail=str(e)).
  • Added hermetic unit test suite in backend/tests/unit/test_database_focus_sessions_resilience.py (11 passing tests; 17 total passing across focus session suites).

Bounty Proposal

  • Category: Backend Bug Fix / Hardening
  • Proposed Bounty: $50 USD
  • Designated Payout Rails: