Skip to content

fix(goals): bucket goal-history documents by the user's local day, not UTC's - #15209

Merged
kodjima33 merged 3 commits into
BasedHardware:mainfrom
Abhist17:fix/goal-history-local-timezone
Sep 21, 2026
Merged

kodjima33 merged 3 commits into
BasedHardware:mainfrom
Abhist17:fix/goal-history-local-timezone

Conversation

@Abhist17

@Abhist17 Abhist17 commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Description

_append_goal_progress_event and save_goal_progress_history in database/goals.py key goal_history documents by datetime.now(timezone.utc).strftime('%Y-%m-%d'). A user west of UTC (e.g. US Pacific) whose local evening hasn't yet crossed UTC midnight has their progress written into tomorrow's UTC-dated document; a user east of UTC can have it land in yesterday's. GET /v1/goals/{id}/history (database.goals.get_goal_history, ordered by the date field, days=30 default) returns a chart whose day boundaries don't match the user's own calendar.

Same bug class as the already-shipped fix for the proactive-notification daily cap (_proactive_daily_cap_reached), which bucketed by resolve_user_timezone(uid) instead of raw UTC.

The fix

Added _history_date_str(uid, now), which resolves the user's IANA timezone via resolve_user_timezone (imported locally inside the function — database.goals is intentionally import-light for its test suite's minimal Firestore stubbing, so a module-level import of database.notifications would break tests/unit/test_goals_id_fallback.py / test_goals_sort_missing_created_at.py) and buckets by the local calendar day, falling back to UTC if the zone is missing or unresolvable. Both write sites now go through it.

Testing performed

  • New regression tests in tests/unit/test_goal_history_local_day.py: local-day bucketing west and east of UTC, the unresolvable-zone fallback, and that save_goal_progress_history writes both the document id and the stored date field as the local day.
  • tests/unit/test_goal_history_local_day.py, test_goal_progress_events_skip_malformed.py, test_goal_get_by_id.py, test_goals_advice_arg_and_clear_metric.py, test_goals_id_fallback.py, test_goal_source_compatibility.py, test_goal_context_null_message_text.py, test_goal_extraction_batch.py, test_goals_response_int_guard.py, test_goals_sort_missing_created_at.py, test_goal_storage_coerce_guard.py, test_dev_goals_limit_include_inactive.py — each run in its own process (matching this repo's own per-file isolation for pollution-prone suites); all green. Confirmed test_goals_id_fallback.py/test_goals_sort_missing_created_at.py broke when resolve_user_timezone was imported at module scope, which is why the import is local to the function instead.
  • python3 -c "import database.goals" — clean, no circular import.
  • scripts/backend-python-format --check — clean.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)

Product invariants affected

none

Failure class (fixes)

Failure-Class: none

The closest existing class, FC-day-bucket-key-recomputed, is scoped to the Flutter app's conversationLocalDayKey comparison (app/lib/providers/**) — a different domain and mechanism (client-side day-key comparison vs. this backend's resolve_user_timezone-based Firestore document keying). Given how many backend UTC-vs-local-day bugs have surfaced recently (the notification cap fix referenced above, plus several open bounty proposals on the same pattern), a backend-scoped class may be worth declaring separately — leaving that call to a maintainer rather than declaring new without surveying the full recent history myself.

Fixes #15206

@Abhist17

Copy link
Copy Markdown
Contributor Author

The 3 failing `Backend unit` shards are pre-existing breaks on `main`, unrelated to this PR's diff (only `database/goals.py` and one new test file):

  • `test_setup_completed_url_uid_query.py` and `test_app_enable_install_count.py` both fail with `TypeError: enable_app_endpoint() missing 1 required positional argument: 'request'` — this is the same root cause already reported in [Bounty proposal] main is red: enable_app_endpoint test misses the new request argument ($50 proposed) #15195.
  • `test_app_client_schema_inventory.py::test_inventory_openapi_route_response_decode_migration_complete` fails independently (an assert not [...] on a raw-response-decode-site inventory) — I couldn't find an existing issue for this one, filing separately.

Shard 2/4 (which happens to contain this PR's own new test file, `test_goal_history_local_day.py`) passed cleanly. Happy to rebase once `main` is green again.

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @Abhist17 — verified end to end, and this checks out cleanly. Notes below.

The fix (backend/database/goals.py): _history_date_str(uid, now) resolving the user's zone via resolve_user_timezone and bucketing by the local calendar day is the right call, and matches the approach already shipped for the proactive-notification daily cap. Nice detail: both the document id and the stored date field now come from the same string at both write sites (_append_goal_progress_event's transactional write and save_goal_progress_history) — that consistency is what actually fixes the chart, since get_goal_history orders by the date field. The UTC fallback for unresolvable zones is sensible defense-in-depth on top of resolve_user_timezone's own normalization.

Tests (tests/unit/test_goal_history_local_day.py): good targeted coverage — west/east-of-UTC bucketing, the unresolvable-zone fallback, and a full save_goal_progress_history write asserting both doc id and stored fields.

