omi icon indicating copy to clipboard operation
omi copied to clipboard

[Bounty Proposal] Guard category id lookup and make trend topic writes atomic

Open Ariyachan opened this issue 2 months ago • 1 comments

Problem

  1. Unhandled KeyError: 'id' drops entire category from public /v1/trends (backend/database/trends.py:31): In get_trends_data:

    category_topics_ref = trends_ref.document(category_data['id']).collection('topics')
    

    If a category document snapshot in Firestore does not have an explicit 'id' key inside its document dictionary (or if 'id' is None), accessing category_data['id'] raises KeyError: 'id'. This error is caught by the per-category except Exception as e: block, which logs the error and continues, silently dropping the entire valid category and all of its associated topics from the public /v1/trends API response.

  2. TypeError vulnerability when memory_ids is a non-sequence (backend/database/trends.py:43, 50): len(e.get('memory_ids') or []) assumes that any truthy value of memory_ids is a sequence. If memory_ids is stored as an integer (e.g. from legacy counter migrations or partial payloads), or [] evaluates to the integer itself, causing len(...) to raise TypeError: object of type 'int' has no attribute '__len__'.

  3. Non-atomic two-phase writes in save_trends (backend/database/trends.py:84-85): save_trends writes topic documents in two sequential operations per topic:

    topic_doc_ref.set({"id": topic_id, "topic": topic}, merge=True)
    topic_doc_ref.update({'memory_ids': firestore.firestore.ArrayUnion([memory_id])})
    

    If the first .set(...) succeeds but the second .update(...) fails or is interrupted, the topic document is left in Firestore with no memory_ids field. Furthermore, executing two calls per topic generates 2N Firestore operations instead of N.

Proposed Solution

  • In get_trends_data, extract category_id = str(category_data.get('id') or getattr(category, 'id', '') or ''), ensuring the Firestore document snapshot ID is used as fallback, and populate category_data['id'].
  • Safe sequence length: verify isinstance(val, (list, tuple, set)) before calling len(...), returning 0 for non-sequence types.
  • In save_trends, combine the topic document data and ArrayUnion([memory_id]) into a single atomic topic_doc_ref.set({"id": topic_id, "topic": topic, "memory_ids": firestore.firestore.ArrayUnion([memory_id])}, merge=True) call.
  • Add comprehensive regression tests in backend/tests/unit/test_trends_category_id_and_atomic_save.py.

Ariyachan avatar Sep 26 '26 02:09 Ariyachan

Thanks for putting this together. We aren't doing bounties at the moment, so we're closing the bounty proposal issues for now — thanks for the fix! 🙏

undivisible avatar Oct 22 '26 11:10 undivisible