get_user_goals drops active goals by truncating before it filters and sorts
Symptom
Mentor notifications and deep daily recaps see at most three of a user's active goals, chosen by Firestore document id rather than by age. A user whose oldest goals were created later gets advice about the wrong goals, and ended goals inside that first page make the list come back short.
Evidence
On origin/main 31a07230bb, get_user_goals (backend/database/goals.py) runs where is_active == True with .limit(limit) and no order_by, then filters out achieved and abandoned goals and sorts oldest-first in Python. Firestore returns the limited page in document-id order, so the filter and sort only ever see that page. backend/utils/proactivity_producers.py and backend/utils/llm/external_integrations.py call it with limit=3.
Expected
limit=3 returns the three oldest active goals, regardless of document id, and ended goals do not shorten the page.
Fixed in #23293 (proposal tracked in #23294) — the limit now applies after the ended-goal filter and the oldest-first sort, matching the get_all_goals pattern in the same module.
I have submitted a fix for this in #23303:
Root cause & Solution
- In
backend/database/goals.py,.limit(limit)was applied at the Firestore query level before filtering and sorting. Because Firestore returns documents in arbitrary document ID order withoutorder_by, and post-query Python filtering removesachievedandabandonedgoals, the returned page could be truncated short and older active goals were missed. - The fix streams active documents without query-level limit, filters out terminal goals (
achieved,abandoned), sorts oldest-first via_goal_created_at_sort_key(preserving safe handling of dateless legacy goals), and slices[:limit]. - Added comprehensive unit test suite in
backend/tests/unit/test_get_user_goals_filter_and_sort.pyverifying all edge cases.
Payout address: 0xC345C07229307d4f1c7935aD2cAe48e390215808 (USDC on Polygon / Base / Arbitrum)