CI: your triage is confirmed — the three failing files (test_app_enable_install_count.py, test_setup_completed_url_uid_query.py, test_app_client_schema_inventory.py) fail identically on main at 16fc2075 (this branch's parent commit), and main's suite is green again from later commits. Unrelated to this diff. For the record, the ENCRYPTION_SECRET in the new test matches the dummy fixture this repo already uses in its other unit tests — no issue there.

Two non-blocking notes, fine to address whenever:

  1. In _append_goal_progress_event, _history_date_str runs inside the @firestore.transactional callback, so the users/{uid} zone read repeats on every transaction retry. Resolving the zone before entering the transaction would avoid that — not urgent.
  2. At deploy time, users off UTC will briefly have both a UTC-dated and a local-dated doc for the boundary day, which can show as a duplicate day in the chart until the stale doc ages out of the 30-day window. Cosmetic; worth a release-note line at most.

Since this changes goal-history persistence semantics (which document a day's progress lands in), leaving the merge call to a human maintainer — everything technical verifies clean.

🤖 Automated review on behalf of the maintainers.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution backend Backend Task (python) labels Sep 20, 2026
…n retry loop

Addressed review note from Git-on-my-level on PR BasedHardware#15209: _history_date_str
did a Firestore read of the user's timezone inside the @firestore.transactional
callback, repeating on every contention retry. now doesn't change across
retries, so resolve it once before entering the transaction.
@Abhist17

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review!

  1. Fixed — _history_date_str is now resolved once before entering the transaction (pushed), so a contention retry no longer repeats the timezone read.
  2. Makes sense, and agreed it's cosmetic — a boundary-day user could briefly see both a UTC- and local-dated doc until the older one ages out of the 30-day window. Didn't add a migration for it since there's no way to know which existing UTC-dated docs actually belong to a different local day without re-reading every user's timezone against every historical doc, which felt like more risk than the cosmetic issue warrants. Happy to do that as a follow-up if a maintainer wants it.

@Git-on-my-level — this is ready whenever a human has a moment to merge. This was proposed as a $50 bounty (#15206); glad to take it whenever that's convenient, no rush.

…nt seam

_history_date_str called database.notifications.resolve_user_timezone(), which
has no firestore_client injection point of its own and always hit the real
Firestore client. Invisible in this module's own tests (they inject a fake
client throughout), but it broke tests/unit/test_workstream_core.py's
hermetic goal tests, which exercise goals.py through their own fake_db and
have no reason to know this module reached into another one's unmocked
client -- CI failed with BlockedNetworkError against the GCP metadata IP
(ADC credential resolution) once resolve_user_timezone tried to read the
real users/{uid} doc.

Reads time_zone directly through _get_db(firestore_client) instead -- the
same seam every other read in this module already goes through -- and
removes the need for the database.notifications import entirely.
@Abhist17

Copy link
Copy Markdown
Contributor Author

Found and fixed a real regression from my last push — this one was actually mine, not a pre-existing main issue.

Root cause: _history_date_str called database.notifications.resolve_user_timezone(uid), which has no firestore_client injection point of its own and always hits the real Firestore client. That was invisible in this PR's own tests (they inject a fake client throughout), but it broke tests/unit/test_workstream_core.py's hermetic goal tests, which exercise database.goals through their own fake_db and have no reason to know this function reached into a different module's unmocked client. CI failed both tests with BlockedNetworkError against the GCP metadata IP — resolve_user_timezone tried a real Firestore read, which tried real ADC credential resolution, which the hermetic-network guard correctly blocked.

Fix: _history_date_str now reads time_zone directly through _get_db(firestore_client) — the same seam every other read in this module already uses — instead of calling into database.notifications. Bonus: this also removes the local-import workaround from the last round of feedback, since there's no cross-module import left at all.

Verified: reproduced both previously-failing test_workstream_core.py tests locally against the prior commit, confirmed they pass against this one, plus the full existing suite (test_goal_history_local_day.py, test_workstream_core.py, test_conversation_first_open_work.py, test_workstream_router_contract.py, test_prompt_cache_integration.py, and the 11 other goal test files from earlier) — all green.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixes #15206: goal-history documents were keyed by UTC calendar day, causing progress to land on the wrong day for non-UTC users. Now buckets via resolve_user_timezone (same pattern as the shipped notification-cap fix), with lazy import to avoid breaking existing test stubbing. New regression tests cover west/east of UTC and the fallback. CI green.

@kodjima33
kodjima33 merged commit 651d0a4 into BasedHardware:main Sep 21, 2026
40 checks passed
@Abhist17

Copy link
Copy Markdown
Contributor Author

Following up on payment for this one — merged 2026-09-21.

I've emailed [email protected] with the full list of my merged bounty PRs, as the contribution guide asks under Paid Bounties ("claiming payment"). Leaving a note here too so it's on the thread rather than only in a mailbox.

Bounty: $50 — proposal #15206.
cc @kodjima33 @josancamon19

Payout — crypto is easiest for me, USDC/USDT on either chain:

  • EVM (Ethereum / Base / Polygon / Arbitrum): 0x49A441f63f00b1978Aa4DD4ff52C237a4A7FdF82
  • Solana: FQetSNNrMouXQ1W3hzCunkd3V5kyvvBtKxQZ2mWfksxV

Happy to use whatever method is simplest on your side. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bounty proposal] fix(backend): goal progress history is bucketed by UTC day, not the user's own ($50 proposed)

3 participants