From 1d2f95ac4a5e016a61d859113f2a8c11b180101f Mon Sep 17 00:00:00 2001 From: Ali Aliyev Date: Thu, 19 Nov 2026 14:29:18 +0100 Subject: [PATCH 1/6] AI-3373: unowned usage alert names each app and counts rows The unowned alert named no app and its number counted sweeps passing over a waiting row. It is now one alert per app (usage_unowned:), read from Postgres at each sweeper count: waiting rows, their cost, when the oldest started and the rows by api_key, modality, provider and model. Apps that have joined an organization are left out. The skip counter keeps its name; its help now says what it counts. --- CHANGELOG.md | 4 ++ acceleration/internal/routing/alerts.go | 41 ++++++++++-- acceleration/internal/routing/alerts_test.go | 45 ++++++++++++- acceleration/internal/routing/metrics.go | 2 +- acceleration/internal/routing/shipper_test.go | 33 +++++++++ acceleration/internal/routing/sweeper.go | 10 ++- acceleration/internal/store/shipping.go | 67 +++++++++++++++++++ acceleration/internal/store/shipping_test.go | 36 ++++++++++ 8 files changed, 231 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bda44748ff..de66af15ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -729,6 +729,10 @@ A folder whose `agent.yaml` names a `plugins` list now fails to load with `plugi ## 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:`, 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`), 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. + ### One `Sync` drops an agent's sandbox and a skill's scripts together The Go SDK's `Agent.Sync` and the Python SDK's `stream.define_agent` stored the config before its skills, so a sync that removed the sandbox and a skill's scripts at once was refused: the router still held the skill with its scripts. Each retry was refused the same way. When the stored config has a sandbox, the skills are now written first, then the config. Adding a sandbox and a skill's scripts in one sync still works (AI-3363). When the stored config has a sandbox and the router refuses the new config, the skill edits stay applied; a corrected Sync converges. diff --git a/acceleration/internal/routing/alerts.go b/acceleration/internal/routing/alerts.go index d6c9bfe2e8..9f3d95ddfc 100644 --- a/acceleration/internal/routing/alerts.go +++ b/acceleration/internal/routing/alerts.go @@ -19,8 +19,9 @@ 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 // pendingSlowSeconds is how long a row may wait to be written before Postgres is too slow. pendingSlowSeconds = 60 @@ -63,8 +64,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, 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, 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 @@ -89,6 +93,35 @@ 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 { + return true + } + for _, app := range *counted { + waited := now.Sub(app.OldestStartedAt) + if waited < span { + continue + } + held[app.App] = 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, + } + } + 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) diff --git a/acceleration/internal/routing/alerts_test.go b/acceleration/internal/routing/alerts_test.go index c212596fca..861e906354 100644 --- a/acceleration/internal/routing/alerts_test.go +++ b/acceleration/internal/routing/alerts_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/suite" "github.com/GetStream/Vision-Agents/acceleration/internal/alerts" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" ) type UsageAlertsSuite struct { @@ -43,13 +44,55 @@ func (s *UsageAlertsSuite) TestTheRouterHasItsEightConditions() { }, levels) } -// 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)}, + ) + + 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") +} + +// 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() { diff --git a/acceleration/internal/routing/metrics.go b/acceleration/internal/routing/metrics.go index 3b85191359..4da8150a0b 100644 --- a/acceleration/internal/routing/metrics.go +++ b/acceleration/internal/routing/metrics.go @@ -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", diff --git a/acceleration/internal/routing/shipper_test.go b/acceleration/internal/routing/shipper_test.go index 7312334706..612f14d147 100644 --- a/acceleration/internal/routing/shipper_test.go +++ b/acceleration/internal/routing/shipper_test.go @@ -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" @@ -492,6 +493,38 @@ 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.JoinOrganization(s.ctx, s.customer, s.organization)) + s.swept(sweeper) + + s.NotContains(unowned.Items(time.Now()), s.customer) +} + func (s *WriterSuite) TestARowWithNoOrganizationWaitsForOne() { before := testutil.ToFloat64(usageUnowned) service := s.usageService() diff --git a/acceleration/internal/routing/sweeper.go b/acceleration/internal/routing/sweeper.go index 3b8712cced..b3ca58580e 100644 --- a/acceleration/internal/routing/sweeper.go +++ b/acceleration/internal/routing/sweeper.go @@ -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 @@ -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() @@ -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.UnownedUsage(counting) + if err != nil { + return err + } + s.unowned.Store(&unowned) return nil } diff --git a/acceleration/internal/store/shipping.go b/acceleration/internal/store/shipping.go index 7dfc110f07..61dd21d1b4 100644 --- a/acceleration/internal/store/shipping.go +++ b/acceleration/internal/store/shipping.go @@ -151,6 +151,73 @@ func (s *Store) Unshipped(ctx context.Context) (int64, time.Duration, error) { return rows, time.Duration(max(oldest, 0) * float64(time.Second)), nil } +// UnownedApp is an app's rows in this shard that wait to ship because the app has joined no +// organization. +type UnownedApp struct { + App string + Rows int64 + OldestStartedAt time.Time + CostMicros int64 + // Groups are the rows by what wrote them, most rows first. + Groups []UnownedGroup +} + +// UnownedGroup is the waiting rows of an app written by one key for one modality and model. +type UnownedGroup struct { + APIKey string `json:"api_key"` + Modality string `json:"modality"` + Provider string `json:"provider"` + Model string `json:"model"` + Rows int64 `json:"rows"` + CostMicros int64 `json:"cost_micros"` +} + +// UnownedUsage is the apps of this shard whose rows wait to ship with no organization, by app. +// An app that has joined one is left out: the next sweep writes it on its rows. +func (s *Store) UnownedUsage(ctx context.Context) ([]UnownedApp, error) { + var groups []struct { + App string `bun:"customer_id"` + UnownedGroup + Oldest time.Time `bun:"oldest"` + } + err := s.shard.NewRaw(` +SELECT customer_id, api_key, modality, provider, model, count(*) AS rows, sum(cost_micros) AS cost_micros, min(started_at) AS oldest +FROM requests WHERE to_ship AND shipped_at IS NULL AND organization_id = '' +GROUP BY 1, 2, 3, 4, 5 ORDER BY customer_id, rows DESC, api_key, modality, provider, model`).Scan(ctx, &groups) + if err != nil { + return nil, stack.Wrap(fmt.Errorf("store: unowned usage: %w", err)) + } + if len(groups) == 0 { + return nil, nil + } + apps := make([]string, 0, len(groups)) + for _, group := range groups { + apps = append(apps, group.App) + } + var joined []string + if err := s.db.NewSelect().Model((*AppOrganization)(nil)).Column("app_id").Where("app_id IN (?)", bun.In(apps)). + Scan(ctx, &joined); err != nil { + return nil, stack.Wrap(fmt.Errorf("store: unowned usage: %w", err)) + } + var unowned []UnownedApp + for _, group := range groups { + if slices.Contains(joined, group.App) { + continue + } + if len(unowned) == 0 || unowned[len(unowned)-1].App != group.App { + unowned = append(unowned, UnownedApp{App: group.App, OldestStartedAt: group.Oldest}) + } + app := &unowned[len(unowned)-1] + app.Rows += group.Rows + app.CostMicros += group.CostMicros + if group.Oldest.Before(app.OldestStartedAt) { + app.OldestStartedAt = group.Oldest + } + app.Groups = append(app.Groups, group.UnownedGroup) + } + return unowned, nil +} + // Reship queues this shard's rows started since then to be sent to the usage service again: // the rows it has (shipped_at set), or with rejected the rows it refused (ship_error set), // clearing why. A row it never had nor refused is left alone: one written before the router diff --git a/acceleration/internal/store/shipping_test.go b/acceleration/internal/store/shipping_test.go index 123f0a7057..4974bb65c1 100644 --- a/acceleration/internal/store/shipping_test.go +++ b/acceleration/internal/store/shipping_test.go @@ -58,3 +58,39 @@ func (s *StoreSuite) TestARouterWithoutTheShipLockKeepsNoConnectionForIt() { s.False(held) s.Nil(other.conn, "given back to the pool until the next try") } + +// waiting writes a row the sweeper has not shipped, of app, with no organization unless change +// gives it one. +func (s *StoreSuite) waiting(app string, startedAt time.Time, change func(*Request)) { + request := &Request{UsageID: uuid.Must(uuid.NewV7()), Modality: "knowledge", CustomerID: app, APIKey: "job:crawler", + Provider: "turbopuffer", Model: "write", StartedAt: startedAt, Success: true, CostMicros: 10, ToShip: true} + if change != nil { + change(request) + } + s.Require().NoError(s.store.RecordRequest(s.ctx, request)) +} + +func (s *StoreSuite) TestUnownedUsageIsTheWaitingRowsOfAppsWithNoOrganization() { + s.waiting("app", s.base.Add(time.Minute), nil) + s.waiting("app", s.base, func(r *Request) { r.CostMicros = 5 }) + s.waiting("app", s.base.Add(2*time.Minute), func(r *Request) { + r.APIKey, r.Modality, r.Provider, r.Model, r.CostMicros = "key-1", "llm", "openai", "gpt", 7 + }) + s.waiting("app", s.base.Add(-time.Hour), func(r *Request) { r.ToShip = false }) + s.waiting("app", s.base.Add(-time.Hour), func(r *Request) { r.OrganizationID = "org" }) + s.waiting("joined", s.base, nil) + s.Require().NoError(s.store.JoinOrganization(s.ctx, "joined", "org")) + + unowned, err := s.store.UnownedUsage(s.ctx) + + s.Require().NoError(err) + s.Require().Len(unowned, 1, "an app that has joined one ships at the next sweep") + s.Equal("app", unowned[0].App) + s.EqualValues(3, unowned[0].Rows) + s.EqualValues(22, unowned[0].CostMicros) + s.True(s.base.Equal(unowned[0].OldestStartedAt), "%v", unowned[0].OldestStartedAt) + s.Equal([]UnownedGroup{ + {APIKey: "job:crawler", Modality: "knowledge", Provider: "turbopuffer", Model: "write", Rows: 2, CostMicros: 15}, + {APIKey: "key-1", Modality: "llm", Provider: "openai", Model: "gpt", Rows: 1, CostMicros: 7}, + }, unowned[0].Groups) +} From 6ce3f1d1275f7a42037873a6e9142155da632400 Mon Sep 17 00:00:00 2001 From: Ali Aliyev Date: Thu, 19 Nov 2026 14:29:40 +0100 Subject: [PATCH 2/6] CHANGELOG: PR number for the unowned alert --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index de66af15ea..ee5d1488c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -731,7 +731,7 @@ A folder whose `agent.yaml` names a `plugins` list now fails to load with `plugi ### 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:`, 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`), 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. +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:`, 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`), 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). ### One `Sync` drops an agent's sandbox and a skill's scripts together From 7b8b5a15933e50c843dada3e18549362b0eba7bd Mon Sep 17 00:00:00 2001 From: Ali Aliyev Date: Thu, 19 Nov 2026 16:26:03 +0100 Subject: [PATCH 3/6] AI-3373: test the unowned alert's boundary, nil count and failed count Tests for the 15-minute boundary, a sweeper not yet counted, the oldest row in a smaller group, and a failed count keeping the last apps. The joined apps are a set. --- acceleration/internal/routing/alerts_test.go | 22 +++++++++++++++++++ acceleration/internal/routing/shipper_test.go | 21 ++++++++++++++++++ acceleration/internal/store/shipping.go | 10 ++++++--- acceleration/internal/store/shipping_test.go | 14 ++++++++++++ 4 files changed, 64 insertions(+), 3 deletions(-) diff --git a/acceleration/internal/routing/alerts_test.go b/acceleration/internal/routing/alerts_test.go index 861e906354..d7a1b6443f 100644 --- a/acceleration/internal/routing/alerts_test.go +++ b/acceleration/internal/routing/alerts_test.go @@ -84,6 +84,28 @@ func (s *UsageAlertsSuite) TestUnownedNamesEachAppWhoseRowsWaitedFifteenMinutes( }}, 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") +} + +// 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") diff --git a/acceleration/internal/routing/shipper_test.go b/acceleration/internal/routing/shipper_test.go index 612f14d147..e3f44e8b4c 100644 --- a/acceleration/internal/routing/shipper_test.go +++ b/acceleration/internal/routing/shipper_test.go @@ -525,6 +525,27 @@ func (s *WriterSuite) TestTheUnownedAlertNamesTheAppWhoseRowsWaitUntilItJoinsOne 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.DB().ExecContext(s.ctx, "ALTER TABLE app_organizations RENAME TO app_organizations_gone") + s.Require().NoError(err) + defer func() { + _, err := s.store.DB().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() diff --git a/acceleration/internal/store/shipping.go b/acceleration/internal/store/shipping.go index 61dd21d1b4..e03f3f72cd 100644 --- a/acceleration/internal/store/shipping.go +++ b/acceleration/internal/store/shipping.go @@ -194,14 +194,18 @@ GROUP BY 1, 2, 3, 4, 5 ORDER BY customer_id, rows DESC, api_key, modality, provi for _, group := range groups { apps = append(apps, group.App) } - var joined []string + var memberships []string if err := s.db.NewSelect().Model((*AppOrganization)(nil)).Column("app_id").Where("app_id IN (?)", bun.In(apps)). - Scan(ctx, &joined); err != nil { + Scan(ctx, &memberships); err != nil { return nil, stack.Wrap(fmt.Errorf("store: unowned usage: %w", err)) } + joined := make(map[string]bool, len(memberships)) + for _, app := range memberships { + joined[app] = true + } var unowned []UnownedApp for _, group := range groups { - if slices.Contains(joined, group.App) { + if joined[group.App] { continue } if len(unowned) == 0 || unowned[len(unowned)-1].App != group.App { diff --git a/acceleration/internal/store/shipping_test.go b/acceleration/internal/store/shipping_test.go index 4974bb65c1..4763afae9f 100644 --- a/acceleration/internal/store/shipping_test.go +++ b/acceleration/internal/store/shipping_test.go @@ -94,3 +94,17 @@ func (s *StoreSuite) TestUnownedUsageIsTheWaitingRowsOfAppsWithNoOrganization() {APIKey: "key-1", Modality: "llm", Provider: "openai", Model: "gpt", Rows: 1, CostMicros: 7}, }, unowned[0].Groups) } + +// The groups are ordered by rows, so the oldest row can be in any of them. +func (s *StoreSuite) TestUnownedUsageStartsAtTheOldestRowOfAnyGroup() { + s.waiting("app", s.base, nil) + s.waiting("app", s.base, nil) + s.waiting("app", s.base.Add(-time.Minute), func(r *Request) { r.APIKey = "key-1" }) + + unowned, err := s.store.UnownedUsage(s.ctx) + + s.Require().NoError(err) + s.Require().Len(unowned, 1) + s.Equal("job:crawler", unowned[0].Groups[0].APIKey, "most rows first") + s.True(s.base.Add(-time.Minute).Equal(unowned[0].OldestStartedAt), "%v", unowned[0].OldestStartedAt) +} From 4bfe2703025faeb9caf86b79d871dab9bc9b68af Mon Sep 17 00:00:00 2001 From: Ali Aliyev Date: Thu, 19 Nov 2026 16:36:53 +0100 Subject: [PATCH 4/6] AI-3373: unowned alert lists an app's 10 largest groups, sums the rest --- CHANGELOG.md | 2 +- acceleration/internal/routing/alerts.go | 15 ++++++++++++++- acceleration/internal/routing/alerts_test.go | 18 ++++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee5d1488c3..fde749209f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -731,7 +731,7 @@ A folder whose `agent.yaml` names a `plugins` list now fails to load with `plugi ### 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:`, 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`), 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` 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:`, 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). ### One `Sync` drops an agent's sandbox and a skill's scripts together diff --git a/acceleration/internal/routing/alerts.go b/acceleration/internal/routing/alerts.go index 9f3d95ddfc..ad65309293 100644 --- a/acceleration/internal/routing/alerts.go +++ b/acceleration/internal/routing/alerts.go @@ -23,6 +23,9 @@ const ( // 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 @@ -108,13 +111,23 @@ func unownedApps(span time.Duration) alerts.ItemCheck { if waited < span { continue } - held[app.App] = map[string]any{ + 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, } + 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 }) diff --git a/acceleration/internal/routing/alerts_test.go b/acceleration/internal/routing/alerts_test.go index d7a1b6443f..1e8f6de1d3 100644 --- a/acceleration/internal/routing/alerts_test.go +++ b/acceleration/internal/routing/alerts_test.go @@ -97,6 +97,24 @@ func (s *UsageAlertsSuite) TestUnownedWarnsFromTheFifteenthMinuteOn() { 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"]) +} + // A sweeper registers before its first count, which may fail: the alerts loop must not stop. func (s *UsageAlertsSuite) TestUnownedReadsNothingFromASweeperNotYetCounted() { sweeper := &Sweeper{} From ac1903b79c9ed17a419901542a1e53f2843e9369 Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 17:05:26 -0500 Subject: [PATCH 5/6] AI-3373: test the unowned alert once a day per app, and ten groups whole Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01SWVEMob5wtaNHdUCC1msgG --- acceleration/internal/routing/alerts_test.go | 56 ++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/acceleration/internal/routing/alerts_test.go b/acceleration/internal/routing/alerts_test.go index 26eba4e341..b22c5f4c07 100644 --- a/acceleration/internal/routing/alerts_test.go +++ b/acceleration/internal/routing/alerts_test.go @@ -1,12 +1,15 @@ 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" @@ -128,6 +131,59 @@ func (s *UsageAlertsSuite) TestUnownedSendsTheTenGroupsWithMostRowsAndSumsTheRes 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{} From b4f1d5b788fc0571cf6856e74bed77050eb56b60 Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 17:14:47 -0500 Subject: [PATCH 6/6] AI-3373: port the unowned sweeper tests to the Store repositories Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01SWVEMob5wtaNHdUCC1msgG --- acceleration/internal/routing/shipper_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/acceleration/internal/routing/shipper_test.go b/acceleration/internal/routing/shipper_test.go index 9bf6be5e42..f7af5f490c 100644 --- a/acceleration/internal/routing/shipper_test.go +++ b/acceleration/internal/routing/shipper_test.go @@ -519,7 +519,7 @@ func (s *WriterSuite) TestTheUnownedAlertNamesTheAppWhoseRowsWaitUntilItJoinsOne 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.JoinOrganization(s.ctx, s.customer, s.organization)) + 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) @@ -534,10 +534,10 @@ func (s *WriterSuite) TestACountThatFailsKeepsTheAppsTheLastOneFound() { 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.DB().ExecContext(s.ctx, "ALTER TABLE app_organizations RENAME TO app_organizations_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.DB().ExecContext(s.ctx, "ALTER TABLE app_organizations_gone RENAME TO app_organizations") + _, err := s.store.GlobalDB().ExecContext(s.ctx, "ALTER TABLE app_organizations_gone RENAME TO app_organizations") s.Require().NoError(err) }()