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
2 changes: 1 addition & 1 deletion acceleration/internal/api/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
18 changes: 18 additions & 0 deletions acceleration/internal/api/account_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(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},
}))
}

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(insertRequest(context.Background(), s.store, &store.Request{
Expand Down
41 changes: 38 additions & 3 deletions acceleration/internal/api/limits_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -647,11 +647,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) {
_, err := s.store.Requests.InsertMany(context.Background(), []store.Request{{
UsageID: uuid.Must(uuid.NewV7()), 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,
}})
s.Require().NoError(err)
}
Expand Down Expand Up @@ -735,3 +735,38 @@ 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() {
Comment thread
martinmitrevski marked this conversation as resolved.
Resolved
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)
}

// 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)
}
27 changes: 18 additions & 9 deletions acceleration/internal/store/app_organization.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)).
Expand All @@ -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
Expand Down
16 changes: 11 additions & 5 deletions acceleration/internal/store/spend.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Comment thread
martinmitrevski marked this conversation as resolved.
Resolved
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
Expand Down
6 changes: 5 additions & 1 deletion acceleration/internal/store/spend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,9 +202,13 @@ 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)
Comment thread
martinmitrevski marked this conversation as resolved.
Resolved
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)
Expand Down
15 changes: 12 additions & 3 deletions acceleration/internal/store/store_explain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -700,7 +705,12 @@ 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)
Comment thread
martinmitrevski marked this conversation as resolved.
Resolved
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 {
Expand All @@ -717,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)
Expand Down
Loading