Skip to content

fix(backend): honor user timezone in conversation metadata + rendering (wrong times/dates in chat) - #10012

Merged
kodjima33 merged 1 commit into
BasedHardware:mainfrom
arhxam:fix/user-timezone-conversation-metadata-render
Jul 21, 2026
Merged

kodjima33 merged 1 commit into
BasedHardware:mainfrom
arhxam:fix/user-timezone-conversation-metadata-render

Conversation

@arhxam

@arhxam arhxam commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Two timezone bugs feed the chat/LLM layer wrong dates and times — the "AI mentions the wrong time of day / wrong date" class reported in #4643 (and referenced in the code around #6214). One of them also silently breaks metadata extraction for any user who hasn't set a timezone.

Root cause & fix

1. utils/llm/chat.py — metadata date-grounding crashes for timezone-less users

retrieve_metadata_from_message / retrieve_metadata_from_text / retrieve_metadata_fields_from_transcript ground the model's notion of "today" with:

today is {created_at.astimezone(ZoneInfo(tz)).strftime('%Y-%m-%d')} in {tz} ...

tz comes from save_structured_vector:

tz = notification_db.get_user_time_zone(uid) or ''

So a user who has not set a timezone produces tz == '', and ZoneInfo('') raises ValueError before the LLM call:

>>> from zoneinfo import ZoneInfo; ZoneInfo('')
ValueError: ZoneInfo keys must be normalized relative paths, got: 

retrieve_metadata_fields_from_transcript is the default path for regular conversations, so those users' people/topics/entities/dates vector metadata is never written — degrading search/retrieval. The raw astimezone on a possibly-naive created_at also reinterprets it as server-local time.

Fix: delegate to the module's existing purpose-built helper date_in_tz(created_at, tz) (utils/llm/temporal.py), which already falls back to UTC for a missing/invalid tz and treats naive datetimes as UTC.

