From 58974dc6f2941069428897564ff2ae79ab2254a4 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Tue, 24 Nov 2026 16:00:08 +0100 Subject: [PATCH 1/2] fix(teams): count no app of another customer by organization id GET /v1/teams, on a router with no usage service or for an app in no organization, sums the request rows of AppOrganizations.Apps, which always holds the organization's own id as an app. So another customer's app whose id matched was counted: for an organization, the app whose id is the organization's; for an app in no organization, every app seen under an organization of the app's id. Their teams, spend and app ids were answered as the caller's. Spend.Teams now takes billed, as Spend.Subject does: a billed organization counts its Members (Apps without its own id), an app in no organization itself alone. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/account.go | 2 +- acceleration/internal/api/account_test.go | 18 +++++++++++++ acceleration/internal/api/limits_test.go | 22 ++++++++++++--- .../internal/store/app_organization.go | 27 ++++++++++++------- acceleration/internal/store/spend.go | 16 +++++++---- acceleration/internal/store/spend_test.go | 2 +- .../internal/store/store_explain_test.go | 3 ++- 7 files changed, 70 insertions(+), 20 deletions(-) diff --git a/acceleration/internal/api/account.go b/acceleration/internal/api/account.go index 8a1afb1be7..064143e227 100644 --- a/acceleration/internal/api/account.go +++ b/acceleration/internal/api/account.go @@ -547,7 +547,7 @@ func (s *Server) teamSpend(ctx context.Context, organization string, billed bool since[i], _ = usage.Window(interval, now) } month, _ := usage.Window(usage.Monthly, now) - rows, err := s.store.Spend.Teams(ctx, organization, since, month) + rows, err := s.store.Spend.Teams(ctx, organization, since, month, billed) if err != nil { return nil, err } diff --git a/acceleration/internal/api/account_test.go b/acceleration/internal/api/account_test.go index 241d34e260..a36e46f448 100644 --- a/acceleration/internal/api/account_test.go +++ b/acceleration/internal/api/account_test.go @@ -535,6 +535,24 @@ func (s *SelfHostedAccountSuite) TestNoUsageServiceAnswersNotEnabled() { } } +// An organization's teams are its apps' work's, not an app's whose id is the organization's, +// which is another customer's. +func (s *SelfHostedAccountSuite) TestTeamsLeaveOutAnAppWhoseIdIsTheOrganizations() { + for app, team := range map[string]string{s.customerID(): "finance", s.app.organization.ID: "stranger"} { + s.Require().NoError(s.store.Requests.Insert(context.Background(), &store.Request{ + Modality: "llm", CustomerID: app, APIKey: "key_a", Provider: "stub", Model: "stub-llm", + StartedAt: time.Now(), CostMicros: 500_000, Billable: true, Success: true, UsageCategories: []string{"team:" + team}, + })) + } + + var teams []Team + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/teams", nil, &teams)) + + s.Require().Len(teams, 1, "%+v", teams) + s.Equal("finance", teams[0].Name) + s.Equal([]string{s.customerID()}, teams[0].Apps) +} + func (s *SelfHostedAccountSuite) TestTeamsSumTheRequestsThisMonth() { record := func(at time.Time, micros int64, team string) { s.Require().NoError(s.store.Requests.Insert(context.Background(), &store.Request{ diff --git a/acceleration/internal/api/limits_test.go b/acceleration/internal/api/limits_test.go index c942b7da8f..aab96ffc6a 100644 --- a/acceleration/internal/api/limits_test.go +++ b/acceleration/internal/api/limits_test.go @@ -646,11 +646,11 @@ func (s *SelfHostedLimitsSuite) backend(app, organization string) *testClient { return &testClient{suite: &s.RouterSuite, header: header, kind: server} } -// spent records a billable request of app's, costing micros, now. -func (s *SelfHostedLimitsSuite) spent(app string, micros int64) { +// spent records a billable request of app's, costing micros, now, carrying categories. +func (s *SelfHostedLimitsSuite) spent(app string, micros int64, categories ...string) { s.Require().NoError(s.store.Requests.Insert(context.Background(), &store.Request{ Modality: "llm", CustomerID: app, APIKey: "key_a", Provider: "stub", Model: "stub-llm", - StartedAt: time.Now(), CostMicros: micros, Billable: true, Success: true, + StartedAt: time.Now(), CostMicros: micros, Billable: true, Success: true, UsageCategories: categories, })) } @@ -733,3 +733,19 @@ func (s *SelfHostedLimitsSuite) TestAnOrganizationsSpendLeavesOutAnAppWhoseIdIsI s.Equal(int64(300_000), s.dailySpend(backend, "subject=organization")) } + +// The teams of an app in no organization are its own work's: an app seen under an organization +// whose id is the app's is another customer's. +func (s *SelfHostedLimitsSuite) TestAnAppInNoOrganizationsTeamsAreItsOwnWorks() { + own, stranger := s.utils.uuid(), s.utils.uuid() + s.Require().NoError(s.store.AppOrganizations.Upsert(context.Background(), &store.AppOrganization{AppID: stranger, OrganizationID: own})) + s.spent(own, 300_000, "team:finance") + s.spent(stranger, 700_000, "team:stranger") + + var teams []Team + s.Require().Equal(http.StatusOK, s.backend(own, "").do(http.MethodGet, "/v1/teams", nil, &teams)) + + s.Require().Len(teams, 1, "%+v", teams) + s.Equal("finance", teams[0].Name) + s.Equal([]string{own}, teams[0].Apps) +} diff --git a/acceleration/internal/store/app_organization.go b/acceleration/internal/store/app_organization.go index 7219319fd8..8fb20770f0 100644 --- a/acceleration/internal/store/app_organization.go +++ b/acceleration/internal/store/app_organization.go @@ -153,10 +153,25 @@ func (r *AppOrganizations) registered(ctx context.Context, appIDs []string) (map return owners, nil } -// Apps is every app of an organization: those requests last named it for, those -// registered under it that no request named another for, and the app whose id is the +// Apps is every app of an organization: its Members, and the app whose id is the // organization's, for an app that is its own. func (r *AppOrganizations) Apps(ctx context.Context, organizationID string) ([]string, error) { + members, err := r.Members(ctx, organizationID) + if err != nil { + return nil, err + } + apps := []string{organizationID} + for _, app := range members { + if app != organizationID { + apps = append(apps, app) + } + } + return apps, nil +} + +// Members is every app of an organization, in order: those requests last named it for, and +// those registered under it that no request named another for. +func (r *AppOrganizations) Members(ctx context.Context, organizationID string) ([]string, error) { // One statement, so an app a request records under the organization meanwhile is in one // half or the other. namedOther := r.store.global.NewSelect().Model((*AppOrganization)(nil)). @@ -172,13 +187,7 @@ func (r *AppOrganizations) Apps(ctx context.Context, organizationID string) ([]s if err != nil { return nil, stack.Wrap(fmt.Errorf("store: organization apps: %w", err)) } - apps := []string{organizationID} - for _, app := range members { - if app != organizationID { - apps = append(apps, app) - } - } - return apps, nil + return members, nil } // ActivityApps is Apps for a read of what an organization did: the diff --git a/acceleration/internal/store/spend.go b/acceleration/internal/store/spend.go index b43d171b96..e5499a599e 100644 --- a/acceleration/internal/store/spend.go +++ b/acceleration/internal/store/spend.go @@ -58,14 +58,20 @@ type TeamAppSpend struct { // Teams sums, across every shard, the billable cost of the rows of every app of the // organization that carry a team's category since each of since, per app and team, for a -// deployment with no usage service to count it. Rows are read from the earliest moment. -func (r *Spend) Teams(ctx context.Context, organizationID string, since []time.Time, month time.Time) ([]TeamAppSpend, error) { +// deployment with no usage service to count it. Rows are read from the earliest moment. A +// billed organization's apps are its Members; an app in no organization, whose id +// organizationID is, is its own only app. Neither counts an app of another customer's whose id +// is the same, as Subject does not. +func (r *Spend) Teams(ctx context.Context, organizationID string, since []time.Time, month time.Time, billed bool) ([]TeamAppSpend, error) { if len(since) == 0 { return nil, nil } - apps, err := r.store.AppOrganizations.Apps(ctx, organizationID) - if err != nil { - return nil, err + apps := []string{organizationID} + if billed { + var err error + if apps, err = r.store.AppOrganizations.Members(ctx, organizationID); err != nil { + return nil, err + } } earliest := slices.MinFunc(append(slices.Clone(since), month), func(a, b time.Time) int { return a.Compare(b) }) var sums strings.Builder diff --git a/acceleration/internal/store/spend_test.go b/acceleration/internal/store/spend_test.go index 3bf3d3e93e..6a3a24cf4f 100644 --- a/acceleration/internal/store/spend_test.go +++ b/acceleration/internal/store/spend_test.go @@ -202,7 +202,7 @@ func (s *StoreSuite) TestSpendQueryBudgets() { s.Require().NoError(err) }), "the organization's apps, then one sum a shard") s.Equal(1+shards, s.countQueries(func() { - _, err := s.store.Spend.Teams(s.ctx, organization, []time.Time{s.base}, s.base) + _, err := s.store.Spend.Teams(s.ctx, organization, []time.Time{s.base}, s.base, true) s.Require().NoError(err) }), "the organization's apps, then one sum a shard") s.Equal(shards, s.countQueries(func() { diff --git a/acceleration/internal/store/store_explain_test.go b/acceleration/internal/store/store_explain_test.go index 7564ad178e..e4bab8686a 100644 --- a/acceleration/internal/store/store_explain_test.go +++ b/acceleration/internal/store/store_explain_test.go @@ -700,7 +700,8 @@ func (s *StoreSuite) TestEveryHotTableIsReadByIndex() { return err }}, {name: "Spend.Teams", index: "requests_customer_spend_idx", run: func(ctx context.Context, store *Store) error { - _, err := store.Spend.Teams(ctx, "org-7", []time.Time{since}, s.base.AddDate(0, 0, -1)) + // Of an app in no organization, as the category sum below is. + _, err := store.Spend.Teams(ctx, "customer-7", []time.Time{since}, s.base.AddDate(0, 0, -1), false) return err }}, {name: "Spend.Subject", index: "requests_customer_spend_idx", run: func(ctx context.Context, store *Store) error { From f0aad6b389e4881e84697e7ecfbd70700ccf8d1c Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Tue, 24 Nov 2026 17:44:28 +0100 Subject: [PATCH 2/2] test(teams): cover a billed organization's apps and the unbilled read - insertRequest in the teams test and in spent, since #2377 removed Requests.Insert. - A billed organization's teams count every app seen under it, the one whose id is the organization's among them. Leaving out the organization's own id, or reading registered apps only, passed before. - The unbilled Spend.Teams read looks up no apps: one sum a shard. - The explain seed records customer-7 and customer-107 under org-7, and a billed Spend.Teams case reads their IN list by index. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/account_test.go | 2 +- acceleration/internal/api/limits_test.go | 21 ++++++++++++++++++- acceleration/internal/store/spend_test.go | 4 ++++ .../internal/store/store_explain_test.go | 12 +++++++++-- 4 files changed, 35 insertions(+), 4 deletions(-) diff --git a/acceleration/internal/api/account_test.go b/acceleration/internal/api/account_test.go index 4c8380c452..2327521ae2 100644 --- a/acceleration/internal/api/account_test.go +++ b/acceleration/internal/api/account_test.go @@ -539,7 +539,7 @@ func (s *SelfHostedAccountSuite) TestNoUsageServiceAnswersNotEnabled() { // which is another customer's. func (s *SelfHostedAccountSuite) TestTeamsLeaveOutAnAppWhoseIdIsTheOrganizations() { for app, team := range map[string]string{s.customerID(): "finance", s.app.organization.ID: "stranger"} { - s.Require().NoError(s.store.Requests.Insert(context.Background(), &store.Request{ + s.Require().NoError(insertRequest(context.Background(), s.store, &store.Request{ Modality: "llm", CustomerID: app, APIKey: "key_a", Provider: "stub", Model: "stub-llm", StartedAt: time.Now(), CostMicros: 500_000, Billable: true, Success: true, UsageCategories: []string{"team:" + team}, })) diff --git a/acceleration/internal/api/limits_test.go b/acceleration/internal/api/limits_test.go index aab96ffc6a..5a7bcfbbd9 100644 --- a/acceleration/internal/api/limits_test.go +++ b/acceleration/internal/api/limits_test.go @@ -648,7 +648,7 @@ func (s *SelfHostedLimitsSuite) backend(app, organization string) *testClient { // spent records a billable request of app's, costing micros, now, carrying categories. func (s *SelfHostedLimitsSuite) spent(app string, micros int64, categories ...string) { - s.Require().NoError(s.store.Requests.Insert(context.Background(), &store.Request{ + s.Require().NoError(insertRequest(context.Background(), s.store, &store.Request{ Modality: "llm", CustomerID: app, APIKey: "key_a", Provider: "stub", Model: "stub-llm", StartedAt: time.Now(), CostMicros: micros, Billable: true, Success: true, UsageCategories: categories, })) @@ -749,3 +749,22 @@ func (s *SelfHostedLimitsSuite) TestAnAppInNoOrganizationsTeamsAreItsOwnWorks() s.Equal("finance", teams[0].Name) s.Equal([]string{own}, teams[0].Apps) } + +// An organization's teams are the work of every app seen under it, the one whose id is the +// organization's among them when it was seen there. +func (s *SelfHostedLimitsSuite) TestAnOrganizationsTeamsAreTheWorkOfEveryAppSeenUnderIt() { + own, organization := s.utils.uuid(), s.utils.uuid() + for _, app := range []string{own, organization} { + s.Require().NoError(s.store.AppOrganizations.Upsert(context.Background(), &store.AppOrganization{AppID: app, OrganizationID: organization})) + } + s.spent(own, 300_000, "team:finance") + s.spent(organization, 700_000, "team:finance") + + var teams []Team + s.Require().Equal(http.StatusOK, s.backend(own, organization).do(http.MethodGet, "/v1/teams", nil, &teams)) + + s.Require().Len(teams, 1, "%+v", teams) + s.Equal("finance", teams[0].Name) + s.ElementsMatch([]string{own, organization}, teams[0].Apps) + s.Equal(int64(1_000_000), teams[0].Spent[3].SpentMicros) +} diff --git a/acceleration/internal/store/spend_test.go b/acceleration/internal/store/spend_test.go index 78f56e8263..bcdbbc350c 100644 --- a/acceleration/internal/store/spend_test.go +++ b/acceleration/internal/store/spend_test.go @@ -205,6 +205,10 @@ func (s *StoreSuite) TestSpendQueryBudgets() { _, err := s.store.Spend.Teams(s.ctx, organization, []time.Time{s.base}, s.base, true) s.Require().NoError(err) }), "the organization's apps, then one sum a shard") + s.Equal(shards, s.countQueries(func() { + _, err := s.store.Spend.Teams(s.ctx, "app-1", []time.Time{s.base}, s.base, false) + s.Require().NoError(err) + }), "an app in no organization looks up no apps: one sum a shard") s.Equal(shards, s.countQueries(func() { _, err := s.store.Spend.Daily(s.ctx, s.base, s.base.AddDate(0, 0, 1)) s.Require().NoError(err) diff --git a/acceleration/internal/store/store_explain_test.go b/acceleration/internal/store/store_explain_test.go index f967910a33..e07ddd375a 100644 --- a/acceleration/internal/store/store_explain_test.go +++ b/acceleration/internal/store/store_explain_test.go @@ -139,6 +139,11 @@ var seedStatements = []string{ CASE WHEN n % 100 = 0 THEN 'queued' WHEN n % 50 = 0 THEN 'failed' ELSE 'done' END, CASE WHEN n % 200 = 0 THEN 'drawn' ELSE '' END, at, at, CASE WHEN n % 100 <> 0 THEN at + interval '1 minute' END FROM generate_series(1, ?1) AS n, LATERAL (SELECT ?0::timestamptz - (?1 - n) * interval '77 seconds' AS at) AS t`, + + // Two apps seen under org-7, whose requests the seed names it for, so a read of an + // organization's apps sums more than one. + `INSERT INTO app_organizations (app_id, organization_id, seen_at) + VALUES ('customer-7', 'org-7', ?0), ('customer-107', 'org-7', ?0)`, } // explained runs read on a store of the seeded database and answers the plan of each @@ -704,6 +709,10 @@ func (s *StoreSuite) TestEveryHotTableIsReadByIndex() { _, err := store.Spend.Teams(ctx, "customer-7", []time.Time{since}, s.base.AddDate(0, 0, -1), false) return err }}, + {name: "Spend.Teams of an organization", index: "requests_customer_spend_idx", run: func(ctx context.Context, store *Store) error { + _, err := store.Spend.Teams(ctx, "org-7", []time.Time{since}, s.base.AddDate(0, 0, -1), true) + return err + }}, {name: "Spend.Subject", index: "requests_customer_spend_idx", run: func(ctx context.Context, store *Store) error { _, err := store.Spend.Subject(ctx, usage.SubjectRef{OrganizationID: "org-7", Subject: usage.SubjectApp, AppID: "customer-7"}, since, true) return err @@ -718,8 +727,7 @@ func (s *StoreSuite) TestEveryHotTableIsReadByIndex() { APIKey: "key-7"}, since, true) return err }}, - // Of an app in no organization, customer-7: the seed records no app under an organization, - // so a billed one's sum names none. + // Of an app in no organization, customer-7. {name: "Spend.Subject of a category", index: "requests_category_spend_idx", run: func(ctx context.Context, store *Store) error { _, err := store.Spend.Subject(ctx, usage.SubjectRef{OrganizationID: "customer-7", Subject: usage.SubjectCategory, Category: "team:team-7"}, since, false)