Repository navigation
Fix UTC day bucketing and a lying cast in the API read path - #714
Conversation
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]>
|
| 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
|
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 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. |
Summary
Two timestamp-correctness fixes, both outside the ingest path:
UTC day bucketing. Three sites used a bare
CAST(start_time AS DATE)on theTIMESTAMPTZcolumn:get_cost_summary'sdaygrouping (and its default fallback for an unrecognisedgroup_by), and the optimize report'sactive_dayscount. 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 meanstj cost --group-by daysilently disagrees with any UTC-based figure elsewhere, andactive_days(which every per-day extrapolation in the optimize report divides by) is off by one near local midnight. Fixed by switching toCAST(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).A
cast()in the HTTP-API fallback backend that lied to the type checker.ApiBackend._dict_to_span(used whentj serveholds the DuckDB write lock) built aNormalizedSpanwithstart_time=cast(datetime, ... or None).NormalizedSpan.start_time(andTraceRecord.start_time, which had the identical pattern inget_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. Thecast()didn't convert anything; it just told the type checker to stop looking while aNonecould flow through, leaving every downstream consumer of an HTTP-fallback span unguarded.Decision: a
start_timeis required here, not optional. A span the daemon serializes always has a realstart_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 aValueErrornaming the offending record instead of casting aNonepast the checker, and factored the shared logic into_require_start_time()sinceget_traceshad the exact same bug forTraceRecord.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-keystart_timecontract for_dict_to_spanand_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 checkandmypypass 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
get_tracescast — a full-repo grep forCAST(... AS DATE)on timestamp columns turned up no other bare occurrences; everything else already used theAT TIME ZONE 'UTC'form.