Skip to content
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -889,6 +889,9 @@ A `recipient` that is neither an E.164 number nor, for channel `imessage` or `al

## Bug Fixes

### The router's `unowned` usage alert names the app and counts rows

The `unowned` alert said only `usage alert: unowned`, with a number that counted every sweep passing over a waiting row, not the rows. It is now one alert per app, fingerprinted `usage_unowned:<app>`, so each app is its own Sentry issue. It warns once the app's oldest row waiting for an organization started 15 minutes ago, and says the app has joined no organization, so its rows are not billed, and to check `app_organizations` for it first, then what wrote the rows. It carries the app's waiting rows, their cost (`cost_micros`), when the oldest started, and the rows by `api_key`, modality, provider and model (`written_by`, the 10 groups with most rows, the rest counted in `other_groups` and `other_rows`), read from Postgres by every router's sweeper at each count. An app that has joined an organization is left out, since the next sweep ships its rows. `router_usage_unowned_total` keeps its name and now says what it counts: each time a sweep passes over such a row (#2118).
### The `unowned` usage alert is sent once a day, not once a minute

The router's `unowned` alert holds for as long as usage rows wait for an app to join an organization, which can be days, and was sent again every minute it held. It is now sent again at most once a day while it holds; it is still sent as soon as it starts holding, including when it holds again after it stopped. Every other usage alert is unchanged (#2115).
Expand Down
54 changes: 50 additions & 4 deletions acceleration/internal/routing/alerts.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,13 @@ const (
// A row's age is counted from when its work started, so a long call written a moment ago
// is already old; the shipper sends it within seconds.
shipStaleFor = 2 * time.Minute
// unownedFor is how long rows must keep waiting for an organization to warn: an app's
// membership is normally written within seconds of its first request.
// unownedFor is how long ago an app's oldest row waiting for an organization must have
// started to warn: an app's membership is normally written within seconds of its first
// request, before any of its rows is written.
unownedFor = 15 * time.Minute
// unownedGroupsSent is how many of an app's groups of waiting rows an alert lists, the ones
// with most rows, so an app with many keys or models keeps its event small.
unownedGroupsSent = 10
// pendingSlowSeconds is how long a row may wait to be written before Postgres is too slow.
pendingSlowSeconds = 60
// holdsUnflushedSeconds is how long a change to a hold may wait to be shared with the other
Expand Down Expand Up @@ -63,8 +67,11 @@ func Alerts(limit time.Duration) []alerts.Condition {
Summary: "spend holds are not reaching the other routers, so billable requests are refused with 503 spend_check_unavailable"},
{Name: "ship_stale", Level: alerts.Page, Check: aboveFor(unshippedOldest, shipStaleSeconds, shipStaleFor, "oldest_unshipped_started_seconds_ago"),
Summary: "usage rows are not reaching the usage service, so the balances it keeps are stale"},
{Name: "unowned", Level: alerts.Warn, Repeat: 24 * time.Hour, Check: alerts.IncreasingFor(func() float64 { return alerts.Total(usageUnowned) }, unownedFor),
Summary: "usage rows of an app that has joined no organization keep waiting; they are not billed until the app joins one"},
// One alert per app, so each is its own Sentry issue.
{Name: "unowned", Level: alerts.Warn, Repeat: 24 * time.Hour, Items: unownedApps(unownedFor), Describe: func(string) string {
return "the app has joined no organization, so its usage rows wait and are not billed until it joins one; " +
"check app_organizations for the app first, then what wrote the rows (written_by: api_key, modality, provider, model)"
}},
{Name: "pending_slow", Level: alerts.Warn, Check: aboveFor(oldestPending, pendingSlowSeconds, 0, "oldest_pending_seconds"),
Summary: fmt.Sprintf("a usage row has waited over %d seconds to be written: Postgres is slow, or writes are failing and retried", pendingSlowSeconds)},
// A site that owns work and names neither a key nor an origin: its rows are billed, and
Expand All @@ -89,6 +96,45 @@ func lostCheck(limit time.Duration) alerts.Check {
}
}

// unownedApps holds for each app whose oldest row waiting for an organization, as the last
// count of the shard found, started at least span ago.
func unownedApps(span time.Duration) alerts.ItemCheck {
return func(now time.Time) map[string]map[string]any {
held := map[string]map[string]any{}
sweepers.Range(func(key, _ any) bool {
counted := key.(*Sweeper).unowned.Load()
if counted == nil {
Comment thread
kanat marked this conversation as resolved.
Resolved
return true
}
for _, app := range *counted {
waited := now.Sub(app.OldestStartedAt)
if waited < span {
continue
}
extra := map[string]any{
"waiting_rows": app.Rows,
"cost_micros": app.CostMicros,
"oldest_started_at": app.OldestStartedAt.UTC().Format(time.RFC3339),
"oldest_waiting": waited.Round(time.Second).String(),
"written_by": app.Groups,
Comment thread
kanat marked this conversation as resolved.
Resolved
}
if len(app.Groups) > unownedGroupsSent {
extra["written_by"] = app.Groups[:unownedGroupsSent]
var rows int64
for _, group := range app.Groups[unownedGroupsSent:] {
rows += group.Rows
}
extra["other_groups"] = len(app.Groups) - unownedGroupsSent
extra["other_rows"] = rows
}
held[app.App] = extra
}
return true
})
return held
}
}

// writeFailing holds when writes kept failing over span and none was written.
func writeFailing(span time.Duration) alerts.Check {
failing := alerts.IncreasingFor(func() float64 { return alerts.Total(usageWriteErrors) }, span)
Expand Down
141 changes: 140 additions & 1 deletion acceleration/internal/routing/alerts_test.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
package routing

import (
"context"
"fmt"
"log/slog"
"strings"
"sync/atomic"
"testing"
"time"

"github.com/getsentry/sentry-go"
"github.com/stretchr/testify/suite"

"github.com/GetStream/Vision-Agents/acceleration/internal/alerts"
"github.com/GetStream/Vision-Agents/acceleration/internal/store"
)

type UsageAlertsSuite struct {
Expand Down Expand Up @@ -56,13 +60,148 @@ func (s *UsageAlertsSuite) TestOnlyUnownedRepeatsOnceADay() {
}, repeats)
}

// The Slack message of an alert is its Sentry title: without a summary it names only the alert.
// The Slack message of an alert is its Sentry title: without a summary, or an item's
// description, it names only the alert.
func (s *UsageAlertsSuite) TestEveryConditionSaysWhatItMeans() {
for _, condition := range Alerts(time.Minute) {
if condition.Items != nil {
s.NotEmpty(strings.TrimSpace(condition.Describe("app")), condition.Name)
continue
}
s.NotEmpty(strings.TrimSpace(condition.Summary), condition.Name)
}
}

// counted makes the apps the last count of a sweeper found waiting for an organization what
// the alerts read.
func (s *UsageAlertsSuite) counted(apps ...store.UnownedApp) {
sweeper := &Sweeper{}
sweeper.unowned.Store(&apps)
sweepers.Store(sweeper, struct{}{})
s.T().Cleanup(func() { sweepers.Delete(sweeper) })
}

func (s *UsageAlertsSuite) TestUnownedNamesEachAppWhoseRowsWaitedFifteenMinutes() {
now := time.Date(2026, 11, 19, 12, 0, 0, 0, time.UTC)
written := []store.UnownedGroup{
{APIKey: "job:crawler", Modality: "knowledge", Provider: "turbopuffer", Model: "write", Rows: 10, CostMicros: 300},
{APIKey: "key-1", Modality: "llm", Provider: "openai", Model: "gpt", Rows: 2, CostMicros: 100},
}
s.counted(
store.UnownedApp{App: "waiting", Rows: 12, CostMicros: 400, OldestStartedAt: now.Add(-26 * time.Hour), Groups: written},
store.UnownedApp{App: "new", Rows: 1, CostMicros: 3, OldestStartedAt: now.Add(-14 * time.Minute)},
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
)

held := s.named("unowned").Items(now)

s.Equal(map[string]map[string]any{"waiting": {
"waiting_rows": int64(12), "cost_micros": int64(400), "oldest_started_at": "2026-11-18T10:00:00Z",
"oldest_waiting": "26h0m0s", "written_by": written,
}}, held, "an app is warned about once its oldest row has waited 15 minutes")
}

func (s *UsageAlertsSuite) TestUnownedWarnsFromTheFifteenthMinuteOn() {
now := time.Date(2026, 11, 19, 12, 0, 0, 0, time.UTC)
s.counted(
store.UnownedApp{App: "fifteen", Rows: 1, OldestStartedAt: now.Add(-15 * time.Minute)},
store.UnownedApp{App: "almost", Rows: 1, OldestStartedAt: now.Add(-15*time.Minute + time.Second)},
)

held := s.named("unowned").Items(now)

s.Contains(held, "fifteen")
s.NotContains(held, "almost")
}

// An app with many keys or models keeps a small event: the groups with most rows, and a count
// of the rest.
func (s *UsageAlertsSuite) TestUnownedSendsTheTenGroupsWithMostRowsAndSumsTheRest() {
now := time.Now()
var groups []store.UnownedGroup
for i := range 13 {
groups = append(groups, store.UnownedGroup{APIKey: fmt.Sprintf("key-%d", i), Modality: "llm", Provider: "openai",
Model: "gpt", Rows: int64(20 - i), CostMicros: 5})
}
s.counted(store.UnownedApp{App: "busy", Rows: 221, CostMicros: 65, OldestStartedAt: now.Add(-time.Hour), Groups: groups})

held := s.named("unowned").Items(now)["busy"]

s.Equal(groups[:10], held["written_by"])
s.Equal(3, held["other_groups"])
s.Equal(int64(10+9+8), held["other_rows"])
}

// An app that stays unowned is named once a day, not every minute: the first send holds the
// next ones back for 24 h, and an app that was sent is sent again after it.
func (s *UsageAlertsSuite) TestUnownedNamesAnAppOnceADayWhileItWaits() {
var sent []string
client, err := sentry.NewClient(sentry.ClientOptions{
BeforeSend: func(event *sentry.Event, _ *sentry.EventHint) *sentry.Event {
sent = append(sent, event.Tags["item"])
return nil
},
})
s.Require().NoError(err)
start := time.Date(2026, 11, 19, 12, 0, 0, 0, time.UTC)
now := start
loop := alerts.New(alerts.Options{
Hub: sentry.NewHub(client, sentry.NewScope()), Logger: slog.New(slog.DiscardHandler),
Limit: time.Minute, Now: func() time.Time { return now },
}, s.named("unowned"))
check := func(at time.Duration) {
now = start.Add(at)
ctx, cancel := context.WithCancel(context.Background())
cancel()
loop.Run(ctx)
}
s.counted(
store.UnownedApp{App: "first", Rows: 1, OldestStartedAt: start.Add(-time.Hour)},
store.UnownedApp{App: "second", Rows: 1, OldestStartedAt: start.Add(-time.Hour)},
)

check(0)
s.ElementsMatch([]string{"first", "second"}, sent, "each app is named")
check(time.Minute)
check(23 * time.Hour)
s.Len(sent, 2, "held back within 24 h")
check(24*time.Hour + time.Second)
s.Len(sent, 4, "named again after 24 h")
}

// Ten groups fit whole: nothing is left over to count.
func (s *UsageAlertsSuite) TestUnownedWithExactlyTenGroupsSendsThemAllAndCountsNoRest() {
now := time.Now()
var groups []store.UnownedGroup
for i := range 10 {
groups = append(groups, store.UnownedGroup{APIKey: fmt.Sprintf("key-%d", i), Rows: int64(20 - i)})
}
s.counted(store.UnownedApp{App: "ten", Rows: 155, OldestStartedAt: now.Add(-time.Hour), Groups: groups})

held := s.named("unowned").Items(now)["ten"]

s.Equal(groups, held["written_by"])
s.NotContains(held, "other_groups")
s.NotContains(held, "other_rows")
}

// A sweeper registers before its first count, which may fail: the alerts loop must not stop.
func (s *UsageAlertsSuite) TestUnownedReadsNothingFromASweeperNotYetCounted() {
sweeper := &Sweeper{}
sweepers.Store(sweeper, struct{}{})
s.T().Cleanup(func() { sweepers.Delete(sweeper) })

s.Empty(s.named("unowned").Items(time.Now()))
}

// What a person who opens the alert checks first: the app's membership, then what wrote its rows.
func (s *UsageAlertsSuite) TestUnownedSaysWhyTheRowsWaitAndWhatToCheck() {
described := s.named("unowned").Describe("app")
s.Contains(described, "joined no organization")
s.Contains(described, "not billed")
s.Contains(described, "app_organizations")
s.Contains(described, "api_key")
}

// A row lost is written back by replay and a refused one is queued again by reship: the summary
// must name the command, not say the work is gone or ships by itself.
func (s *UsageAlertsSuite) TestLostAndRejectedNameTheirWayBack() {
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/routing/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ var (
usageUnowned = promauto.NewCounter(prometheus.CounterOpts{
Namespace: "router",
Name: "usage_unowned_total",
Help: "Usage rows a sweep left unshipped because their app has joined no organization yet",
Help: "Times a sweep passed over a usage row because its app has joined no organization yet; a row is counted again at every sweep while it waits",
})
_ = promauto.NewGaugeFunc(prometheus.GaugeOpts{
Namespace: "router",
Expand Down
54 changes: 54 additions & 0 deletions acceleration/internal/routing/shipper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/google/uuid"
"github.com/prometheus/client_golang/prometheus/testutil"

"github.com/GetStream/Vision-Agents/acceleration/internal/alerts"
"github.com/GetStream/Vision-Agents/acceleration/internal/pricing"
"github.com/GetStream/Vision-Agents/acceleration/internal/store"
"github.com/GetStream/Vision-Agents/acceleration/internal/usage"
Expand Down Expand Up @@ -492,6 +493,59 @@ func (s *WriterSuite) TestARejectedRowIsKeptAndCounted() {
s.Len(s.events(service), 1)
}

func (s *WriterSuite) TestTheUnownedAlertNamesTheAppWhoseRowsWaitUntilItJoinsOne() {
service := s.usageService()
writer := s.shippingWriter(service, nil)
writer.enqueue(s.row(func(request *store.Request) {
request.StartedAt, request.APIKey = time.Now().UTC().Add(-time.Hour), "job:crawler"
}))
s.written(1)
sweeper := s.sweeper(service.Client)
var unowned alerts.Condition
for _, condition := range Alerts(time.Minute) {
if condition.Name == "unowned" {
unowned = condition
}
}

s.swept(sweeper)

held := unowned.Items(time.Now())
s.Require().Contains(held, s.customer)
s.EqualValues(1, held[s.customer]["waiting_rows"], "rows, however many sweeps passed over them")
s.EqualValues(25, held[s.customer]["cost_micros"])
s.Equal([]store.UnownedGroup{{APIKey: "job:crawler", Modality: "llm", Provider: "openai", Model: "gpt", Rows: 1, CostMicros: 25}},
held[s.customer]["written_by"])
s.swept(sweeper)
s.EqualValues(1, unowned.Items(time.Now())[s.customer]["waiting_rows"], "a second sweep counts the same row once")

s.Require().NoError(s.store.AppOrganizations.Upsert(s.ctx, &store.AppOrganization{AppID: s.customer, OrganizationID: s.organization}))
s.swept(sweeper)

s.NotContains(unowned.Items(time.Now()), s.customer)
}

func (s *WriterSuite) TestACountThatFailsKeepsTheAppsTheLastOneFound() {
service := s.usageService()
writer := s.shippingWriter(service, nil)
writer.enqueue(s.row(nil))
s.written(1)
sweeper := s.sweeper(service.Client)
s.Require().NoError(sweeper.count(s.ctx))
s.Require().Len(*sweeper.unowned.Load(), 1)
// Reading the memberships fails while the table is gone.
_, err := s.store.GlobalDB().ExecContext(s.ctx, "ALTER TABLE app_organizations RENAME TO app_organizations_gone")
s.Require().NoError(err)
defer func() {
_, err := s.store.GlobalDB().ExecContext(s.ctx, "ALTER TABLE app_organizations_gone RENAME TO app_organizations")
s.Require().NoError(err)
}()

s.Error(sweeper.count(s.ctx))

s.Len(*sweeper.unowned.Load(), 1)
}

func (s *WriterSuite) TestARowWithNoOrganizationWaitsForOne() {
before := testutil.ToFloat64(usageUnowned)
service := s.usageService()
Expand Down
10 changes: 9 additions & 1 deletion acceleration/internal/routing/sweeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ type Sweeper struct {
// nanoseconds since the oldest started.
unshipped atomic.Int64
oldest atomic.Int64
// unowned is the apps the last count found waiting for an organization, for the unowned alert.
unowned atomic.Pointer[[]store.UnownedApp]

// errorLogged is when a failed sweep was last logged, in Unix nanoseconds, and
// unownedLogged when each app whose rows have no organization was. Only the sweeping
Expand Down Expand Up @@ -159,7 +161,8 @@ func (s *Sweeper) sweep(ctx context.Context) (bool, error) {
}

// count reads how many rows wait in the shard and how long ago the oldest started, for the
// gauges. A count that fails leaves them as they were.
// gauges, and the apps whose rows wait for an organization, for the alert. A count that fails
// leaves them as they were.
func (s *Sweeper) count(ctx context.Context) error {
counting, cancel := context.WithTimeout(ctx, countTimeout)
defer cancel()
Expand All @@ -169,6 +172,11 @@ func (s *Sweeper) count(ctx context.Context) error {
}
s.unshipped.Store(rows)
s.oldest.Store(int64(oldest))
unowned, err := s.store.Requests.UnownedUsage(counting)
if err != nil {
return err
}
s.unowned.Store(&unowned)
return nil
}

Expand Down
Loading
Loading