Skip to content

Commit 49e0900

Browse files
committed
fix(usage): handle Daylight saving time (DST) hour boundaries
1 parent 7a23b2d commit 49e0900

3 files changed

Lines changed: 307 additions & 36 deletions

File tree

Lines changed: 251 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,251 @@
1+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
2+
import { __test, buildPeakErrorHours } from "./usage-metrics.ts";
3+
import { renderUsage } from "./usage.ts";
4+
import type { UsageColumnId, UsageSessionEntry } from "./usageTypes.ts";
5+
6+
const ORIGINAL_TZ = process.env.TZ;
7+
8+
function makeSession(startIso: string, endIso: string): UsageSessionEntry {
9+
const firstActivity = new Date(startIso).getTime();
10+
const lastActivity = new Date(endIso).getTime();
11+
return {
12+
key: `${startIso}-${endIso}`,
13+
updatedAt: lastActivity,
14+
usage: {
15+
input: 0,
16+
output: 0,
17+
cacheRead: 0,
18+
cacheWrite: 0,
19+
totalTokens: 100,
20+
totalCost: 1,
21+
inputCost: 0,
22+
outputCost: 0,
23+
cacheReadCost: 0,
24+
cacheWriteCost: 0,
25+
missingCostEntries: 0,
26+
firstActivity,
27+
lastActivity,
28+
durationMs: lastActivity - firstActivity,
29+
messageCounts: {
30+
total: 100,
31+
user: 50,
32+
assistant: 50,
33+
toolCalls: 0,
34+
toolResults: 0,
35+
errors: 10,
36+
},
37+
},
38+
};
39+
}
40+
41+
function makeUsageProps(sessions: UsageSessionEntry[], selectedHours: number[] = []) {
42+
const totals = sessions.reduce(
43+
(acc, session) => {
44+
const usage = session.usage;
45+
if (!usage) {
46+
return acc;
47+
}
48+
acc.input += usage.input;
49+
acc.output += usage.output;
50+
acc.cacheRead += usage.cacheRead;
51+
acc.cacheWrite += usage.cacheWrite;
52+
acc.totalTokens += usage.totalTokens;
53+
acc.totalCost += usage.totalCost;
54+
acc.inputCost += usage.inputCost;
55+
acc.outputCost += usage.outputCost;
56+
acc.cacheReadCost += usage.cacheReadCost;
57+
acc.cacheWriteCost += usage.cacheWriteCost;
58+
acc.missingCostEntries += usage.missingCostEntries;
59+
return acc;
60+
},
61+
{
62+
input: 0,
63+
output: 0,
64+
cacheRead: 0,
65+
cacheWrite: 0,
66+
totalTokens: 0,
67+
totalCost: 0,
68+
inputCost: 0,
69+
outputCost: 0,
70+
cacheReadCost: 0,
71+
cacheWriteCost: 0,
72+
missingCostEntries: 0,
73+
},
74+
);
75+
76+
return {
77+
data: {
78+
loading: false,
79+
error: null,
80+
sessions,
81+
sessionsLimitReached: false,
82+
totals,
83+
aggregates: {
84+
messages: {
85+
total: 100,
86+
user: 50,
87+
assistant: 50,
88+
toolCalls: 0,
89+
toolResults: 0,
90+
errors: 10,
91+
},
92+
tools: { totalCalls: 0, uniqueTools: 0, tools: [] },
93+
byModel: [],
94+
byProvider: [],
95+
byAgent: [],
96+
byChannel: [],
97+
daily: [],
98+
},
99+
costDaily: [],
100+
},
101+
filters: {
102+
startDate: "2026-04-05",
103+
endDate: "2026-04-05",
104+
selectedSessions: [],
105+
selectedDays: [],
106+
selectedHours,
107+
query: "",
108+
queryDraft: "",
109+
timeZone: "local" as const,
110+
},
111+
display: {
112+
chartMode: "tokens" as const,
113+
dailyChartMode: "total" as const,
114+
sessionSort: "tokens" as const,
115+
sessionSortDir: "desc" as const,
116+
recentSessions: [],
117+
sessionsTab: "all" as const,
118+
visibleColumns: [
119+
"channel",
120+
"agent",
121+
"provider",
122+
"model",
123+
"messages",
124+
"tools",
125+
"errors",
126+
"duration",
127+
] as UsageColumnId[],
128+
contextExpanded: false,
129+
headerPinned: false,
130+
},
131+
detail: {
132+
timeSeriesMode: "cumulative" as const,
133+
timeSeriesBreakdownMode: "total" as const,
134+
timeSeries: null,
135+
timeSeriesLoading: false,
136+
timeSeriesCursorStart: null,
137+
timeSeriesCursorEnd: null,
138+
sessionLogs: null,
139+
sessionLogsLoading: false,
140+
sessionLogsExpanded: false,
141+
logFilters: {
142+
roles: [],
143+
tools: [],
144+
hasTools: false,
145+
query: "",
146+
},
147+
},
148+
callbacks: {
149+
filters: {
150+
onStartDateChange() {},
151+
onEndDateChange() {},
152+
onRefresh() {},
153+
onTimeZoneChange() {},
154+
onToggleHeaderPinned() {},
155+
onSelectDay() {},
156+
onSelectHour() {},
157+
onClearDays() {},
158+
onClearHours() {},
159+
onClearSessions() {},
160+
onClearFilters() {},
161+
onQueryDraftChange() {},
162+
onApplyQuery() {},
163+
onClearQuery() {},
164+
},
165+
display: {
166+
onChartModeChange() {},
167+
onDailyChartModeChange() {},
168+
onSessionSortChange() {},
169+
onSessionSortDirChange() {},
170+
onSessionsTabChange() {},
171+
onToggleColumn() {},
172+
},
173+
details: {
174+
onToggleContextExpanded() {},
175+
onToggleSessionLogsExpanded() {},
176+
onLogFilterRolesChange() {},
177+
onLogFilterToolsChange() {},
178+
onLogFilterHasToolsChange() {},
179+
onLogFilterQueryChange() {},
180+
onLogFilterClear() {},
181+
onSelectSession() {},
182+
onTimeSeriesModeChange() {},
183+
onTimeSeriesBreakdownChange() {},
184+
onTimeSeriesCursorRangeChange() {},
185+
},
186+
},
187+
};
188+
}
189+
190+
describe("usage DST hour boundaries", () => {
191+
beforeEach(() => {
192+
process.env.TZ = "Australia/Sydney";
193+
});
194+
195+
afterEach(() => {
196+
if (ORIGINAL_TZ === undefined) {
197+
delete process.env.TZ;
198+
} else {
199+
process.env.TZ = ORIGINAL_TZ;
200+
}
201+
});
202+
203+
it("moves forward through the repeated hour at DST fallback", () => {
204+
const current = new Date("2026-04-05T02:00:00+10:00");
205+
const next = __test.getNextHourStart(current, "local");
206+
207+
expect(next.getTime()).toBeGreaterThan(current.getTime());
208+
expect(next.getTime()).toBe(new Date("2026-04-05T03:00:00+10:00").getTime());
209+
});
210+
211+
it("skips the missing hour at DST spring forward", () => {
212+
const current = new Date("2026-10-04T01:30:00+10:00");
213+
const next = __test.getNextHourStart(current, "local");
214+
215+
expect(next.getTime()).toBe(new Date("2026-10-04T03:00:00+11:00").getTime());
216+
});
217+
218+
it(
219+
"builds peak error stats for sessions that span the fallback rollover",
220+
{ timeout: 1_000 },
221+
() => {
222+
const stats = buildPeakErrorHours(
223+
[makeSession("2026-04-05T02:30:00+11:00", "2026-04-05T02:30:00+10:00")],
224+
"local",
225+
);
226+
227+
// Vitest runs this file in a worker thread, so runtime TZ changes are not
228+
// guaranteed to alter the worker's local timezone on every host. The same
229+
// instant range can appear as one Sydney repeated-hour bucket or two
230+
// ordinary buckets elsewhere, but every bucket must preserve the rate.
231+
expect(stats.length).toBeGreaterThan(0);
232+
expect(stats.length).toBeLessThanOrEqual(2);
233+
expect(stats.every((entry) => entry.value === "10.00%")).toBe(true);
234+
},
235+
);
236+
237+
it(
238+
"renders the usage view with an hour filter across the fallback rollover",
239+
{ timeout: 1_000 },
240+
() => {
241+
const result = renderUsage(
242+
makeUsageProps(
243+
[makeSession("2026-04-05T02:30:00+11:00", "2026-04-05T02:30:00+10:00")],
244+
[2],
245+
),
246+
);
247+
248+
expect(result).toBeTruthy();
249+
},
250+
);
251+
});

‎ui/src/ui/views/usage-metrics.ts‎

Lines changed: 52 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -56,19 +56,20 @@ function forEachSessionHourSlice(
5656
const durationMs = Math.max(endMs - startMs, 1);
5757
const totalMinutes = durationMs / 60000;
5858

59+
// Use half-open slices [cursor, nextBoundary) so exact hour boundaries do
60+
// not create zero-duration buckets and DST transitions remain monotonic.
5961
let cursor = startMs;
6062
while (cursor < endMs) {
6163
const date = new Date(cursor);
62-
const nextHour = setToHourEnd(date, timeZone);
63-
const nextMs = Math.min(nextHour.getTime(), endMs);
64+
const nextMs = getNextHourBoundaryMs(cursor, endMs, timeZone);
6465
const minutes = Math.max((nextMs - cursor) / 60000, 0);
6566
visitor({
6667
usage,
6768
hour: getZonedHour(date, timeZone),
6869
weekday: getZonedWeekday(date, timeZone),
6970
share: minutes / totalMinutes,
7071
});
71-
cursor = nextMs + 1;
72+
cursor = nextMs;
7273
}
7374

7475
return true;
@@ -125,16 +126,56 @@ function getZonedWeekday(date: Date, zone: "local" | "utc"): number {
125126
return zone === "utc" ? date.getUTCDay() : date.getDay();
126127
}
127128

128-
function setToHourEnd(date: Date, zone: "local" | "utc"): Date {
129+
function getNextHourStart(date: Date, zone: "local" | "utc"): Date {
129130
const next = new Date(date);
130131
if (zone === "utc") {
131-
next.setUTCMinutes(59, 59, 999);
132+
next.setUTCHours(next.getUTCHours() + 1, 0, 0, 0);
132133
} else {
133-
next.setMinutes(59, 59, 999);
134+
// Advance in local wall time so repeated and skipped hours are handled by
135+
// the runtime's timezone rules instead of reconstructing an ambiguous end.
136+
next.setHours(next.getHours() + 1, 0, 0, 0);
134137
}
135138
return next;
136139
}
137140

141+
function getNextHourBoundaryMs(cursor: number, endMs: number, zone: "local" | "utc"): number {
142+
const nextStartMs = getNextHourStart(new Date(cursor), zone).getTime();
143+
const boundedNextMs = Math.min(nextStartMs, endMs);
144+
// Guard against non-monotonic timezone transitions so the UI never stalls.
145+
return boundedNextMs > cursor ? boundedNextMs : endMs;
146+
}
147+
148+
function sessionTouchesHours(
149+
session: UsageSessionEntry,
150+
timeZone: "local" | "utc",
151+
hours: number[],
152+
): boolean {
153+
if (hours.length === 0) {
154+
return true;
155+
}
156+
157+
const usage = session.usage;
158+
const start = usage?.firstActivity ?? session.updatedAt;
159+
const end = usage?.lastActivity ?? session.updatedAt;
160+
if (!start || !end) {
161+
return false;
162+
}
163+
164+
const startMs = Math.min(start, end);
165+
const endMs = Math.max(start, end);
166+
let cursor = startMs;
167+
168+
while (true) {
169+
if (hours.includes(getZonedHour(new Date(cursor), timeZone))) {
170+
return true;
171+
}
172+
if (cursor >= endMs) {
173+
return false;
174+
}
175+
cursor = getNextHourBoundaryMs(cursor, endMs, timeZone);
176+
}
177+
}
178+
138179
function buildUsageMosaicStats(
139180
sessions: UsageSessionEntry[],
140181
timeZone: "local" | "utc",
@@ -610,6 +651,10 @@ const buildUsageInsightStats = (
610651
};
611652
};
612653

654+
export const __test = {
655+
getNextHourStart,
656+
};
657+
613658
export type { UsageInsightStats };
614659
export {
615660
buildAggregatesFromSessions,
@@ -624,5 +669,5 @@ export {
624669
formatTokens,
625670
getZonedHour,
626671
renderUsageMosaic,
627-
setToHourEnd,
672+
sessionTouchesHours,
628673
};

0 commit comments

Comments
 (0)