Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions acceleration/internal/store/bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) AND %[1]s < "+
"date_trunc('%[2]s', ?::timestamptz - interval '1 microsecond') + interval '1 %[2]s'",
column, granularity.truncateUnit())
return fmt.Sprintf("%[1]s >= date_trunc('%[2]s', ?::timestamptz, 'UTC') AND %[1]s < "+
"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) {
Expand All @@ -135,7 +144,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),
Expand Down Expand Up @@ -205,7 +214,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,
Expand Down
112 changes: 111 additions & 1 deletion acceleration/internal/store/bucket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,15 @@

package store

import "time"
import (
"fmt"
"net/url"
"testing"
"time"

"github.com/stretchr/testify/require"
"github.com/uptrace/bun"
)

func (s *StoreSuite) TestRollupAggregatesRequestsIntoOneBucket() {
s.record("acme", s.base.Add(1*time.Minute), 1000, 100, true)
Expand Down Expand Up @@ -213,6 +221,108 @@ 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
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)

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)

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 a startup parameter of its DSNs, which
// pgdriver passes on, so nothing outlives the test.
func (s *StoreSuite) inTimeZone(zone string) *Store {
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()) })
for _, db := range []*bun.DB{router.global, router.shard} {
var current string
s.Require().NoError(db.QueryRowContext(s.ctx, "SHOW timezone").Scan(&current))
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
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/store/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 5 additions & 5 deletions acceleration/internal/store/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,32 +139,32 @@ 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 < ?
) AS seen
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,
Expand Down
8 changes: 4 additions & 4 deletions acceleration/internal/store/tag_bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions acceleration/internal/store/tag_bucket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 9 additions & 9 deletions acceleration/internal/store/turn_bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 hour [From, To) touches, whole. An
// agent id narrows them to one agent.
type TurnBucketFilter struct {
AgentID string
Granularity Granularity
Expand Down Expand Up @@ -143,8 +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. 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. 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() {
Expand All @@ -153,7 +155,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"`
Expand All @@ -175,8 +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("bucket >= ?", from).
Where("bucket < ?", to).
Where(wholeBuckets(Hourly, "bucket"), from, to).
GroupExpr("customer_id, agent_id, " + bucket).
OrderExpr(bucket + " ASC, agent_id ASC")
bins := db.NewSelect().
Expand All @@ -185,8 +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("bucket >= ?", from).
Where("bucket < ?", to).
Where(wholeBuckets(Hourly, "bucket"), from, to).
GroupExpr("agent_id, leg, bin, " + bucket).
OrderExpr("bin ASC")
if agentID != "" {
Expand Down
30 changes: 30 additions & 0 deletions acceleration/internal/store/turn_bucket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,36 @@ 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")
}

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
Expand Down
Loading