Skip to content

fix(stats): 7d cost sparkline was flat on PostgreSQL — DATE() bucket never matched the axis (#2193) - #2194

Merged
vybe merged 4 commits into
devfrom
fix/2193-token-stats-day-bucket
Aug 15, 2026
Merged

vybe merged 4 commits into
devfrom
fix/2193-token-stats-day-bucket

Conversation

@trinity-ability

@trinity-ability trinity-ability commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2193

The bug

The yellow 7-day cost sparkline in the Agent Detail header renders as a flat zero line, while every scalar beside it on the same row is correct — Today $100, ^56% vs avg, Lifetime $1,218 · 1002 runs.

PostgreSQL only. SQLite installs are unaffected, which is why it never showed up locally.

Root cause

get_agent_token_stats (#250) bucketed the 7-day series with a date function on a TEXT column:

SELECT DATE(started_at) as day, ... GROUP BY DATE(started_at)

started_at is an ISO-Z TEXT column (Invariant #16).

  • SQLite — DATE() returns TEXT '2026-08-14'.
  • PostgreSQL — date(x) is the type-name-as-function cast, so psycopg hands back a datetime.date.

The gap-filled axis immediately below is keyed by strftime("%Y-%m-%d") strings:

raw_days = {row["day"]: row for row in day_rows}
...
d = (now_utc - timedelta(days=i)).strftime("%Y-%m-%d")
if d in raw_days:      # str vs datetime.date -> never matches on PG

A str/date dict lookup does not raise — it misses, and a missed bucket is indistinguishable from a day with no executions. So the whole series read as legitimate zeros. The scalar cost_24h / cost_7d / lifetime_* fields come from a different query that never touches DATE(), which is why they stayed right and the failure looked cosmetic rather than like a broken query.

Nothing raised, on either backend.

Verified on a real engine

Same rows, same code, both backends. Pre-fix:

[sqlite]   daily_breakdown = [0.0, 0.0, 0.0, 25.0, 0.0, 40.0, 100.0]   total=165.0
[postgres] daily_breakdown = [0.0, 0.0, 0.0,  0.0, 0.0,  0.0,   0.0]   total=0.0
           (cost_24h=100.0  cost_7d=165.0  lifetime=165.0 on BOTH)

Post-fix both backends return [0.0, 0.0, 0.0, 25.0, 0.0, 40.0, 100.0].

Why it survived this long

This was the last dialect-dependent date function in the backend. Every sibling series already uses the substring idiom — get_agent_analytics (#1107, substr(started_at, 1, 10)), get_fleet_execution_timeline (ent#326), the audit heatmap (Python-side bucketing) — which is why the #1107 Overview chart on the same page renders correctly while this one is flat. #250 predates the convention and was missed by #1540, which repointed the canary collectors at the live engine but not this accessor.

The change

  1. Bucket with the house idiom — substr(started_at, 1, 10), byte-identical to the expression get_agent_analytics already uses, so the two day series cannot drift. Dialect-agnostic, returns text on both backends, and slices the same UTC string the row was written with. Pre-bug: schedule-triggered executions store naive started_at (no timezone suffix) — UI shows wrong relative time #1474 scheduler rows (YYYY-MM-DD HH:MM:SS, space separator) need no special handling: the separator sits at position 11, outside a 10-char slice. (ent#326's hour bucket does wrap the column in replace(..., ' ', 'T') — its 13-char slice spans the separator. An earlier revision of this PR copied that wrapper here on the strength of the similar name; see the correction note below.)
  2. Normalize the join key (_day_bucket_key) so a key-type mismatch can never again read as data. The SQL fix is the fix; this is the belt, because the failure mode here is silent zeros rather than an exception.
  3. Guard the class, not the instance.

On the tests — read this before trusting the green check

db_backend yields SQLite only unless TEST_POSTGRES_URL is set, and no CI workflow sets it. So the nine behavioural cases in this PR cannot catch a reintroduction in CI — on SQLite the broken query passes every one of them. They are the proof on a real engine (run here against PostgreSQL 16; they fail 8/10 against the pre-fix query there), not the guard.

The guard that actually protects the class on SQLite-only CI is TestNoDateFunctionInDayBucket, an AST check over the SQL string literals the accessor issues, plus the pure _day_bucket_key normalizer exercised with the datetime.date a PG driver returns. It reads literals rather than source text on purpose: the first draft grepped the function source and failed against its own comment explaining the bug — a guard that fires on its own rationale is one nobody keeps. A meta-test pins that property so a later "simplification" back to a grep can't pass silently.

Verification that the suite is not vacuous:

pre-fix post-fix
SQLite (CI default) 8 failed, 9 passed 17 passed
SQLite + PostgreSQL 8 failed (PG behavioural) 26 passed

Neighbouring suites unaffected: test_1771c_schedules_analytics_edges, test_agent_analytics, test_schedule_analytics, test_1115_schedules_summary — 101 passed. Broader -k "schedule or stats or executions or timeline" sweep on the working branch: 680 passed.

Correction after review

/code-review was run on this branch after the first push and caught a real error, kept here rather than force-pushed away because the reasoning is the point:

The day bucket originally shipped as substr(replace(started_at, ' ', 'T'), 1, 10). The replace is a provable no-op for a 10-character slice — the separator is at position 11 — and its rationale had been transplanted from ent#326's hour bucket, where the 13-char slice genuinely spans it. Verified in Python and SQLite across ISO-Z, space-separator and +00:00 shapes: identical output with and without.

It was not merely redundant. The AST guard asserted "substr(replace(started_at" in sql, so the guard rejected substr(started_at, 1, 10) — the codebase's own idiom — and would have handed anyone normalizing the three copies a red check with a false reason. The claim had also propagated into the feature-flow doc and a test billed as its coverage that passed identically without it.

Also fixed from the same review:

  • The guard now sweeps the whole db/schedules/ package, not one accessor. Per-accessor scoping protects the instance, not the class — and fix: Replace budget display with actual token usage tracking #250 surviving Canary invariant harness is blind on PostgreSQL — reads stale SQLite /data/trinity.db #1540 is exactly that failure. Matching moved from literal prefixes to a \b-anchored regex, catching the alias / whitespace / CAST / ::date evasions a prefix match misses (the \b keeps update( from reading as date().
  • Two cases were clock-flaky — rows at now-2h/now-1h asserted against the last axis slot, which is a different day when CI runs between 00:00–02:00 UTC (~8% of clock positions). They now resolve the bucket by its own UTC date. Simulated at 00:30Z: the old assertion reads 0.0 against an expected 100.0; the new one holds.
  • test_the_guard_reads_sql_not_prose asserted on the wording of a source comment; it now proves the extractor property against a synthetic module.
  • _day_bucket_key's docstring overclaimed ("degrades to correct"); the call site is a dict comprehension, so colliding sub-day buckets would be last-wins. It now states the guarantee it actually provides.
  • Removed a dead local re-import shadowing the module-level datetime import.

Three pre-existing defects the review surfaced in this accessor are filed as #2203 rather than folded in — the 168h-vs-7-calendar-day axis skew, the status IN ('success','failed') filter dropping legacy error rows its siblings count, and avg_daily_cost including today while its comment says it excludes it. None was introduced here; #2 and #3 change displayed spend figures and want their own review.

Scope

Backend + the feature-flow doc that documented the broken query (token-usage-display.md stated GROUP BY DATE(started_at) as the bucketer — the line that would lead the next person to reintroduce it, sitting directly above an Invariant #16 note that covered only the cutoff half). No frontend change (AgentHeader.vue and SparklineChart.vue were drawing exactly the zeros they were handed). No schema change, so no migration on either track. Swept the rest of src/backend and src/scheduler for the same class — no other SQL date functions remain, and get_agent_analytics's Python-side .date().isoformat() axis already joins string-to-string.

🤖 Generated with Claude Code

trinity-ability and others added 2 commits August 14, 2026 20:41
…never matched the axis (#2193)

The agent-header sparkline rendered a flat zero line while every scalar
beside it on the same row was correct (`Today $100`, `^56% vs avg`,
`Lifetime $1,218 · 1002 runs`). PostgreSQL only; SQLite installs were
unaffected, which is why it never showed locally.

`get_agent_token_stats` bucketed the 7-day series with `DATE(started_at)`
on an ISO-Z TEXT column. On SQLite that returns TEXT; on PostgreSQL
`date(x)` is the type-name-as-function cast, so psycopg hands back a
`datetime.date`. The gap-filled axis right below is keyed by
`strftime("%Y-%m-%d")` strings — and a `str`/`date` dict lookup does not
raise, it MISSES. A missed bucket is indistinguishable from a day with no
executions, so the whole series read as legitimate zeros. The scalar
fields come from a different query that never touches `DATE()`, which is
why they stayed right and the failure looked cosmetic.

Verified on both engines with identical rows: pre-fix PostgreSQL returned
`[0,0,0,0,0,0,0]` against `cost_7d=165.0`; both backends now return
`[0,0,0,25.0,0,40.0,100.0]`.

This was the last dialect-dependent date function in the backend. Every
sibling series already uses the substring idiom — `get_agent_analytics`
(#1107), `get_fleet_execution_timeline` (ent#326), the audit heatmap
(Python-side) — so the #1107 Overview chart on the *same page* rendered
correctly while this one was flat. #250 predates the convention and was
missed by #1540, which repointed the canary collectors at the live engine
but not this accessor.

- bucket with `substr(replace(started_at, ' ', 'T'), 1, 10)`; `replace`
  keeps pre-#1474 space-separator rows in their day instead of dropping
  them from the chart alone, having been counted by the scalar query
- normalize the join key (`_day_bucket_key`) so a key-type mismatch can
  never again read as data rather than raise
- guard the class, not the instance: unit tests are SQLite-only unless
  `TEST_POSTGRES_URL` is set and no workflow sets it, so the behavioural
  cases pass vacuously in CI. The AST guard on the accessor's SQL
  literals is what actually catches a reintroduction. It reads literals,
  not source text — the first draft grepped the source and failed against
  its own comment explaining the bug.

Fixes #2193

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The `ops` fixture evicts `db.*` so `from db.schedules import ...` re-imports
against the harness-bound engine. That eviction is deliberate and cannot be a
`monkeypatch.delitem` — it records no undo for a key absent on entry, so the
harness-bound module would stay resident for later files.

The escape hatch the lint recognises is the `_STUBBED_MODULE_NAMES` +
`_restore_sys_modules` pair; the file had only the second half.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@github-actions

Copy link
Copy Markdown

⚠️ Nightly unit-suite check skipped — merge conflict against dev.

Resolve by running git merge dev locally and pushing the result. The next nightly run will re-test once the conflict is gone.

trinity-ability and others added 2 commits August 15, 2026 09:06
`token-usage-display.md` stated `GROUP BY DATE(started_at)` as the per-day
bucketer — the exact SQL the fix removes, and the line that would lead the
next person to reintroduce it. It also carried a "Time-window invariant"
note citing Invariant #16 for the *cutoff* while the *bucket* beside it
violated the same principle.

The invariant note now covers both halves and records why: the dialect
split, the str/date lookup that misses instead of raising, and why the
behavioural tests cannot catch a reintroduction on SQLite-only CI.

Also corrects the DB-method path, stale since the #1481 package split
(`db/schedules.py` -> `db/schedules/stats.py`) — same heading, so left
wrong it would send a reader to a file that no longer exists.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Code review caught that the `replace(started_at, ' ', 'T')` I wrapped the
day bucket in is a provable no-op, and that its ~6-line rationale was
transplanted from ent#326's HOUR bucket where it IS load-bearing. The
separator sits at position 11; a 10-char slice never reaches it.
Verified in both Python and SQLite: identical output for ISO-Z,
space-separator and `+00:00` shapes, with and without.

That mattered beyond tidiness in three ways:

* The AST guard asserted `"substr(replace(started_at" in sql`, so it
  REJECTED `substr(started_at, 1, 10)` — the codebase's own idiom, used by
  `get_agent_analytics` — and would have handed anyone normalizing the
  three copies a red check with a false reason.
* It made this expression a third divergent spelling of one concept. It is
  now byte-identical to analytics.py's, so the two day series cannot drift.
* The false claim had been repeated into the commit message, the PR body,
  the feature-flow doc and a test docstring, and
  `test_pre_1474_space_separator_row_is_bucketed_not_dropped` was billed as
  its coverage while passing identically without it — a test that cannot
  fail when its subject is deleted. Its docstring now states what it does
  and does not discriminate.

Also from the same review:

* The guard now sweeps every SQL literal in `db/schedules/` instead of one
  accessor, so a new accessor inherits it. Per-accessor scoping protects
  the instance, not the class, and #250 surviving #1540 is exactly that
  failure. Matching moved from literal prefixes to a `\b`-anchored regex,
  which catches the alias/whitespace/CAST/`::date` evasions the prefix
  match missed (the `\b` keeps `update(` from reading as `date(`).
* `test_the_guard_reads_sql_not_prose` asserted on the wording of a source
  comment, so rewording the explanation went red. It now proves the
  extractor property against a synthetic module.
* Two cases were clock-flaky: they placed rows at `now-2h`/`now-1h` and
  asserted on the LAST axis slot, which is a different day when CI runs
  between 00:00 and 02:00 UTC (~8% of positions). They now resolve the
  bucket by its own UTC date. Simulated at 00:30Z: the old assertion reads
  0.0 against an expected 100.0; the new one holds.
* `_day_bucket_key`'s docstring promised it "degrades to correct" under a
  future dialect change. The call site is a dict comprehension, so colliding
  sub-day buckets would be last-wins, not summed. The docstring now states
  the guarantee it actually provides and why the current bucket cannot
  collide.
* Removed a dead local re-import of datetime/timezone/timedelta shadowing
  the module-level one.

Pre-existing defects the review surfaced in this accessor are filed
separately rather than folded in: the rolling-168h vs 7-calendar-day axis
skew, the `status IN ('success','failed')` filter dropping legacy `error`
rows its siblings count, and `avg_daily_cost` including today while its
comment says it excludes it.

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

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Validated via /validate-pr. All 21 checks green; merges clean against dev@58df9aed (the nightly bot's conflict comment is a stale false positive — branch is 0 commits behind dev).

The fix is one expression, but the test design is what earns the merge: the PR states outright that CI is SQLite-only unless TEST_POSTGRES_URL is set, so the behavioural cases cannot catch a reintroduction — and then builds the guard that can (AST sweep over SQL string literals across the whole db/schedules/ package, \b-anchored, catching the alias/whitespace/::date/to_date evasions a prefix match misses). Package-scoped rather than accessor-scoped, because #250 surviving #1540 is exactly what per-accessor scoping fails to prevent.

The on-branch /code-review correction is kept in history rather than force-pushed away, and it caught a real one: the transplanted replace(...) no-op that the guard itself asserted on, which would have rejected the codebase's own idiom with a false reason. Two clock-flaky assertions fixed alongside.

The three pre-existing defects in this accessor being filed as #2203 rather than folded in is the right call — two of them move displayed spend figures.

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.

2 participants