[Bounty Proposal] Guard category id lookup and make trend topic writes atomic
Problem
-
Unhandled
KeyError: 'id'drops entire category from public/v1/trends(backend/database/trends.py:31): Inget_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), accessingcategory_data['id']raisesKeyError: 'id'. This error is caught by the per-categoryexcept Exception as e:block, which logs the error andcontinues, silently dropping the entire valid category and all of its associated topics from the public/v1/trendsAPI response. -
TypeErrorvulnerability whenmemory_idsis a non-sequence (backend/database/trends.py:43, 50):len(e.get('memory_ids') or [])assumes that any truthy value ofmemory_idsis a sequence. Ifmemory_idsis stored as an integer (e.g. from legacy counter migrations or partial payloads),or []evaluates to the integer itself, causinglen(...)to raiseTypeError: object of type 'int' has no attribute '__len__'. -
Non-atomic two-phase writes in
save_trends(backend/database/trends.py:84-85):save_trendswrites 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 nomemory_idsfield. Furthermore, executing two calls per topic generates 2N Firestore operations instead of N.
Proposed Solution
- In
get_trends_data, extractcategory_id = str(category_data.get('id') or getattr(category, 'id', '') or ''), ensuring the Firestore document snapshot ID is used as fallback, and populatecategory_data['id']. - Safe sequence length: verify
isinstance(val, (list, tuple, set))before callinglen(...), returning 0 for non-sequence types. - In
save_trends, combine the topic document data andArrayUnion([memory_id])into a single atomictopic_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.
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! 🙏