Skip to content

Fix UTC day bucketing and a lying cast in the API read path - #714

Merged
anshss merged 1 commit into
mainfrom
fix-day-bucketing
Aug 9, 2026
Merged

anshss merged 1 commit into
mainfrom
fix-day-bucketing

Conversation

@anshss

@anshss anshss commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Summary

Two timestamp-correctness fixes, both outside the ingest path:

  1. UTC day bucketing. Three sites used a bare CAST(start_time AS DATE) on the TIMESTAMPTZ column: get_cost_summary's day grouping (and its default fallback for an unrecognised group_by), and the optimize report's active_days count. A bare cast resolves through the session's local timezone before truncating, so on a machine running ahead of UTC, spans logged late in the UTC day get stamped with tomorrow's date. That means tj cost --group-by day silently disagrees with any UTC-based figure elsewhere, and active_days (which every per-day extrapolation in the optimize report divides by) is off by one near local midnight. Fixed by switching to CAST(start_time AT TIME ZONE 'UTC' AS DATE), matching the convention already used elsewhere in the codebase (core/data_span.py, api/routes/analytics.py, api/routes/cost.py).

  2. A cast() in the HTTP-API fallback backend that lied to the type checker. ApiBackend._dict_to_span (used when tj serve holds the DuckDB write lock) built a NormalizedSpan with start_time=cast(datetime, ... or None). NormalizedSpan.start_time (and TraceRecord.start_time, which had the identical pattern in get_traces) is declared non-Optional by design — the header comment on the field says ingest already rejects any span with no observed time rather than substituting a default. The cast() didn't convert anything; it just told the type checker to stop looking while a None could flow through, leaving every downstream consumer of an HTTP-fallback span unguarded.

    Decision: a start_time is required here, not optional. A span the daemon serializes always has a real start_time (ingest enforces it), so a missing/unparseable value in the wire payload means the response itself is malformed, not that the field is legitimately absent. I raise a ValueError naming the offending record instead of casting a None past the checker, and factored the shared logic into _require_start_time() since get_traces had the exact same bug for TraceRecord.

Tests

  • tests/integration/test_db.py::test_get_cost_summary_by_day_buckets_on_the_utc_date — parametrized over UTC/Asia-Kolkata/America-Los_Angeles session timezones.
  • tests/unit/test_optimize.py::test_summarize_window_active_days_buckets_on_the_utc_date — same parametrization, two spans straddling UTC midnight.
  • tests/unit/test_api_backend_span_deserialize.py — new file covering the present/missing/absent-key start_time contract for _dict_to_span and _require_start_time.

I confirmed both new day-bucketing tests fail against the pre-fix bare CAST(... AS DATE) (reverted each site locally, ran red, restored, ran green) before finalizing.

CI

ruff check and mypy pass on all touched files. Ran the touched test files plus the broader db/optimize/mcp/proxy/storage-parity suites locally (183 passed); did not run the full suite (that's what remote CI is for).

Deliberately not done

  • Did not widen the sweep beyond the three named sites plus the one get_traces cast — a full-repo grep for CAST(... AS DATE) on timestamp columns turned up no other bare occurrences; everything else already used the AT TIME ZONE 'UTC' form.

Three bare CAST(start_time AS DATE) sites in cost-summary grouping and
active-days counting bucketed by the session's local timezone instead of
UTC, disagreeing with every other day-bucketed figure in the codebase on
a non-UTC machine. Switched them to CAST(... AT TIME ZONE 'UTC' AS DATE),
matching the existing convention, and added parametrized timezone tests
that fail against the old bare cast.

Also removed a cast() in the HTTP-API fallback backend that silently let
a missing start_time flow through as a typed datetime, defeating type
checking for every downstream consumer. Both start_time fields are
non-Optional by design (ingest already rejects timeless spans), so a
missing value from the wire now raises instead of passing None through.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@anshss
anshss requested a review from anilmurty as a code owner August 9, 2026 08:00
@greptile-apps

greptile-apps Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR corrects UTC day bucketing in cost and optimization queries and makes API timestamp deserialization enforce the models’ required start_time contract.

  • Converts TIMESTAMPTZ values to UTC before deriving calendar dates.
  • Replaces type-only casts with a shared fail-fast timestamp parser.
  • Adds regression coverage for multiple session timezones and malformed API records.

Confidence Score: 5/5

The PR appears safe to merge with no actionable defects identified.

The UTC conversions match the stored TIMESTAMPTZ semantics and established query convention, while strict API deserialization enforces an existing non-null timestamp invariant.

Important Files Changed

Filename Overview
tokenjam/core/api_backend.py Replaces casts that could conceal None with a shared parser consistent with the required model and database contract.
tokenjam/core/db.py Makes cost-summary day grouping independent of the DuckDB session timezone.
tokenjam/core/optimize/runner.py Counts active days using distinct UTC calendar dates.
tests/integration/test_db.py Adds cost-summary regression coverage across UTC and non-UTC session timezones.
tests/unit/test_optimize.py Verifies that spans straddling UTC midnight count as two active days regardless of session timezone.
tests/unit/test_api_backend_span_deserialize.py Covers valid, null, and absent API timestamp payloads and verifies identifying error messages.

Reviews (1): Last reviewed commit: "Fix UTC day bucketing and a lying cast i..." | Re-trigger Greptile

@anshss

anshss commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

Bundled — this lands via #715, which now carries every commit from this branch. Leaving this PR open on purpose: once the anchor merges (as a merge commit, not a squash), this one flips to Merged automatically because its head SHA stays an ancestor of main.

Please don't push to this branch in the meantime. A new commit here changes the head SHA, breaks that ancestry, and strands this PR open with a stale diff.

@anshss
anshss merged commit c1a8353 into main Aug 9, 2026
7 checks passed
@anilmurty
anilmurty deleted the fix-day-bucketing branch September 18, 2026 21:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant