From f81ebe3c6a8af0303496d9ba3ac0926a2f8d5ddd Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 19:36:43 +0100 Subject: [PATCH 1/2] fix(store): statistic windows keep their whole buckets, and days are UTC Tag and turn statistics read every bucket the window touches, as the rollups do, instead of comparing bucket starts with the window's ends. Every date_trunc names UTC, so a day does not follow the server's zone. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/store/bucket.go | 8 +-- acceleration/internal/store/bucket_test.go | 58 ++++++++++++++++++- acceleration/internal/store/request.go | 2 +- acceleration/internal/store/store.go | 10 ++-- acceleration/internal/store/tag_bucket.go | 8 +-- .../internal/store/tag_bucket_test.go | 16 +++++ acceleration/internal/store/turn_bucket.go | 17 +++--- .../internal/store/turn_bucket_test.go | 13 +++++ 8 files changed, 108 insertions(+), 24 deletions(-) diff --git a/acceleration/internal/store/bucket.go b/acceleration/internal/store/bucket.go index 478961171b..8cf6a5d9ef 100644 --- a/acceleration/internal/store/bucket.go +++ b/acceleration/internal/store/bucket.go @@ -114,8 +114,8 @@ func (r *Buckets) Rollup(ctx context.Context, granularity Granularity, from, to // from and to as its two parameters. Postgres keeps timestamps to the microsecond, so to // less one is the window's last instant. func wholeBuckets(granularity Granularity, column string) string { - return fmt.Sprintf("%[1]s >= date_trunc('%[2]s', ?::timestamptz) AND %[1]s < "+ - "date_trunc('%[2]s', ?::timestamptz - interval '1 microsecond') + interval '1 %[2]s'", + return fmt.Sprintf("%[1]s >= date_trunc('%[2]s', ?::timestamptz, 'UTC') AND %[1]s < "+ + "date_trunc('%[2]s', ?::timestamptz - interval '1 microsecond', 'UTC') + interval '1 %[2]s'", column, granularity.truncateUnit()) } @@ -135,7 +135,7 @@ SELECT customer_id, provider, model, - date_trunc('%[2]s', started_at) AS bucket, + date_trunc('%[2]s', started_at, 'UTC') AS bucket, COALESCE(SUM(audio_ms), 0), COALESCE(SUM(characters), 0), COALESCE(SUM(input_tokens), 0), @@ -205,7 +205,7 @@ SELECT customer_id, provider, model, - date_trunc('%[1]s', started_at) AS bucket, + date_trunc('%[1]s', started_at, 'UTC') AS bucket, COALESCE(SUM(audio_ms), 0) AS audio_ms_total, COALESCE(SUM(characters), 0) AS characters_total, COALESCE(SUM(input_tokens), 0) AS input_tokens_total, diff --git a/acceleration/internal/store/bucket_test.go b/acceleration/internal/store/bucket_test.go index db03e83d1b..35b0ab08dc 100644 --- a/acceleration/internal/store/bucket_test.go +++ b/acceleration/internal/store/bucket_test.go @@ -2,7 +2,11 @@ package store -import "time" +import ( + "time" + + "github.com/uptrace/bun" +) func (s *StoreSuite) TestRollupAggregatesRequestsIntoOneBucket() { s.record("acme", s.base.Add(1*time.Minute), 1000, 100, true) @@ -213,6 +217,58 @@ func (s *StoreSuite) TestDailyRollupOverAnHourRecomputesTheWholeDay() { s.EqualValues(3000, buckets[0].AudioMsTotal, "the day keeps the request outside the hour asked for") } +func (s *StoreSuite) TestADayIsAUTCDayWhateverTheDatabasesTimeZone() { + // 03:00 UTC is the evening before in Denver, and 10:00 UTC the same morning. + early, late := time.Date(2026, 3, 1, 3, 0, 0, 0, time.UTC), s.base + s.record("acme", early, 1000, 100, true) + s.record("acme", late, 2000, 100, true) + s.Require().NoError(s.store.TurnBuckets.Add(s.ctx, s.turn(early, 100))) + s.Require().NoError(s.store.TurnBuckets.Add(s.ctx, s.turn(late, 100))) + denver := s.inTimeZone("America/Denver") + day := time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC) + from, to := day.Add(-24*time.Hour), day.Add(48*time.Hour) + + requests, err := denver.Buckets.Select(s.ctx, "acme", BucketFilter{Modality: "stt", Granularity: Daily, From: from, To: to}) + s.Require().NoError(err) + s.Require().Len(requests, 1) + s.Equal(day, requests[0].Bucket.UTC()) + s.EqualValues(3000, requests[0].AudioMsTotal) + + turns, err := denver.TurnBuckets.Select(s.ctx, "acme", TurnBucketFilter{Granularity: Daily, From: from, To: to}) + s.Require().NoError(err) + s.Require().Len(turns, 1) + s.Equal(day, turns[0].Bucket.UTC()) + s.EqualValues(2, turns[0].TurnCount) + + _, err = denver.Buckets.Rollup(s.ctx, Daily, day.Add(time.Hour), day.Add(2*time.Hour)) + s.Require().NoError(err) + rolled := s.rolledUp("stats_daily", "acme") + s.Require().Len(rolled, 1) + s.Equal(day, rolled[0].Bucket.UTC()) + s.EqualValues(3000, rolled[0].AudioMsTotal, "the rollup's day is the UTC day too") +} + +// inTimeZone is another router on the suite's databases whose connections are in zone, as a +// server whose default is not UTC gives them. The zone is the shard database's until the test +// ends. +func (s *StoreSuite) inTimeZone(zone string) *Store { + var database string + s.Require().NoError(s.store.shard.QueryRowContext(s.ctx, "SELECT current_database()").Scan(&database)) + _, err := s.store.shard.ExecContext(s.ctx, "ALTER DATABASE ? SET timezone = ?", bun.Ident(database), zone) + s.Require().NoError(err) + s.T().Cleanup(func() { + _, err := s.store.shard.ExecContext(s.ctx, "ALTER DATABASE ? RESET timezone", bun.Ident(database)) + s.NoError(err) + }) + router, err := s.openRouter() + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(router.Close()) }) + var current string + s.Require().NoError(router.shard.QueryRowContext(s.ctx, "SHOW timezone").Scan(¤t)) + s.Require().Equal(zone, current) + return router +} + // rolledUp is what a rollup table holds for a customer, oldest first. func (s *StoreSuite) rolledUp(table, customer string) []Bucket { var buckets []Bucket diff --git a/acceleration/internal/store/request.go b/acceleration/internal/store/request.go index 20a7142cdc..a14345de1a 100644 --- a/acceleration/internal/store/request.go +++ b/acceleration/internal/store/request.go @@ -834,7 +834,7 @@ func (r *Requests) Spend( // to keep in one shard may be the biggest once the others are added. query := fmt.Sprintf(` SELECT - date_trunc('%s', started_at) AS bucket, + date_trunc('%s', started_at, 'UTC') AS bucket, %s AS value, COALESCE(SUM(cost_micros), 0) AS cost_micros_total, %s AS request_count diff --git a/acceleration/internal/store/store.go b/acceleration/internal/store/store.go index 8e32dc8efb..0c1cd05d8a 100644 --- a/acceleration/internal/store/store.go +++ b/acceleration/internal/store/store.go @@ -139,11 +139,11 @@ func (s *Store) CustomerActivity( // the shared database knows rather than the shard. people := fmt.Sprintf(` SELECT DISTINCT bucket, user_id FROM ( - SELECT date_trunc('%[1]s', s.created_at) AS bucket, s.user_id, s.caller_kind + SELECT date_trunc('%[1]s', s.created_at, 'UTC') AS bucket, s.user_id, s.caller_kind FROM agent_sessions AS s WHERE s.customer_id = ? AND s.created_at >= ? AND s.created_at < ? UNION ALL - SELECT date_trunc('%[1]s', a.created_at) AS bucket, s.user_id, s.caller_kind + SELECT date_trunc('%[1]s', a.created_at, 'UTC') AS bucket, s.user_id, s.caller_kind FROM agent_responses AS a JOIN agent_sessions AS s ON s.id = a.session_id WHERE a.customer_id = ? AND a.created_at >= ? AND a.created_at < ? @@ -151,20 +151,20 @@ SELECT DISTINCT bucket, user_id FROM ( WHERE user_id <> '' AND caller_kind <> 'anonymous'`, unit) query := fmt.Sprintf(` WITH session_counts AS ( - SELECT date_trunc('%[1]s', created_at) AS bucket, COUNT(*) AS n + SELECT date_trunc('%[1]s', created_at, 'UTC') AS bucket, COUNT(*) AS n FROM agent_sessions WHERE customer_id = ? AND created_at >= ? AND created_at < ? GROUP BY bucket ), message_counts AS ( - SELECT date_trunc('%[1]s', created_at) AS bucket, COUNT(*) AS n + SELECT date_trunc('%[1]s', created_at, 'UTC') AS bucket, COUNT(*) AS n FROM agent_responses WHERE customer_id = ? AND created_at >= ? AND created_at < ? GROUP BY bucket ), call_counts AS ( SELECT - date_trunc('%[1]s', started_at) AS bucket, + date_trunc('%[1]s', started_at, 'UTC') AS bucket, COUNT(*) AS n, SUM(EXTRACT(EPOCH FROM (COALESCE(ended_at, now()) - started_at)))::double precision / 60 AS voice_minutes, diff --git a/acceleration/internal/store/tag_bucket.go b/acceleration/internal/store/tag_bucket.go index d60a570705..cf08b630b1 100644 --- a/acceleration/internal/store/tag_bucket.go +++ b/acceleration/internal/store/tag_bucket.go @@ -33,7 +33,8 @@ type TagBucket struct { Uptime *float64 `bun:"uptime"` } -// TagBucketFilter picks a customer's buckets of one modality and one tag key in [From, To). +// TagBucketFilter picks a customer's buckets of one modality and one tag key: every bucket +// [From, To) touches, whole, as a rollup writes it. type TagBucketFilter struct { Modality string Key string @@ -65,7 +66,7 @@ SELECT r.customer_id, tag.key, tag.value, - date_trunc('%[2]s', r.started_at) AS bucket, + date_trunc('%[2]s', r.started_at, 'UTC') AS bucket, COALESCE(SUM(r.audio_ms), 0), COALESCE(SUM(r.characters), 0), COALESCE(SUM(r.input_tokens), 0), @@ -131,8 +132,7 @@ func (r *TagBuckets) Select(ctx context.Context, customerID string, f TagBucketF Where("modality = ?", f.Modality). Where("customer_id = ?", customerID). Where("tag_key = ?", f.Key). - Where("bucket >= ?", f.From). - Where("bucket < ?", f.To). + Where(wholeBuckets(f.Granularity, "bucket"), f.From, f.To). Order("bucket ASC", "tag_value ASC"). Scan(ctx, &buckets) return buckets, err diff --git a/acceleration/internal/store/tag_bucket_test.go b/acceleration/internal/store/tag_bucket_test.go index 17977ff034..85efb1087e 100644 --- a/acceleration/internal/store/tag_bucket_test.go +++ b/acceleration/internal/store/tag_bucket_test.go @@ -40,6 +40,22 @@ func (s *StoreSuite) TestARequestCarryingTwoLabelsIsCountedUnderBoth() { s.EqualValues(1000, byEnvironment[0].AudioMsTotal, "the same request, seen through the other label") } +func (s *StoreSuite) TestATagWindowInsideItsHoursReturnsEveryHourItTouches() { + s.tagged("acme", s.base.Add(45*time.Minute), 1000, map[string]string{"project": "support"}) + s.tagged("acme", s.base.Add(2*time.Hour+45*time.Minute), 500, map[string]string{"project": "support"}) + _, err := s.store.Buckets.Rollup(s.ctx, Hourly, s.base, s.base.Add(3*time.Hour)) + s.Require().NoError(err) + + buckets, err := s.store.TagBuckets.Select(s.ctx, "acme", TagBucketFilter{Modality: "stt", Key: "project", Granularity: Hourly, + From: s.base.Add(30 * time.Minute), To: s.base.Add(2*time.Hour + 30*time.Minute)}) + s.Require().NoError(err) + s.Require().Len(buckets, 2, "the hour the window starts in and the hour it ends in") + s.Equal(s.base, buckets[0].Bucket.UTC()) + s.EqualValues(1000, buckets[0].AudioMsTotal) + s.Equal(s.base.Add(2*time.Hour), buckets[1].Bucket.UTC()) + s.EqualValues(500, buckets[1].AudioMsTotal) +} + // tagged stores a labelled request, which is what the tag rollups are built from. func (s *StoreSuite) tagged(customerID string, at time.Time, audioMs int64, tags map[string]string) { latencyMs := 100.0 diff --git a/acceleration/internal/store/turn_bucket.go b/acceleration/internal/store/turn_bucket.go index a5922e7ffa..ca48175827 100644 --- a/acceleration/internal/store/turn_bucket.go +++ b/acceleration/internal/store/turn_bucket.go @@ -62,8 +62,8 @@ type TurnBucket struct { RoundtripP99Ms *float64 `bun:"-"` } -// TurnBucketFilter picks a customer's turn buckets in [From, To). An agent id narrows them to -// one agent. +// TurnBucketFilter picks a customer's turn buckets: every bucket [From, To) touches, whole. An +// agent id narrows them to one agent. type TurnBucketFilter struct { AgentID string Granularity Granularity @@ -143,8 +143,9 @@ ON CONFLICT (customer_id, agent_id, bucket, leg, bin) DO UPDATE SET return nil } -// Select returns the conversational latency buckets for one customer, oldest first. A day is -// the hours in it from the filter's From to its To. +// Select returns the conversational latency buckets for one customer, oldest first. An hour +// row is kept whole, so a window starting or ending inside a bucket returns all of it rather +// than dropping the bucket it starts in. Days are UTC days, whatever the server's time zone. func (r *TurnBuckets) Select(ctx context.Context, customerID string, f TurnBucketFilter) ([]TurnBucket, error) { granularity, agentID, from, to := f.Granularity, f.AgentID, f.From, f.To if !granularity.Valid() { @@ -153,7 +154,7 @@ func (r *TurnBuckets) Select(ctx context.Context, customerID string, f TurnBucke if customerID == "" { return nil, stack.Wrap(errors.New("store: customer id is required")) } - bucket := fmt.Sprintf("date_trunc('%s', bucket)", granularity.truncateUnit()) + bucket := fmt.Sprintf("date_trunc('%s', bucket, 'UTC')", granularity.truncateUnit()) type binRow struct { AgentID string `bun:"agent_id"` @@ -175,8 +176,7 @@ func (r *TurnBuckets) Select(ctx context.Context, customerID string, f TurnBucke ColumnExpr("SUM(interrupted_count) AS interrupted_count"). ColumnExpr("SUM(audio_out_ms_total) AS audio_out_ms_total"). Where("customer_id = ?", customerID). - Where("bucket >= ?", from). - Where("bucket < ?", to). + Where(wholeBuckets(granularity, "bucket"), from, to). GroupExpr("customer_id, agent_id, " + bucket). OrderExpr(bucket + " ASC, agent_id ASC") bins := db.NewSelect(). @@ -185,8 +185,7 @@ func (r *TurnBuckets) Select(ctx context.Context, customerID string, f TurnBucke ColumnExpr(bucket+" AS bucket"). ColumnExpr("SUM(count) AS count"). Where("customer_id = ?", customerID). - Where("bucket >= ?", from). - Where("bucket < ?", to). + Where(wholeBuckets(granularity, "bucket"), from, to). GroupExpr("agent_id, leg, bin, " + bucket). OrderExpr("bin ASC") if agentID != "" { diff --git a/acceleration/internal/store/turn_bucket_test.go b/acceleration/internal/store/turn_bucket_test.go index 47ab2c712b..3da6a38838 100644 --- a/acceleration/internal/store/turn_bucket_test.go +++ b/acceleration/internal/store/turn_bucket_test.go @@ -67,6 +67,19 @@ func (s *StoreSuite) TestOneAgentsTurnsAreNotAnothers() { s.InEpsilon(100, *buckets[0].RoundtripP99Ms, 0.05) } +func (s *StoreSuite) TestATurnWindowInsideItsHoursReturnsEveryHourItTouches() { + s.Require().NoError(s.store.TurnBuckets.Add(s.ctx, s.turn(s.base.Add(45*time.Minute), 100))) + s.Require().NoError(s.store.TurnBuckets.Add(s.ctx, s.turn(s.base.Add(2*time.Hour+45*time.Minute), 100))) + + buckets, err := s.store.TurnBuckets.Select(s.ctx, "acme", TurnBucketFilter{Granularity: Hourly, + From: s.base.Add(30 * time.Minute), To: s.base.Add(2*time.Hour + 30*time.Minute)}) + s.Require().NoError(err) + s.Require().Len(buckets, 2, "the hour the window starts in and the hour it ends in") + s.Equal(s.base, buckets[0].Bucket.UTC()) + s.Equal(s.base.Add(2*time.Hour), buckets[1].Bucket.UTC()) + s.Require().NotNil(buckets[0].RoundtripP50Ms, "the start hour's latency is read with it") +} + // turn builds one conversational turn with every leg measured. func (s *StoreSuite) turn(at time.Time, roundtripMs float64) TurnSample { sttMs, ttftMs, ttfbMs := 30.0, 120.0, 90.0 From b0064f2726246caab5eaa9ea9b1d05a95405c051 Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 20:11:26 +0100 Subject: [PATCH 2/2] fix(store): whole buckets are fixed lengths, and a daily turn read keeps its window wholeBuckets added '1 day' in the session's zone, so across a DST change the day it read was an hour short or long; it now adds 24 hours. A daily turn read groups the hours the window touches by UTC day, as the request and spend statistics keep their window, instead of widening to whole days. The time zone test sets the zone as a startup parameter of its own DSNs rather than on the database, and now covers spend, activity and the label rollup as well as the day clocks change. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/store/bucket.go | 15 +++- acceleration/internal/store/bucket_test.go | 86 +++++++++++++++---- acceleration/internal/store/turn_bucket.go | 13 +-- .../internal/store/turn_bucket_test.go | 17 ++++ 4 files changed, 106 insertions(+), 25 deletions(-) diff --git a/acceleration/internal/store/bucket.go b/acceleration/internal/store/bucket.go index 8cf6a5d9ef..243ae0aec2 100644 --- a/acceleration/internal/store/bucket.go +++ b/acceleration/internal/store/bucket.go @@ -112,11 +112,20 @@ func (r *Buckets) Rollup(ctx context.Context, granularity Granularity, from, to // wholeBuckets is a rollup's WHERE on column: the whole buckets [from, to) touches, taking // from and to as its two parameters. Postgres keeps timestamps to the microsecond, so to -// less one is the window's last instant. +// less one is the window's last instant. A bucket's length is a fixed interval: '1 day' +// would be a calendar day in the session's zone, an hour short or long across a DST change. func wholeBuckets(granularity Granularity, column string) string { return fmt.Sprintf("%[1]s >= date_trunc('%[2]s', ?::timestamptz, 'UTC') AND %[1]s < "+ - "date_trunc('%[2]s', ?::timestamptz - interval '1 microsecond', 'UTC') + interval '1 %[2]s'", - column, granularity.truncateUnit()) + "date_trunc('%[2]s', ?::timestamptz - interval '1 microsecond', 'UTC') + interval '%[3]s'", + column, granularity.truncateUnit(), granularity.length()) +} + +// length is one bucket of the granularity as a fixed Postgres interval. +func (g Granularity) length() string { + if g == Daily { + return "24 hours" + } + return "1 hour" } func (r *Buckets) rollup(ctx context.Context, granularity Granularity, from, to time.Time) (int64, error) { diff --git a/acceleration/internal/store/bucket_test.go b/acceleration/internal/store/bucket_test.go index 35b0ab08dc..de28bb1b12 100644 --- a/acceleration/internal/store/bucket_test.go +++ b/acceleration/internal/store/bucket_test.go @@ -3,8 +3,12 @@ package store import ( + "fmt" + "net/url" + "testing" "time" + "github.com/stretchr/testify/require" "github.com/uptrace/bun" ) @@ -220,10 +224,20 @@ func (s *StoreSuite) TestDailyRollupOverAnHourRecomputesTheWholeDay() { func (s *StoreSuite) TestADayIsAUTCDayWhateverTheDatabasesTimeZone() { // 03:00 UTC is the evening before in Denver, and 10:00 UTC the same morning. early, late := time.Date(2026, 3, 1, 3, 0, 0, 0, time.UTC), s.base - s.record("acme", early, 1000, 100, true) - s.record("acme", late, 2000, 100, true) + project := map[string]string{"project": "support"} + s.tagged("acme", early, 1000, project) + s.tagged("acme", late, 2000, project) s.Require().NoError(s.store.TurnBuckets.Add(s.ctx, s.turn(early, 100))) s.Require().NoError(s.store.TurnBuckets.Add(s.ctx, s.turn(late, 100))) + for i, at := range []time.Time{early, late} { + session := s.opened(fmt.Sprintf("session-%d", i), "acme", at, nil) + s.Require().NoError(s.store.Responses.Insert(s.ctx, &AgentResponse{ + ID: session.ID + "-1", SessionID: session.ID, CustomerID: "acme", CreatedAt: at, + })) + call := &Call{ID: fmt.Sprintf("call-%d", i), CustomerID: "acme", CallID: fmt.Sprintf("c-%d", i), AgentID: "a-1", StartedAt: at} + s.Require().NoError(s.store.Calls.Start(s.ctx, call)) + s.Require().NoError(s.store.Calls.Finish(s.ctx, "acme", call.ID, at.Add(time.Minute))) + } denver := s.inTimeZone("America/Denver") day := time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC) from, to := day.Add(-24*time.Hour), day.Add(48*time.Hour) @@ -234,41 +248,81 @@ func (s *StoreSuite) TestADayIsAUTCDayWhateverTheDatabasesTimeZone() { s.Equal(day, requests[0].Bucket.UTC()) s.EqualValues(3000, requests[0].AudioMsTotal) + spend, err := denver.Requests.Spend(s.ctx, "acme", "modality", Daily, from, to, 6, nil, UsageFilter{}) + s.Require().NoError(err) + s.Require().Len(spend, 1) + s.Equal(day, spend[0].Bucket.UTC()) + s.EqualValues(2, spend[0].RequestCount) + turns, err := denver.TurnBuckets.Select(s.ctx, "acme", TurnBucketFilter{Granularity: Daily, From: from, To: to}) s.Require().NoError(err) s.Require().Len(turns, 1) s.Equal(day, turns[0].Bucket.UTC()) s.EqualValues(2, turns[0].TurnCount) + activity, err := denver.CustomerActivity(s.ctx, "acme", ActivityDaily, from, to) + s.Require().NoError(err) + s.Require().Len(activity, 1, "sessions, messages, calls and people all fall in the one UTC day") + s.Equal(day, activity[0].Bucket.UTC()) + s.Equal(ActivityBucket{Bucket: activity[0].Bucket, ActiveUsers: 1, Sessions: 2, Messages: 2, Calls: 2, VoiceMinutes: 2}, activity[0]) + _, err = denver.Buckets.Rollup(s.ctx, Daily, day.Add(time.Hour), day.Add(2*time.Hour)) s.Require().NoError(err) rolled := s.rolledUp("stats_daily", "acme") s.Require().Len(rolled, 1) s.Equal(day, rolled[0].Bucket.UTC()) s.EqualValues(3000, rolled[0].AudioMsTotal, "the rollup's day is the UTC day too") + + tagged, err := denver.TagBuckets.Select(s.ctx, "acme", TagBucketFilter{Modality: "stt", Key: "project", Granularity: Daily, From: from, To: to}) + s.Require().NoError(err) + s.Require().Len(tagged, 1) + s.Equal(day, tagged[0].Bucket.UTC()) + s.EqualValues(3000, tagged[0].AudioMsTotal, "so is the label rollup's") +} + +func (s *StoreSuite) TestADailyRollupOnTheDayTheClocksChangeKeepsTheWholeUTCDay() { + // Denver moves to summer time on 2026-03-08, so that day is 23 hours long there. + day := time.Date(2026, 3, 8, 0, 0, 0, 0, time.UTC) + s.record("acme", day.Add(time.Hour), 1000, 100, true) + s.record("acme", day.Add(23*time.Hour+30*time.Minute), 2000, 100, true) + // Midday the day before, which Denver's day holding midnight UTC also holds. + s.record("acme", day.Add(-12*time.Hour), 4000, 100, true) + denver := s.inTimeZone("America/Denver") + + _, err := denver.Buckets.Rollup(s.ctx, Daily, day, day.Add(24*time.Hour)) + s.Require().NoError(err) + + rolled := s.rolledUp("stats_daily", "acme") + s.Require().Len(rolled, 1) + s.Equal(day, rolled[0].Bucket.UTC()) + s.EqualValues(3000, rolled[0].AudioMsTotal, "the request in the day's last half hour is in it, and the day before is not touched") } // inTimeZone is another router on the suite's databases whose connections are in zone, as a -// server whose default is not UTC gives them. The zone is the shard database's until the test -// ends. +// server whose default is not UTC gives them. The zone is a startup parameter of its DSNs, which +// pgdriver passes on, so nothing outlives the test. func (s *StoreSuite) inTimeZone(zone string) *Store { - var database string - s.Require().NoError(s.store.shard.QueryRowContext(s.ctx, "SELECT current_database()").Scan(&database)) - _, err := s.store.shard.ExecContext(s.ctx, "ALTER DATABASE ? SET timezone = ?", bun.Ident(database), zone) - s.Require().NoError(err) - s.T().Cleanup(func() { - _, err := s.store.shard.ExecContext(s.ctx, "ALTER DATABASE ? RESET timezone", bun.Ident(database)) - s.NoError(err) - }) - router, err := s.openRouter() + router, err := OpenShards(Options{DSN: inZone(s.T(), s.dsn, zone), ShardDSN: inZone(s.T(), s.shardDSN, zone)}) s.Require().NoError(err) s.T().Cleanup(func() { s.NoError(router.Close()) }) - var current string - s.Require().NoError(router.shard.QueryRowContext(s.ctx, "SHOW timezone").Scan(¤t)) - s.Require().Equal(zone, current) + for _, db := range []*bun.DB{router.global, router.shard} { + var current string + s.Require().NoError(db.QueryRowContext(s.ctx, "SHOW timezone").Scan(¤t)) + s.Require().Equal(zone, current) + } return router } +// inZone is dsn with its connections' timezone set to zone. +func inZone(t *testing.T, dsn, zone string) string { + parsed, err := url.Parse(dsn) + require.NoError(t, err) + query := parsed.Query() + query.Set("timezone", zone) + parsed.RawQuery = query.Encode() + return parsed.String() +} + // rolledUp is what a rollup table holds for a customer, oldest first. func (s *StoreSuite) rolledUp(table, customer string) []Bucket { var buckets []Bucket diff --git a/acceleration/internal/store/turn_bucket.go b/acceleration/internal/store/turn_bucket.go index ca48175827..3112c455e8 100644 --- a/acceleration/internal/store/turn_bucket.go +++ b/acceleration/internal/store/turn_bucket.go @@ -62,7 +62,7 @@ type TurnBucket struct { RoundtripP99Ms *float64 `bun:"-"` } -// TurnBucketFilter picks a customer's turn buckets: every bucket [From, To) touches, whole. An +// TurnBucketFilter picks a customer's turn buckets: every hour [From, To) touches, whole. An // agent id narrows them to one agent. type TurnBucketFilter struct { AgentID string @@ -143,9 +143,10 @@ ON CONFLICT (customer_id, agent_id, bucket, leg, bin) DO UPDATE SET return nil } -// Select returns the conversational latency buckets for one customer, oldest first. An hour -// row is kept whole, so a window starting or ending inside a bucket returns all of it rather -// than dropping the bucket it starts in. Days are UTC days, whatever the server's time zone. +// Select returns the conversational latency buckets for one customer, oldest first. The rows +// are hours, and every hour the window touches is read whole, rather than dropping the hour it +// starts in. A day is those hours of one UTC day, as the request statistics' day is the +// window's part of it, whatever the server's time zone. func (r *TurnBuckets) Select(ctx context.Context, customerID string, f TurnBucketFilter) ([]TurnBucket, error) { granularity, agentID, from, to := f.Granularity, f.AgentID, f.From, f.To if !granularity.Valid() { @@ -176,7 +177,7 @@ func (r *TurnBuckets) Select(ctx context.Context, customerID string, f TurnBucke ColumnExpr("SUM(interrupted_count) AS interrupted_count"). ColumnExpr("SUM(audio_out_ms_total) AS audio_out_ms_total"). Where("customer_id = ?", customerID). - Where(wholeBuckets(granularity, "bucket"), from, to). + Where(wholeBuckets(Hourly, "bucket"), from, to). GroupExpr("customer_id, agent_id, " + bucket). OrderExpr(bucket + " ASC, agent_id ASC") bins := db.NewSelect(). @@ -185,7 +186,7 @@ func (r *TurnBuckets) Select(ctx context.Context, customerID string, f TurnBucke ColumnExpr(bucket+" AS bucket"). ColumnExpr("SUM(count) AS count"). Where("customer_id = ?", customerID). - Where(wholeBuckets(granularity, "bucket"), from, to). + Where(wholeBuckets(Hourly, "bucket"), from, to). GroupExpr("agent_id, leg, bin, " + bucket). OrderExpr("bin ASC") if agentID != "" { diff --git a/acceleration/internal/store/turn_bucket_test.go b/acceleration/internal/store/turn_bucket_test.go index 3da6a38838..5429fd198c 100644 --- a/acceleration/internal/store/turn_bucket_test.go +++ b/acceleration/internal/store/turn_bucket_test.go @@ -80,6 +80,23 @@ func (s *StoreSuite) TestATurnWindowInsideItsHoursReturnsEveryHourItTouches() { s.Require().NotNil(buckets[0].RoundtripP50Ms, "the start hour's latency is read with it") } +func (s *StoreSuite) TestADailyTurnWindowStartingMidDayCountsOnlyTheHoursInIt() { + day := time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC) + s.Require().NoError(s.store.TurnBuckets.Add(s.ctx, s.turn(day.Add(5*time.Hour), 100))) + s.Require().NoError(s.store.TurnBuckets.Add(s.ctx, s.turn(day.Add(15*time.Hour), 100))) + s.Require().NoError(s.store.TurnBuckets.Add(s.ctx, s.turn(day.Add(32*time.Hour), 100))) + s.Require().NoError(s.store.TurnBuckets.Add(s.ctx, s.turn(day.Add(40*time.Hour), 100))) + + days, err := s.store.TurnBuckets.Select(s.ctx, "acme", TurnBucketFilter{Granularity: Daily, + From: day.Add(10 * time.Hour), To: day.Add(34 * time.Hour)}) + s.Require().NoError(err) + s.Require().Len(days, 2) + s.Equal(day, days[0].Bucket.UTC()) + s.EqualValues(1, days[0].TurnCount, "the morning before the window is not in it") + s.Equal(day.Add(24*time.Hour), days[1].Bucket.UTC()) + s.EqualValues(1, days[1].TurnCount, "nor the evening after it") +} + // turn builds one conversational turn with every leg measured. func (s *StoreSuite) turn(at time.Time, roundtripMs float64) TurnSample { sttMs, ttftMs, ttfbMs := 30.0, 120.0, 90.0