From 23a1be9fe5422927587c66cd86a731694a56782e Mon Sep 17 00:00:00 2001 From: thesyncim Date: Mon, 23 Nov 2026 10:28:11 +0000 Subject: [PATCH 1/3] fix(store): count a request only toward its own organization's grants A grant use now matches the grant on the request row's organization as well as its id, on the write path and in the reconcile. An imported request names no grant. --- CHANGELOG.md | 3 + acceleration/internal/policy/policy_test.go | 2 +- acceleration/internal/policy/reserve_test.go | 4 +- acceleration/internal/store/datamove.go | 5 +- acceleration/internal/store/datamove_test.go | 10 ++++ .../internal/store/limit_grant_use.go | 37 ++++++------ .../internal/store/limit_grant_use_test.go | 57 +++++++++++++++---- 7 files changed, 86 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e9b6e6576f..9b5b9413c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -876,6 +876,9 @@ Only a built-in connector takes the OAuth client the deployment keeps in its env ### Only a number on the customer's own trunk moves in an import `/v1/data/import`, and a change applied after it, writes a `phone_numbers` row only when its vendor is exactly `sip_trunk`; any other row is skipped without an error. A number bought at a vendor stays in the vendor account of the deployment that bought it, and its bills already move with the requests, so the destination neither holds it nor bills its months again. A customer that moves keeps a bought number by buying or porting it at the destination. A number bought here and still held is never updated or deleted by an imported row or a replayed change, whatever id it names. An imported `sip_trunk` number is held to the API's rules (E.164, a vendor, a cost that is not negative), and no imported number keeps its `dlc_use_case_id`, which names a use case of the source. +### A request counts only toward its own organization's spend grants + +A request row's cost is added to a grant it names only when the grant belongs to the row's organization, both as the row is written and when the grant uses are reconciled. An imported request names no grant: it was drawn from the grants of the deployment that recorded it. ### A customer can no longer list or speak in another customer's cloned voice diff --git a/acceleration/internal/policy/policy_test.go b/acceleration/internal/policy/policy_test.go index 3832958be7..6adda550cf 100644 --- a/acceleration/internal/policy/policy_test.go +++ b/acceleration/internal/policy/policy_test.go @@ -329,7 +329,7 @@ func (s *PolicySuite) TestAGrantAdmitsPastASpentLimitUntilItIsUsed() { s.NoError(refused) s.ErrorIs(s.admitted().Spend, ErrBudgetSpent, "the hold uses the grant up at once") - s.spendAs(store.Request{UsageID: usageID, CustomerID: s.app, CostMicros: 2_000_000, LimitGrants: drawn}) + s.spendAs(store.Request{UsageID: usageID, CustomerID: s.app, OrganizationID: s.org, CostMicros: 2_000_000, LimitGrants: drawn}) s.enforcer.Written([]routing.Acked{{UsageID: usageID, OrganizationID: s.org, CostMicros: 2_000_000}}) s.never(func() bool { s.enforcer.money.mu.Lock() diff --git a/acceleration/internal/policy/reserve_test.go b/acceleration/internal/policy/reserve_test.go index daa8c7d360..0e56deb29b 100644 --- a/acceleration/internal/policy/reserve_test.go +++ b/acceleration/internal/policy/reserve_test.go @@ -533,8 +533,8 @@ func (s *PolicySuite) TestAGrantsRemainingNeverRisesPastTheTruthAcrossItsCount() }, time.Second, 2*time.Millisecond, "the other router counts the hold") truth.Store(1_000_000 - cost) - s.spendAs(store.Request{UsageID: id, CustomerID: s.app, CostMicros: cost, LimitGrants: []int64{grant.ID}}) - _, err := s.store.LimitGrantUses.InsertMany(s.ctx, []store.GrantUse{{GrantID: grant.ID, UsageID: id, Micros: cost}}) + s.spendAs(store.Request{UsageID: id, CustomerID: s.app, OrganizationID: s.org, CostMicros: cost, LimitGrants: []int64{grant.ID}}) + _, err := s.store.LimitGrantUses.InsertMany(s.ctx, []store.GrantUse{{GrantID: grant.ID, OrganizationID: s.org, UsageID: id, Micros: cost}}) s.Require().NoError(err) a.Written([]routing.Acked{{UsageID: id, OrganizationID: s.org, CostMicros: cost}}) a.Counted([]routing.Acked{{UsageID: id, OrganizationID: s.org, CostMicros: cost}}) diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index cf7e38e29a..296e923c3a 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -1481,10 +1481,11 @@ func (t dataTable) identity() string { } // A request was billed by the deployment that recorded it, so this one never ships it, and // what that one's usage service answered for it is not this one's: a reship of the rows - // this one shipped or had refused leaves it alone. + // this one shipped or had refused leaves it alone. Nor was it drawn from a grant here, + // whose ids are this deployment's own. // Nor is it billed here, and it counts against the importing app's organization alone. if t.name == "requests" { - return "jsonb_build_object('customer_id', ?::text, 'to_ship', false, 'shipped_at', NULL, 'ship_error', '')" + + return "jsonb_build_object('customer_id', ?::text, 'to_ship', false, 'shipped_at', NULL, 'ship_error', '', 'limit_grants', '{}'::bigint[])" + " || jsonb_build_object('billable', false)" + " || jsonb_build_object('organization_id', ?::text)" } diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index d0f793dfa5..9ee13c9e9e 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -3531,6 +3531,16 @@ func (s *DataMoveSuite) TestAnImportedRequestKeepsItsUsageIDAndIsNeverShipped() s.Equal("", moved["ship_error"]) } +func (s *DataMoveSuite) TestAnImportedRequestNamesNoGrant() { + s.Require().NoError(s.source.Requests.Insert(s.ctx, &Request{UsageID: uuid.Must(uuid.NewV7()), Modality: "llm", CustomerID: "acme", + Provider: "openai", Model: "m", StartedAt: time.Now().UTC(), Success: true, Billable: true, CostMicros: 500, + LimitGrants: []int64{7, 8}})) + + moved := s.movedRequest(false) + + s.Empty(moved["limit_grants"], "the source's grant ids name other grants here") +} + // takenRequest writes a request of acme's with the id given, as two deployments' own // sequences can each hand out. func (s *DataMoveSuite) takenRequest(store *Store, id int64) *Request { diff --git a/acceleration/internal/store/limit_grant_use.go b/acceleration/internal/store/limit_grant_use.go index 434a949750..1f6783747c 100644 --- a/acceleration/internal/store/limit_grant_use.go +++ b/acceleration/internal/store/limit_grant_use.go @@ -17,10 +17,12 @@ import ( ) // GrantUse is one row counted toward one grant: its billable cost, by its usage id. +// OrganizationID is the row's: a grant of another organization counts nothing. type GrantUse struct { - GrantID int64 - UsageID uuid.UUID - Micros int64 + GrantID int64 + OrganizationID string + UsageID uuid.UUID + Micros int64 } // GrantUsesOf is what the rows written of requests (written names them by usage id) count @@ -38,7 +40,7 @@ func GrantUsesOf(requests []Request, written []uuid.UUID) []GrantUse { // Only the first of two rows sent with one usage id was written. delete(wrote, request.UsageID) for _, grant := range slices.Compact(slices.Sorted(slices.Values(request.LimitGrants))) { - uses = append(uses, GrantUse{GrantID: grant, UsageID: request.UsageID, Micros: request.CostMicros}) + uses = append(uses, GrantUse{GrantID: grant, OrganizationID: request.OrganizationID, UsageID: request.UsageID, Micros: request.CostMicros}) } } return uses @@ -65,7 +67,7 @@ const grantEndedBefore = "least(g.revoked_at, g.expires_at) < now() - make_inter // InsertMany counts the rows toward their grants in the shared database: each (grant, usage // id) once, however often it is sent, added to the grant's used_micros. A grant that is not -// there, or ended more than GrantUsesKept ago, counts nothing. It says how many it had not +// there, is another organization's, or ended more than GrantUsesKept ago, counts nothing. It says how many it had not // counted before. func (r *LimitGrantUses) InsertMany(ctx context.Context, uses []GrantUse) (int, error) { added := 0 @@ -90,10 +92,11 @@ func addGrantUses(ctx context.Context, tx bun.Tx, uses []GrantUse) (int, error) return 0, nil } grants := make([]int64, len(uses)) + organizations := make([]string, len(uses)) usageIDs := make([]string, len(uses)) micros := make([]int64, len(uses)) for i, use := range uses { - grants[i], usageIDs[i], micros[i] = use.GrantID, use.UsageID.String(), use.Micros + grants[i], organizations[i], usageIDs[i], micros[i] = use.GrantID, use.OrganizationID, use.UsageID.String(), use.Micros } _, err := tx.NewSelect().Model((*LimitGrant)(nil)). Column("lg.id"). @@ -107,10 +110,11 @@ func addGrantUses(ctx context.Context, tx bun.Tx, uses []GrantUse) (int, error) var added int err = tx.NewRaw(` WITH sent AS ( - SELECT * FROM unnest(?::bigint[], ?::uuid[], ?::bigint[]) AS s (grant_id, usage_id, micros) + SELECT * FROM unnest(?::bigint[], ?::text[], ?::uuid[], ?::bigint[]) AS s (grant_id, organization_id, usage_id, micros) ), counted AS ( INSERT INTO limit_grant_uses (grant_id, usage_id, micros) - SELECT s.grant_id, s.usage_id, s.micros FROM sent s JOIN limit_grants g ON g.id = s.grant_id + SELECT s.grant_id, s.usage_id, s.micros FROM sent s + JOIN limit_grants g ON g.id = s.grant_id AND g.organization_id = s.organization_id WHERE NOT coalesce(`+grantEndedBefore+`, false) ON CONFLICT DO NOTHING RETURNING grant_id, micros @@ -120,7 +124,7 @@ WITH sent AS ( WHERE g.id = c.grant_id RETURNING 1 ) -SELECT count(*) FROM counted`, pgdialect.Array(grants), pgdialect.Array(usageIDs), pgdialect.Array(micros), GrantUsesKept.Seconds()).Scan(ctx, &added) +SELECT count(*) FROM counted`, pgdialect.Array(grants), pgdialect.Array(organizations), pgdialect.Array(usageIDs), pgdialect.Array(micros), GrantUsesKept.Seconds()).Scan(ctx, &added) return added, err } @@ -249,7 +253,7 @@ func (r *LimitGrantUses) Reconcile(ctx context.Context) (int, error) { // reconcileGrantsQuery is one page of a shard's rows naming a grant, on from (started_at, id), // read by requests_limit_grants_started_idx. -const reconcileGrantsQuery = "SELECT id, started_at, usage_id, cost_micros, limit_grants FROM requests " + +const reconcileGrantsQuery = "SELECT id, started_at, organization_id, usage_id, cost_micros, limit_grants FROM requests " + "WHERE limit_grants <> '{}' AND (started_at, id) > (?, ?) AND billable AND cost_micros > 0 AND usage_id IS NOT NULL " + "ORDER BY started_at, id LIMIT ?" @@ -268,11 +272,12 @@ func (r *LimitGrantUses) reconcileShard(ctx context.Context, shard bun.IDB, name counted := 0 for { var rows []struct { - ID int64 `bun:"id"` - StartedAt time.Time `bun:"started_at"` - UsageID uuid.UUID `bun:"usage_id"` - CostMicros int64 `bun:"cost_micros"` - LimitGrants []int64 `bun:"limit_grants,array"` + ID int64 `bun:"id"` + StartedAt time.Time `bun:"started_at"` + OrganizationID string `bun:"organization_id"` + UsageID uuid.UUID `bun:"usage_id"` + CostMicros int64 `bun:"cost_micros"` + LimitGrants []int64 `bun:"limit_grants,array"` } err := shard.NewRaw(reconcileGrantsQuery, after, afterID, grantReconcilePage).Scan(ctx, &rows) if err != nil { @@ -281,7 +286,7 @@ func (r *LimitGrantUses) reconcileShard(ctx context.Context, shard bun.IDB, name var uses []GrantUse for _, row := range rows { for _, grant := range slices.Compact(slices.Sorted(slices.Values(row.LimitGrants))) { - uses = append(uses, GrantUse{GrantID: grant, UsageID: row.UsageID, Micros: row.CostMicros}) + uses = append(uses, GrantUse{GrantID: grant, OrganizationID: row.OrganizationID, UsageID: row.UsageID, Micros: row.CostMicros}) } } n, err := r.InsertMany(ctx, uses) diff --git a/acceleration/internal/store/limit_grant_use_test.go b/acceleration/internal/store/limit_grant_use_test.go index d5b869856d..02afb9b4ec 100644 --- a/acceleration/internal/store/limit_grant_use_test.go +++ b/acceleration/internal/store/limit_grant_use_test.go @@ -8,12 +8,18 @@ import ( "github.com/google/uuid" ) -// grantRow is a request row that names grants, written as the writer writes it. +// grantRow is a request row that names grants, written as the writer writes it: of the +// organization of the first grant it names. func (s *StoreSuite) grantRow(store *Store, grants []int64, cost int64, billable bool) Request { row := Request{ - UsageID: uuid.Must(uuid.NewV7()), Modality: "llm", CustomerID: "app-1", Provider: "openai", Model: "m", + UsageID: uuid.Must(uuid.NewV7()), Modality: "llm", CustomerID: "app-1", OrganizationID: "org-1", Provider: "openai", Model: "m", StartedAt: s.base, CostMicros: cost, Billable: billable, Success: true, LimitGrants: grants, } + if len(grants) > 0 { + grant, err := s.store.LimitGrants.Get(s.ctx, "", grants[0]) + s.Require().NoError(err) + row.OrganizationID = grant.OrganizationID + } s.writeAsTheWriter(store, row) return row } @@ -49,6 +55,20 @@ func (s *StoreSuite) TestAWrittenRowCountsTowardEachGrantItNames() { s.EqualValues(200, s.used(b.ID), "a row naming two counts for both") } +func (s *StoreSuite) TestAWrittenRowCountsOnlyTowardItsOwnOrganizationsGrant() { + grant := s.grant(LimitGrant{AmountMicros: 10_000}) + written := func(organization string, cost int64) Request { + return Request{ + UsageID: uuid.Must(uuid.NewV7()), Modality: "llm", CustomerID: "app-2", OrganizationID: organization, Provider: "openai", + Model: "m", StartedAt: s.base, CostMicros: cost, Billable: true, Success: true, LimitGrants: []int64{grant.ID}, + } + } + + s.writeAsTheWriter(s.store, written("org-2", 300), written("org-1", 50), written("", 700)) + + s.EqualValues(50, s.used(grant.ID), "a row of another organization, or of none, naming the grant counts nothing") +} + func (s *StoreSuite) TestARowWrittenTwiceCountsOnceTowardItsGrant() { grant := s.grant(LimitGrant{AmountMicros: 10_000}) row := s.grantRow(s.store, []int64{grant.ID}, 300, true) @@ -58,13 +78,13 @@ func (s *StoreSuite) TestARowWrittenTwiceCountsOnceTowardItsGrant() { written, err := s.store.Requests.InsertMany(s.ctx, []Request{again, again}) s.Require().NoError(err) s.Empty(written, "the shard has it") - counted, err := s.store.LimitGrantUses.InsertMany(s.ctx, []GrantUse{{GrantID: grant.ID, UsageID: row.UsageID, Micros: 300}}) + counted, err := s.store.LimitGrantUses.InsertMany(s.ctx, []GrantUse{{GrantID: grant.ID, OrganizationID: "org-1", UsageID: row.UsageID, Micros: 300}}) s.Require().NoError(err) s.Zero(counted, "nor does counting it again") s.EqualValues(300, s.used(grant.ID)) fresh := Request{ - UsageID: uuid.Must(uuid.NewV7()), Modality: "llm", CustomerID: "app-1", Provider: "openai", Model: "m", + UsageID: uuid.Must(uuid.NewV7()), Modality: "llm", CustomerID: "app-1", OrganizationID: "org-1", Provider: "openai", Model: "m", StartedAt: s.base, CostMicros: 50, Billable: true, Success: true, LimitGrants: []int64{grant.ID}, } s.writeAsTheWriter(s.store, fresh, fresh) @@ -75,10 +95,10 @@ func (s *StoreSuite) TestGrantUsesCountedIsHowManyGrantsEachRowCountsToward() { a, b := s.grant(LimitGrant{AmountMicros: 10_000}), s.grant(LimitGrant{AmountMicros: 10_000}) both, one, other, unasked := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()) _, err := s.store.LimitGrantUses.InsertMany(s.ctx, []GrantUse{ - {GrantID: a.ID, UsageID: both, Micros: 10}, - {GrantID: b.ID, UsageID: both, Micros: 10}, - {GrantID: a.ID, UsageID: one, Micros: 10}, - {GrantID: b.ID, UsageID: unasked, Micros: 10}, + {GrantID: a.ID, OrganizationID: "org-1", UsageID: both, Micros: 10}, + {GrantID: b.ID, OrganizationID: "org-1", UsageID: both, Micros: 10}, + {GrantID: a.ID, OrganizationID: "org-1", UsageID: one, Micros: 10}, + {GrantID: b.ID, OrganizationID: "org-1", UsageID: unasked, Micros: 10}, }) s.Require().NoError(err) @@ -113,7 +133,7 @@ func (s *StoreSuite) TestTheUsesOfAGrantEndedLongAgoArePruned() { s.Equal(1, uses(recent.ID), "a grant ended inside GrantUsesKept keeps them") s.Equal(1, uses(live.ID)) s.EqualValues(300, s.used(expired.ID), "what it paid for stays") - counted, err := s.store.LimitGrantUses.InsertMany(s.ctx, []GrantUse{{GrantID: revoked.ID, UsageID: uuid.Must(uuid.NewV7()), Micros: 5}}) + counted, err := s.store.LimitGrantUses.InsertMany(s.ctx, []GrantUse{{GrantID: revoked.ID, OrganizationID: "org-1", UsageID: uuid.Must(uuid.NewV7()), Micros: 5}}) s.Require().NoError(err) s.Zero(counted, "nor does it count anything more") s.EqualValues(300, s.used(revoked.ID)) @@ -132,7 +152,7 @@ func (s *ShardedStoreSuite) TestRowsInEveryShardCountTowardTheirGrant() { // or stopped before it, leaves it. func (s *StoreSuite) uncounted(store *Store, startedAt time.Time, cost int64, grants ...int64) { lost := Request{ - UsageID: uuid.Must(uuid.NewV7()), Modality: "llm", CustomerID: "app-1", Provider: "openai", Model: "m", + UsageID: uuid.Must(uuid.NewV7()), Modality: "llm", CustomerID: "app-1", OrganizationID: "org-1", Provider: "openai", Model: "m", StartedAt: startedAt, CostMicros: cost, Billable: true, Success: true, LimitGrants: grants, } s.Require().NoError(prepareRequest(&lost)) @@ -158,6 +178,21 @@ func (s *ShardedStoreSuite) TestAReconcileCountsARowItsWriterDidNot() { s.EqualValues(370, s.used(grant.ID)) } +func (s *ShardedStoreSuite) TestAReconcileCountsARowOnlyTowardItsOwnOrganizationsGrant() { + grant := s.grant(LimitGrant{AmountMicros: 10_000}) + s.uncounted(s.other, s.base, 70, grant.ID) + foreign := Request{ + UsageID: uuid.Must(uuid.NewV7()), Modality: "llm", CustomerID: "app-2", OrganizationID: "org-2", Provider: "openai", Model: "m", + StartedAt: s.base, CostMicros: 9_000, Billable: true, Success: true, LimitGrants: []int64{grant.ID}, + } + s.Require().NoError(prepareRequest(&foreign)) + _, err := s.other.ShardDB().NewInsert().Model(&foreign).Exec(s.ctx) + s.Require().NoError(err) + + s.Equal(1, s.reconcile(), "only the row of the grant's own organization") + s.EqualValues(70, s.used(grant.ID)) +} + func (s *ShardedStoreSuite) TestAReconcileReadsOnlyTheRowsSinceTheLastLessItsOverlap() { grant := s.grant(LimitGrant{AmountMicros: 1_000_000}) for range grantReconcilePage + 1 { @@ -212,7 +247,7 @@ func (s *StoreSuite) TestLimitGrantUseQueryBudgets() { first, second := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()) s.Equal(4, s.countQueries(func() { counted, err := s.store.LimitGrantUses.InsertMany(s.ctx, []GrantUse{ - {GrantID: a.ID, UsageID: first, Micros: 1}, {GrantID: b.ID, UsageID: first, Micros: 1}, {GrantID: a.ID, UsageID: second, Micros: 1}, + {GrantID: a.ID, OrganizationID: "org-1", UsageID: first, Micros: 1}, {GrantID: b.ID, OrganizationID: "org-1", UsageID: first, Micros: 1}, {GrantID: a.ID, OrganizationID: "org-1", UsageID: second, Micros: 1}, }) s.Require().NoError(err) s.Equal(3, counted) From 5e61620afbe6d9bca10476296da185a61e058f58 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Mon, 23 Nov 2026 11:48:40 +0000 Subject: [PATCH 2/3] fix(store): a grant use is owned by the row's app as well as its organization A row written without its organization, as an app in none has it or as the writer leaves a row it could not attribute, now counts toward the grants of its app: those of the organization the app was last seen under, or the app's own id for an app in none. A grant of any other organization still counts nothing. --- CHANGELOG.md | 3 +- .../internal/store/limit_grant_use.go | 30 ++++++++----- .../internal/store/limit_grant_use_test.go | 43 +++++++++++++++++++ 3 files changed, 65 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b5b9413c1..05181752df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -876,9 +876,10 @@ Only a built-in connector takes the OAuth client the deployment keeps in its env ### Only a number on the customer's own trunk moves in an import `/v1/data/import`, and a change applied after it, writes a `phone_numbers` row only when its vendor is exactly `sip_trunk`; any other row is skipped without an error. A number bought at a vendor stays in the vendor account of the deployment that bought it, and its bills already move with the requests, so the destination neither holds it nor bills its months again. A customer that moves keeps a bought number by buying or porting it at the destination. A number bought here and still held is never updated or deleted by an imported row or a replayed change, whatever id it names. An imported `sip_trunk` number is held to the API's rules (E.164, a vendor, a cost that is not negative), and no imported number keeps its `dlc_use_case_id`, which names a use case of the source. + ### A request counts only toward its own organization's spend grants -A request row's cost is added to a grant it names only when the grant belongs to the row's organization, both as the row is written and when the grant uses are reconciled. An imported request names no grant: it was drawn from the grants of the deployment that recorded it. +A request row's cost is added to a grant it names only when the grant belongs to the row's organization or to its app's (the organization the app is in, or the app itself for an app in none), both as the row is written and when the grant uses are reconciled. An imported request names no grant: it was drawn from the grants of the deployment that recorded it. ### A customer can no longer list or speak in another customer's cloned voice diff --git a/acceleration/internal/store/limit_grant_use.go b/acceleration/internal/store/limit_grant_use.go index 1f6783747c..b46d73e456 100644 --- a/acceleration/internal/store/limit_grant_use.go +++ b/acceleration/internal/store/limit_grant_use.go @@ -17,9 +17,11 @@ import ( ) // GrantUse is one row counted toward one grant: its billable cost, by its usage id. -// OrganizationID is the row's: a grant of another organization counts nothing. +// CustomerID and OrganizationID are the row's: a grant of neither the row's organization nor +// its app's counts nothing. type GrantUse struct { GrantID int64 + CustomerID string OrganizationID string UsageID uuid.UUID Micros int64 @@ -40,7 +42,7 @@ func GrantUsesOf(requests []Request, written []uuid.UUID) []GrantUse { // Only the first of two rows sent with one usage id was written. delete(wrote, request.UsageID) for _, grant := range slices.Compact(slices.Sorted(slices.Values(request.LimitGrants))) { - uses = append(uses, GrantUse{GrantID: grant, OrganizationID: request.OrganizationID, UsageID: request.UsageID, Micros: request.CostMicros}) + uses = append(uses, GrantUse{GrantID: grant, CustomerID: request.CustomerID, OrganizationID: request.OrganizationID, UsageID: request.UsageID, Micros: request.CostMicros}) } } return uses @@ -67,8 +69,8 @@ const grantEndedBefore = "least(g.revoked_at, g.expires_at) < now() - make_inter // InsertMany counts the rows toward their grants in the shared database: each (grant, usage // id) once, however often it is sent, added to the grant's used_micros. A grant that is not -// there, is another organization's, or ended more than GrantUsesKept ago, counts nothing. It says how many it had not -// counted before. +// there, is of neither the row's organization nor its app's, or ended more than GrantUsesKept +// ago, counts nothing. It says how many it had not counted before. func (r *LimitGrantUses) InsertMany(ctx context.Context, uses []GrantUse) (int, error) { added := 0 for start := 0; start < len(uses); start += grantUsesChunk { @@ -92,11 +94,12 @@ func addGrantUses(ctx context.Context, tx bun.Tx, uses []GrantUse) (int, error) return 0, nil } grants := make([]int64, len(uses)) + customers := make([]string, len(uses)) organizations := make([]string, len(uses)) usageIDs := make([]string, len(uses)) micros := make([]int64, len(uses)) for i, use := range uses { - grants[i], organizations[i], usageIDs[i], micros[i] = use.GrantID, use.OrganizationID, use.UsageID.String(), use.Micros + grants[i], customers[i], organizations[i], usageIDs[i], micros[i] = use.GrantID, use.CustomerID, use.OrganizationID, use.UsageID.String(), use.Micros } _, err := tx.NewSelect().Model((*LimitGrant)(nil)). Column("lg.id"). @@ -107,14 +110,20 @@ func addGrantUses(ctx context.Context, tx bun.Tx, uses []GrantUse) (int, error) if err != nil { return 0, err } + // A grant is the row's organization's, or that of the row's app as the enforcer drew it: the + // organization the app was last seen under, or for an app in none the app itself. Either + // one serves, since a row is written without its organization when the app could not be + // looked up, and the app's membership is recorded in the background after its first grant + // may be drawn. var added int err = tx.NewRaw(` WITH sent AS ( - SELECT * FROM unnest(?::bigint[], ?::text[], ?::uuid[], ?::bigint[]) AS s (grant_id, organization_id, usage_id, micros) + SELECT * FROM unnest(?::bigint[], ?::text[], ?::text[], ?::uuid[], ?::bigint[]) AS s (grant_id, customer_id, organization_id, usage_id, micros) ), counted AS ( INSERT INTO limit_grant_uses (grant_id, usage_id, micros) SELECT s.grant_id, s.usage_id, s.micros FROM sent s - JOIN limit_grants g ON g.id = s.grant_id AND g.organization_id = s.organization_id + LEFT JOIN app_organizations ao ON ao.app_id = s.customer_id + JOIN limit_grants g ON g.id = s.grant_id AND g.organization_id IN (s.organization_id, coalesce(ao.organization_id, s.customer_id)) WHERE NOT coalesce(`+grantEndedBefore+`, false) ON CONFLICT DO NOTHING RETURNING grant_id, micros @@ -124,7 +133,7 @@ WITH sent AS ( WHERE g.id = c.grant_id RETURNING 1 ) -SELECT count(*) FROM counted`, pgdialect.Array(grants), pgdialect.Array(organizations), pgdialect.Array(usageIDs), pgdialect.Array(micros), GrantUsesKept.Seconds()).Scan(ctx, &added) +SELECT count(*) FROM counted`, pgdialect.Array(grants), pgdialect.Array(customers), pgdialect.Array(organizations), pgdialect.Array(usageIDs), pgdialect.Array(micros), GrantUsesKept.Seconds()).Scan(ctx, &added) return added, err } @@ -253,7 +262,7 @@ func (r *LimitGrantUses) Reconcile(ctx context.Context) (int, error) { // reconcileGrantsQuery is one page of a shard's rows naming a grant, on from (started_at, id), // read by requests_limit_grants_started_idx. -const reconcileGrantsQuery = "SELECT id, started_at, organization_id, usage_id, cost_micros, limit_grants FROM requests " + +const reconcileGrantsQuery = "SELECT id, started_at, customer_id, organization_id, usage_id, cost_micros, limit_grants FROM requests " + "WHERE limit_grants <> '{}' AND (started_at, id) > (?, ?) AND billable AND cost_micros > 0 AND usage_id IS NOT NULL " + "ORDER BY started_at, id LIMIT ?" @@ -274,6 +283,7 @@ func (r *LimitGrantUses) reconcileShard(ctx context.Context, shard bun.IDB, name var rows []struct { ID int64 `bun:"id"` StartedAt time.Time `bun:"started_at"` + CustomerID string `bun:"customer_id"` OrganizationID string `bun:"organization_id"` UsageID uuid.UUID `bun:"usage_id"` CostMicros int64 `bun:"cost_micros"` @@ -286,7 +296,7 @@ func (r *LimitGrantUses) reconcileShard(ctx context.Context, shard bun.IDB, name var uses []GrantUse for _, row := range rows { for _, grant := range slices.Compact(slices.Sorted(slices.Values(row.LimitGrants))) { - uses = append(uses, GrantUse{GrantID: grant, OrganizationID: row.OrganizationID, UsageID: row.UsageID, Micros: row.CostMicros}) + uses = append(uses, GrantUse{GrantID: grant, CustomerID: row.CustomerID, OrganizationID: row.OrganizationID, UsageID: row.UsageID, Micros: row.CostMicros}) } } n, err := r.InsertMany(ctx, uses) diff --git a/acceleration/internal/store/limit_grant_use_test.go b/acceleration/internal/store/limit_grant_use_test.go index 02afb9b4ec..0270060355 100644 --- a/acceleration/internal/store/limit_grant_use_test.go +++ b/acceleration/internal/store/limit_grant_use_test.go @@ -69,6 +69,34 @@ func (s *StoreSuite) TestAWrittenRowCountsOnlyTowardItsOwnOrganizationsGrant() { s.EqualValues(50, s.used(grant.ID), "a row of another organization, or of none, naming the grant counts nothing") } +// unresolved is a request row of the app naming the grant, written without its organization, +// as an app in none has it and as the writer leaves a row it could not look the app up for. +func (s *StoreSuite) unresolved(app string, cost int64, grant int64) Request { + return Request{ + UsageID: uuid.Must(uuid.NewV7()), Modality: "llm", CustomerID: app, Provider: "openai", Model: "m", + StartedAt: s.base, CostMicros: cost, Billable: true, Success: true, LimitGrants: []int64{grant}, + } +} + +// member records the app as seen under the organization. +func (s *StoreSuite) member(app, organization string) { + s.Require().NoError(s.store.AppOrganizations.Upsert(s.ctx, &AppOrganization{AppID: app, OrganizationID: organization})) +} + +func (s *StoreSuite) TestARowWithoutItsOrganizationCountsTowardItsAppsGrants() { + own := s.grant(LimitGrant{OrganizationID: "app-alone", AmountMicros: 10_000}) + theirs := s.grant(LimitGrant{AmountMicros: 10_000}) + s.member("app-1", "org-1") + s.member("org-1", "org-2") + + s.writeAsTheWriter(s.store, s.unresolved("app-alone", 100, own.ID), s.unresolved("app-1", 20, theirs.ID), + s.unresolved("app-2", 3_000, own.ID), s.unresolved("app-2", 3_000, theirs.ID), s.unresolved("org-1", 3_000, theirs.ID)) + + s.EqualValues(100, s.used(own.ID), "an app in no organization keeps its grants under its own id") + s.EqualValues(20, s.used(theirs.ID), "a row of the organization's app counts; one of another app, or of an app of "+ + "another organization whose id is this one's, does not") +} + func (s *StoreSuite) TestARowWrittenTwiceCountsOnceTowardItsGrant() { grant := s.grant(LimitGrant{AmountMicros: 10_000}) row := s.grantRow(s.store, []int64{grant.ID}, 300, true) @@ -193,6 +221,21 @@ func (s *ShardedStoreSuite) TestAReconcileCountsARowOnlyTowardItsOwnOrganization s.EqualValues(70, s.used(grant.ID)) } +func (s *ShardedStoreSuite) TestAReconcileCountsARowWithoutItsOrganizationTowardItsAppsGrants() { + own := s.grant(LimitGrant{OrganizationID: "app-alone", AmountMicros: 10_000}) + theirs := s.grant(LimitGrant{AmountMicros: 10_000}) + s.member("app-1", "org-1") + for _, row := range []Request{s.unresolved("app-alone", 100, own.ID), s.unresolved("app-1", 20, theirs.ID), s.unresolved("app-2", 3_000, own.ID)} { + s.Require().NoError(prepareRequest(&row)) + _, err := s.other.ShardDB().NewInsert().Model(&row).Exec(s.ctx) + s.Require().NoError(err) + } + + s.Equal(2, s.reconcile(), "the rows of the grants' own apps") + s.EqualValues(100, s.used(own.ID)) + s.EqualValues(20, s.used(theirs.ID)) +} + func (s *ShardedStoreSuite) TestAReconcileReadsOnlyTheRowsSinceTheLastLessItsOverlap() { grant := s.grant(LimitGrant{AmountMicros: 1_000_000}) for range grantReconcilePage + 1 { From 560d3458dcce2581fb9f4e2dea451cbcd4a2df30 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Mon, 23 Nov 2026 13:38:15 +0000 Subject: [PATCH 3/3] fix(store): a grant scoped to an app counts only that app's rows, and a refused use is counted --- CHANGELOG.md | 2 +- .../internal/store/limit_grant_use.go | 46 +++++++++++++++---- .../internal/store/limit_grant_use_test.go | 39 ++++++++++++++++ 3 files changed, 76 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 05181752df..153ee7a0ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -879,7 +879,7 @@ Only a built-in connector takes the OAuth client the deployment keeps in its env ### A request counts only toward its own organization's spend grants -A request row's cost is added to a grant it names only when the grant belongs to the row's organization or to its app's (the organization the app is in, or the app itself for an app in none), both as the row is written and when the grant uses are reconciled. An imported request names no grant: it was drawn from the grants of the deployment that recorded it. +A request row's cost is added to a grant it names only when the grant belongs to the row's organization or to its app's (the organization the app is in, or the app itself for an app in none), both as the row is written and when the grant uses are reconciled. A grant scoped to an app, or to its key or user, counts only that app's rows. A use refused because the grant is not the row's is counted on `/metrics` as `router_usage_grant_uses_refused_total`. An imported request names no grant: it was drawn from the grants of the deployment that recorded it. ### A customer can no longer list or speak in another customer's cloned voice diff --git a/acceleration/internal/store/limit_grant_use.go b/acceleration/internal/store/limit_grant_use.go index b46d73e456..18a313685a 100644 --- a/acceleration/internal/store/limit_grant_use.go +++ b/acceleration/internal/store/limit_grant_use.go @@ -10,12 +10,22 @@ import ( "time" "github.com/google/uuid" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" "github.com/uptrace/bun" "github.com/uptrace/bun/dialect/pgdialect" "github.com/GetStream/Vision-Agents/acceleration/internal/stack" ) +// grantUsesRefused counts what a grant's owner check turned away, so a grant that pays for +// less than it admitted shows why. +var grantUsesRefused = promauto.NewCounter(prometheus.CounterOpts{ + Namespace: "router", + Name: "usage_grant_uses_refused_total", + Help: "Attempts to count a usage row toward a live grant of neither its organization nor its app, or scoped to another app, that had not counted it before", +}) + // GrantUse is one row counted toward one grant: its billable cost, by its usage id. // CustomerID and OrganizationID are the row's: a grant of neither the row's organization nor // its app's counts nothing. @@ -69,8 +79,9 @@ const grantEndedBefore = "least(g.revoked_at, g.expires_at) < now() - make_inter // InsertMany counts the rows toward their grants in the shared database: each (grant, usage // id) once, however often it is sent, added to the grant's used_micros. A grant that is not -// there, is of neither the row's organization nor its app's, or ended more than GrantUsesKept -// ago, counts nothing. It says how many it had not counted before. +// there, is of neither the row's organization nor its app's, is scoped to another app, or ended +// more than GrantUsesKept ago, counts nothing; one refused on whose it is is counted on +// /metrics. It says how many it had not counted before. func (r *LimitGrantUses) InsertMany(ctx context.Context, uses []GrantUse) (int, error) { added := 0 for start := 0; start < len(uses); start += grantUsesChunk { @@ -114,17 +125,24 @@ func addGrantUses(ctx context.Context, tx bun.Tx, uses []GrantUse) (int, error) // organization the app was last seen under, or for an app in none the app itself. Either // one serves, since a row is written without its organization when the app could not be // looked up, and the app's membership is recorded in the background after its first grant - // may be drawn. - var added int + // may be drawn. A grant scoped to an app is that app's alone. + var counts struct { + Added int `bun:"added"` + Refused int `bun:"refused"` + } err = tx.NewRaw(` WITH sent AS ( SELECT * FROM unnest(?::bigint[], ?::text[], ?::text[], ?::uuid[], ?::bigint[]) AS s (grant_id, customer_id, organization_id, usage_id, micros) -), counted AS ( - INSERT INTO limit_grant_uses (grant_id, usage_id, micros) - SELECT s.grant_id, s.usage_id, s.micros FROM sent s +), granted AS ( + SELECT s.grant_id, s.usage_id, s.micros, + g.organization_id IN (s.organization_id, coalesce(ao.organization_id, s.customer_id)) AND g.app_id IN ('', s.customer_id) AS owned + FROM sent s LEFT JOIN app_organizations ao ON ao.app_id = s.customer_id - JOIN limit_grants g ON g.id = s.grant_id AND g.organization_id IN (s.organization_id, coalesce(ao.organization_id, s.customer_id)) + JOIN limit_grants g ON g.id = s.grant_id WHERE NOT coalesce(`+grantEndedBefore+`, false) +), counted AS ( + INSERT INTO limit_grant_uses (grant_id, usage_id, micros) + SELECT grant_id, usage_id, micros FROM granted WHERE owned ON CONFLICT DO NOTHING RETURNING grant_id, micros ), raised AS ( @@ -133,8 +151,16 @@ WITH sent AS ( WHERE g.id = c.grant_id RETURNING 1 ) -SELECT count(*) FROM counted`, pgdialect.Array(grants), pgdialect.Array(customers), pgdialect.Array(organizations), pgdialect.Array(usageIDs), pgdialect.Array(micros), GrantUsesKept.Seconds()).Scan(ctx, &added) - return added, err +SELECT (SELECT count(*) FROM counted) AS added, + (SELECT count(*) FROM granted r WHERE NOT r.owned + AND NOT EXISTS (SELECT 1 FROM limit_grant_uses u WHERE u.grant_id = r.grant_id AND u.usage_id = r.usage_id)) AS refused`, + pgdialect.Array(grants), pgdialect.Array(customers), pgdialect.Array(organizations), pgdialect.Array(usageIDs), pgdialect.Array(micros), + GrantUsesKept.Seconds()).Scan(ctx, &counts) + if err != nil { + return 0, err + } + grantUsesRefused.Add(float64(counts.Refused)) + return counts.Added, nil } // Prune forgets which rows counted toward the grants that expired or were revoked diff --git a/acceleration/internal/store/limit_grant_use_test.go b/acceleration/internal/store/limit_grant_use_test.go index 0270060355..f9306e81e1 100644 --- a/acceleration/internal/store/limit_grant_use_test.go +++ b/acceleration/internal/store/limit_grant_use_test.go @@ -6,6 +6,9 @@ import ( "time" "github.com/google/uuid" + "github.com/prometheus/client_golang/prometheus/testutil" + + "github.com/GetStream/Vision-Agents/acceleration/internal/usage" ) // grantRow is a request row that names grants, written as the writer writes it: of the @@ -97,6 +100,42 @@ func (s *StoreSuite) TestARowWithoutItsOrganizationCountsTowardItsAppsGrants() { "another organization whose id is this one's, does not") } +func (s *StoreSuite) TestAGrantScopedToAnAppCountsOnlyThatAppsRows() { + app := s.grant(LimitGrant{Subject: usage.SubjectApp, AppID: "app-1", AmountMicros: 10_000}) + key := s.grant(LimitGrant{Subject: usage.SubjectAPIKey, AppID: "app-1", APIKey: "k", AmountMicros: 10_000}) + written := func(app string, cost int64, grant int64) Request { + return Request{ + UsageID: uuid.Must(uuid.NewV7()), Modality: "llm", CustomerID: app, OrganizationID: "org-1", Provider: "openai", + Model: "m", StartedAt: s.base, CostMicros: cost, Billable: true, Success: true, LimitGrants: []int64{grant}, + } + } + + s.writeAsTheWriter(s.store, written("app-1", 40, app.ID), written("app-3", 900, app.ID), written("app-1", 5, key.ID), written("app-3", 900, key.ID)) + + s.EqualValues(40, s.used(app.ID), "a row of another app of the organization counts nothing toward the app's grant") + s.EqualValues(5, s.used(key.ID), "nor toward a grant of the app's key") +} + +func (s *StoreSuite) TestAUseRefusedOnWhoseTheGrantIsIsCountedOnMetrics() { + grant := s.grant(LimitGrant{AmountMicros: 10_000}) + moved := uuid.Must(uuid.NewV7()) + _, err := s.store.LimitGrantUses.InsertMany(s.ctx, []GrantUse{{GrantID: grant.ID, CustomerID: "app-1", OrganizationID: "org-1", UsageID: moved, Micros: 10}}) + s.Require().NoError(err) + before := testutil.ToFloat64(grantUsesRefused) + + _, err = s.store.LimitGrantUses.InsertMany(s.ctx, []GrantUse{ + {GrantID: grant.ID, CustomerID: "app-1", OrganizationID: "org-1", UsageID: uuid.Must(uuid.NewV7()), Micros: 10}, + {GrantID: grant.ID, CustomerID: "app-2", OrganizationID: "org-2", UsageID: uuid.Must(uuid.NewV7()), Micros: 10}, + {GrantID: grant.ID, CustomerID: "app-2", OrganizationID: "org-2", UsageID: moved, Micros: 10}, + {GrantID: grant.ID + 1_000_000, CustomerID: "app-2", OrganizationID: "org-2", UsageID: uuid.Must(uuid.NewV7()), Micros: 10}, + }) + s.Require().NoError(err) + + s.InDelta(1, testutil.ToFloat64(grantUsesRefused)-before, 0, "only the use of another organization the grant had not counted; "+ + "a use it counts, one it counted before and one of a grant that is not there are not refusals") + s.EqualValues(20, s.used(grant.ID)) +} + func (s *StoreSuite) TestARowWrittenTwiceCountsOnceTowardItsGrant() { grant := s.grant(LimitGrant{AmountMicros: 10_000}) row := s.grantRow(s.store, []int64{grant.ID}, 300, true)