-today is {created_at.astimezone(ZoneInfo(tz)).strftime('%Y-%m-%d')} in {tz} (user's local timezone).
+today is {date_in_tz(created_at, tz)} in {tz} (user's local timezone).

2. utils/conversations/render.py — naive timestamps rendered as server-local

conversations_to_string renders created_at / started_at / finished_at with .astimezone(display_tz) but skips the module's own _as_utc() guard — the guard that format_local_time / format_local_date already apply for exactly this reason:

def _as_utc(dt):  # "Treat a naive timestamp as UTC so astimezone cannot reinterpret it as server-local."
    return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt

created_at/started_at/finished_at are plain datetime (often naive UTC), so on any non-UTC backend host the conversation text handed to the chat LLM shows the wrong wall clock.

Fix: wrap each timestamp in _as_utc() before .astimezone(display_tz).

Tests

  • test_conversations_to_string.py → TestConversationsToStringNaiveTimestamps forces a non-UTC process timezone (America/Los_Angeles) via TZ + time.tzset() so the naive-as-local defect is deterministic regardless of where CI runs, and asserts naive timestamps render as UTC and convert correctly to a user tz. These fail on the pre-fix code.
  • test_temporal_date_in_tz.py locks the date_in_tz contract the chat.py fix now relies on: empty / None / invalid tz fall back to UTC without raising (the exact '' input that crashed the old expression), and naive datetimes are read as UTC.

Verification

$ python -m pytest tests/unit/test_conversations_to_string.py tests/unit/test_temporal_date_in_tz.py
19 passed

# revert the render.py _as_utc fix -> the two naive tests fail:
$ python -m pytest tests/unit/test_conversations_to_string.py::TestConversationsToStringNaiveTimestamps
2 failed

$ black --line-length 120 --check utils/llm/chat.py utils/conversations/render.py \
    tests/unit/test_conversations_to_string.py tests/unit/test_temporal_date_in_tz.py
All done! 4 files would be left unchanged.

Note: I ran the affected backend unit tests and black directly (in a fork). The repo's maintainer-only preflight tooling (make preflight, scripts/failure-class) requires the full monorepo checkout/toolchain and was not run here.

Relates to #4643, #6214


🤖 Generated with Claude Code

Review in cubic

Two timezone-correctness defects fed wrong dates/times into the chat LLM
and, for timezone-less users, silently broke conversation metadata
extraction. Both are the "AI states the wrong time/date" class from BasedHardware#4643
and BasedHardware#6214.

1. utils/llm/chat.py — retrieve_metadata_from_message / _from_text /
   _fields_from_transcript ground "today" with
   `created_at.astimezone(ZoneInfo(tz))`. `tz` originates from
   `get_user_time_zone(uid) or ''` (save_structured_vector), so a user who
   has not set a timezone yields `tz == ''` and `ZoneInfo('')` raises
   ValueError — before the LLM call — on the DEFAULT conversation path
   (_fields_from_transcript). That user's people/topics/entities/dates
   vector metadata is never written, degrading search. The raw astimezone
   also reinterprets a naive created_at as server-local time.
   Fix: delegate to the existing `date_in_tz(created_at, tz)` helper, which
   already falls back to UTC for a missing/invalid tz and treats a naive
   datetime as UTC.

2. utils/conversations/render.py — conversations_to_string rendered
   created_at/started_at/finished_at with `.astimezone(display_tz)` without
   the module's own `_as_utc()` guard (which format_local_time /
   format_local_date already apply for exactly this reason). A naive stored
   timestamp is then presented to the model as server-local wall clock, so
   any non-UTC backend host shows the wrong time in the conversation text
   fed to chat. Fix: wrap each timestamp in `_as_utc()`.

Tests:
- test_conversations_to_string.py: TestConversationsToStringNaiveTimestamps
  forces a non-UTC process TZ (America/Los_Angeles) so the naive-as-local
  defect is deterministic, and asserts naive timestamps render as UTC and
  convert correctly to a user tz. Fails on the pre-fix code.
- test_temporal_date_in_tz.py: locks the date_in_tz contract the chat.py
  fix relies on — empty/None/invalid tz fall back to UTC without raising
  (the exact input that crashed the old expression), and naive datetimes
  are read as UTC.

Verification:
  python -m pytest tests/unit/test_conversations_to_string.py \
    tests/unit/test_temporal_date_in_tz.py -> 19 passed
  Reverting the render _as_utc fix makes the two naive tests fail.
  black --line-length 120 --check: 4 files unchanged.

Relates to BasedHardware#4643, BasedHardware#6214

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @arhxam — this is a genuinely well-scoped first contribution. Clear root-cause write-up, the fix lands exactly where it should, and the contract tests are the right shape. Leaving a positive signal rather than a formal approval for the reasons at the end.

What this fixes, and why it's correct

  • chat.py metadata prompts: created_at.astimezone(ZoneInfo(tz)) raised ValueError whenever tz == '' (users with no saved timezone — the default conversation path), which aborted metadata extraction before the LLM call and silently dropped people/topics/entities/dates vector metadata for those users. It also re-interpreted naive timestamps as server-local. Delegating to date_in_tz(created_at, tz) fixes both: missing/None/invalid tz falls back to UTC, naive datetimes are read as UTC, and it never raises. I confirmed date_in_tz in utils/llm/temporal.py has exactly those guarantees.
  • render.py conversations_to_string: wrapping created_at/started_at/finished_at with _as_utc(...) before .astimezone(display_tz) stops naive stored timestamps being read as the host's local wall clock. _as_utc already exists in render.py and is the same helper used by format_local_time/format_local_date, so this just makes the module consistent.

Verification notes

  • All three chat.py call sites now use date_in_tz(created_at, tz); all three render.py lines use _as_utc(...). Diff matches the description.
  • from zoneinfo import ZoneInfo is still used elsewhere in both files, so there's no dead-import regression.
  • The new tests (test_temporal_date_in_tz.py + TestConversationsToStringNaiveTimestamps) lock the exact invariants the fixes rely on, and forcing TZ=America/Los_Angeles makes the naive-as-local failure deterministic regardless of where the suite runs.

One thing for a human maintainer before merge

  • The only CI signal on this PR is cubic (neutral); the backend pytest suite does not appear to have actually executed, so the new tests haven't been exercised by automation yet. They look correct by inspection, but please confirm the suite runs green (ideally including the two new files) before merging.

No changes requested from my side — flagging needs-maintainer-review purely because this touches user-facing times and the default metadata-extraction path, and a maintainer should be the one to push the merge button. Nice work.


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 needs-maintainer-review Needs a human maintainer to sign off before merge backend Backend Task (python) labels Jul 19, 2026

@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.

Backend timezone fix in conversation metadata/rendering (#4643) with tests. Approve-only — no CI checks ran for contributor.

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @arhxam — this is a clean, well-scoped fix for a real defect class. Quick maintainer notes after reviewing against main:

What this fixes (verified)

  • utils/llm/chat.py — the three metadata-extraction prompts replace created_at.astimezone(ZoneInfo(tz)) with the existing date_in_tz helper. This fixes a crash for timezone-less users: tz == '' (the default path, from get_user_time_zone(uid) or '') made ZoneInfo('') raise ValueError, so the default conversation path silently produced no people/topics/entities/dates vector metadata. It also stops naive created_at from being read as server-local.
  • utils/conversations/render.py — conversations_to_string wraps created_at / started_at / finished_at with the existing _as_utc() helper before .astimezone(display_tz), so naive stored timestamps are treated as UTC rather than server-local.

Both date_in_tz and _as_utc already exist on main and are purpose-built for these defects, so this reuses them rather than reinventing. ZoneInfo is still imported in chat.py because get_user_timezone / get_current_datetime_block use it with their own try/except UTC fallback — those aren't the defect here, so leaving them is correct.

Tests

  • test_temporal_date_in_tz.py locks the empty-string-tz ValueError regression plus None/invalid fallbacks and naive-as-UTC.
  • The conversations_to_string extension forces TZ=America/Los_Angeles via time.tzset() to make the naive-as-server-local defect deterministic, with proper save/restore and a pytest.skip where tzset is unavailable.

Coverage matches the fix surface and would fail on the pre-fix code.

Status
Not approving — this needs a human maintainer sign-off before merge (it touches user-data persistence/retrieval surfaces), so leaving the needs-maintainer-review label in place. The code itself looks correct and minimal.

Two non-blocking notes for a follow-up, not a reason to block or split this PR:

  1. The three metadata prompts still contain the line Do not include dates greater than 2025. This pre-exists on main (not introduced here) and is already stale; worth a separate issue.
  2. The naive-timestamps-as-server-local defect class likely exists at other astimezone call sites across the backend beyond these two modules. This PR fixes the two that feed the chat LLM, which is a coherent slice; a repo-wide sweep would be a natural follow-up.

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

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

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants