Skip to content

Commit 8b96a59

Browse files
committed
fix rollup lookback condition
1 parent d3baa06 commit 8b96a59

File tree

3 files changed

+34
-12
lines changed

3 files changed

+34
-12
lines changed

coderd/database/dbmem/dbmem.go

+20-6
Original file line numberDiff line numberDiff line change
@@ -7963,23 +7963,37 @@ func (q *FakeQuerier) UpsertTemplateUsageStats(ctx context.Context) error {
79637963
/*
79647964
latest_start AS (
79657965
SELECT
7966-
COALESCE(
7967-
MAX(start_time) - '1 hour'::interval,
7968-
-- TODO(mafredri): Fix this, required for tests to pass.
7969-
NOW() - '2 years'::interval
7970-
) AS t
7966+
-- Truncate to hour so that we always look at even ranges of data.
7967+
date_trunc('hour', COALESCE(
7968+
MAX(start_time) - '1 hour'::interval),
7969+
-- Fallback when there are no template usage stats yet.
7970+
-- App stats can exist before this, but not agent stats,
7971+
-- limit the lookback to avoid inconsistency.
7972+
(SELECT MIN(created_at) FROM workspace_agent_stats)
7973+
)) AS t
79717974
FROM
79727975
template_usage_stats
79737976
),
79747977
*/
79757978

79767979
now := time.Now()
7977-
latestStart := now.AddDate(-2, 0, 0)
7980+
latestStart := time.Time{}
79787981
for _, stat := range q.templateUsageStats {
79797982
if stat.StartTime.After(latestStart) {
79807983
latestStart = stat.StartTime.Add(-time.Hour)
79817984
}
79827985
}
7986+
if latestStart.IsZero() {
7987+
for _, stat := range q.workspaceAgentStats {
7988+
if latestStart.IsZero() || stat.CreatedAt.Before(latestStart) {
7989+
latestStart = stat.CreatedAt
7990+
}
7991+
}
7992+
}
7993+
if latestStart.IsZero() {
7994+
return nil
7995+
}
7996+
latestStart = latestStart.Truncate(time.Hour)
79837997

79847998
/*
79857999
workspace_app_stat_buckets AS (

coderd/database/queries.sql.go

+7-3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

coderd/database/queries/insights.sql

+7-3
Original file line numberDiff line numberDiff line change
@@ -347,10 +347,14 @@ WHERE
347347
WITH
348348
latest_start AS (
349349
SELECT
350-
COALESCE(
350+
-- Truncate to hour so that we always look at even ranges of data.
351+
date_trunc('hour', COALESCE(
351352
MAX(start_time) - '1 hour'::interval,
352-
NOW() - '6 months'::interval
353-
) AS t
353+
-- Fallback when there are no template usage stats yet.
354+
-- App stats can exist before this, but not agent stats,
355+
-- limit the lookback to avoid inconsistency.
356+
(SELECT MIN(created_at) FROM workspace_agent_stats)
357+
)) AS t
354358
FROM
355359
template_usage_stats
356360
),

0 commit comments

Comments
 (0)