Skip to content

fix(store): spend limits, resets and grants keep whose they are - #2396

Draft
thesyncim wants to merge 6 commits into
mainfrom
fix/ai-3765-limit-owner
Draft

thesyncim wants to merge 6 commits into
mainfrom
fix/ai-3765-limit-owner

Conversation

@thesyncim

@thesyncim thesyncim commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Problem
A spend limit, a reset or a grant names its owner by organization_id, which for an app in no organization is the app's own id. The row did not say which of the two kinds of owner that id is.

Fix

  • limits, usage_resets and limit_grants say whose organization_id is (billed). An owner is the key admission already kept its accounts by (store.LimitOwner), from the same billed signal as AI-3735: refuse another organization's app_id in spend limits #2372.
  • Every limits, usage, reset, grant and teams operation reads and writes its owner's rows. Admission holds an account to its owner's limits, resets and grants, and a written row counts toward its owner's grants.
  • The holds of an app in no organization have Redis keys of their own (hold:app:). An organization's keys do not change.
  • The manage operations take an organization, and by id reach any row.
  • Migrations: three nullable columns; then, built concurrently, one unique index per owner in place of limits_one_per_level, an index on the organization id and one on the audit log. An earlier release inserts and reads as before. A row it writes is unique against both owners.
  • A row with no owner is attributed each minute from the audit log and the recorded organizations (Store.AttributeLimits). Until then it stays in force, and staff manage it.
  • While both releases run, holds of an app in no organization are shared only among routers of one release; spend and limits are still counted by both.
  • Merge after the lower-numbered global migrations of open PRs.

Tests

  • SelfHostedLimitsSuite (limit_owner_test.go): both directions over HTTP for list, read, create, change, delete, usage, teams, parents, resets, grants, the cap on live grants and the search a limit refuses, with what a row of no known owner shows and holds. Eight of them, run on main, fail.
  • PolicySuite (limit_owner_test.go): limits, grants, resets, a write's re-read and shared holds at admission. Of seven run on main, without the column, the three that only need one owner's limit or hold fail, and the four that give both owners a limit at one place fail on the second insert.
  • StoreSuite (limit_owner_test.go): attribution, the unique places and the rows counted toward a grant. They cover new code, so they have no run on main.
  • The limits suites and the policy suite's limit, grant, reset and hold tests of main at 83d7b27 pass on the migrated database.

Fixes AI-3765

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: NO-GO

Reviewed ad5532a merged onto main at 21b2551 (main moved to b11e578 during the review; nothing new touches this PR's areas). CI on the head is green, but that run predates the conflict with main.

Main partly covers AI-3765. #2400 (merged 2026-11-25) answers 403 to an app in no organization whose id is a known organization's, on the customer limits, usage, resets, grants and teams operations. It leaves admission alone: rows are still keyed by id, so an organization's limit still holds the same-id app's work (#2400's own TestALimitOfASharedIdHoldsTheAppsWorkAndTheOrganizations asserts this). This PR is still needed for admission, holds and grants.

Conflicts with main

  • internal/policy/reads.go, internal/policy/spend.go: textual and easy. Keep main's Enforcer.Funded and pass #2482's new from argument to keepLimits.

  • internal/api/limit_owner_test.go against #2400's limits_shared_id_test.go: semantic and hard. Five helpers are declared twice with different signatures (limitAs, grantAs, limitsAs, grantsAs, usageAs), and refusedSearch too. With the PR's helpers renamed, the merge compiles and 11 SelfHostedLimitsSuite tests fail:

    • 8 of this PR's tests get #2400's 403 once the organization of the id is known.
    • 3 of #2400's tests (TestALimitOfASharedIdHoldsTheAppsWorkAndTheOrganizations, TestAnAppInTheOrganizationOfItsOwnIdKeepsItsLimits, TestAnOrganizationThatComesLaterHasTheLimits) assert the shared behaviour this PR removes.

    This needs a decision: with owner-keyed rows, is errLimitsManaged still wanted for an app in none, and which of #2400's tests go?

Findings with no diff line

  • [Should fix] R1.4 acceleration/README.md:536,549-556: the limits section does not say that an organization and an app in none of one id each have their own limits, resets and grants. It also does not say that a 409 limit_exists may name no limit ("which support can change"), or that a row with no known owner is hidden from customers and holds both owners until it is attributed. Lines 553-555 still say staff "reach the same operations ... what they write is the customer's", which R1.3 contradicts. The PR changes no .md file.
  • [Nit] R1.8 Rollback: the previous release's indexLimits (policy/limits.go) keeps one row per place. Once both owners of one id hold a place, a rolled-back router applies the later row to both. This only happens for a shared id; worth a line in the body's rollback notes.

Checked and sound

  • The previous release runs on the migrated schema. I ran main with these two migrations, renumbered: main's limits API suites (83), store limit/grant/reset tests (80) and policy limit/grant/reset/hold tests (106) all pass.
  • The partial unique indexes and the AttributeLimits cases are pinned by tests.
  • The addGrantUses ownership SQL is pinned by tests.
  • hold:app:{id} keys stay in their slot and do not collide.
  • No operation's shape changed, so the spec and the SDKs are unaffected.
  • Logs carry counts only.

Mutations: 38 checked, 32 killed. Survivors: the four staff-write refreshes (R1.5) and the attributeLimits start (R1.6). The sixth, grantKey with the organization's prefix, is equivalent: grant ids are global, and planFlush plans grant keys with an explicit slot.

Verdict: request changes, for R1.1 (migrations refused on any database already on main), R1.2 (a limit an app writes is not enforced) and R1.3/R1.4. R1.5 and R1.6 are follow-ups that do not block.

@@ -0,0 +1,17 @@
-- +goose Up

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Blocker] R1.1 Both versions (20270301001100, 20270301001110) are lower than main's newest global migration, 20270301008300. store.migrate builds its goose provider without WithAllowOutofOrder, so any database already on main refuses the migration.

I checked it on the tree merged with main: migrate, revert these two by hand, then migrate again. The second migrate answered store: migrate global: detected 2 missing (out-of-order) migrations lower than database version (20270301008300): versions 20270301001100,20270301001110.

Fix: renumber both, e.g. to 20270301008400 and 20270301008410. No open PR has a global migration above 8300. Also update schema/global.sql and any comment that names the old numbers.


// limitsOwner is whose limits, resets and grants the caller reads and writes: its organization's
// or, for an app in none, its own.
func (s *Server) limitsOwner(ctx context.Context, organization string) string {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Blocker] R1.2 The owner comes from the request's organization header (billedOrganization). Admission keys the account by the organization the app is recorded under (Enforcer.accountOf / decided.organization).

Take an app recorded in the organization of its own id that sends no organization header. It writes billed=false rows. Its admission account is the organization's, and HeldTo there keeps only billed true or NULL rows, so the app's own limit never applies.

Probe: upsert AppOrganization{AppID: id, OrganizationID: id}, then backend(id, "") POSTs an organization limit of 0, then /v1/search.

  • On the merge base the search is refused (402).
  • On this head it is not.

AttributeLimits already gives such an app's old rows to the organization (named.organization_id = r.organization_id), so an app's attributed rows and its new rows disagree.

Fix: for the customer operations, take billed from the same membership admission uses (as #2400's Members check does: an app recorded in the organization of its own id belongs to that organization). Add the probe as a test.

return nil, errNoLimits
}
return s.listLimits(ctx, request.OrganizationId, &request.ListLimitsParams)
return s.listLimits(ctx, request.OrganizationId, true, &request.ListLimitsParams)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.3 Staff can no longer reach the limits of an app in no organization by its id. The manage list, create, usage, reset, grants and teams operations all treat organization_id as an organization (billed=true). Probe with backend(id, ""), which creates a team limit; staff then list with organization_id=<id> and create an organization limit of 0:

  • Base: staff's list shows the app's row, and staff's limit of 0 refuses the app's work.
  • Head: the list is empty, and the app's work is not refused, because the new row is written as the organization's.

Fix: let the manage operations name an app in none as the owner (for example an owner-kind parameter). If dropping this is intended, say so in the README (R1.4) and in the body.

return nil, err
}
s.policies.LimitsChanged(ctx, existing.OrganizationID)
s.policies.LimitsChanged(ctx, store.Holders(existing)...)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix, follow-up] R1.5 Staff's refresh of the owner's account is untested at four sites: here, :961, grants.go:400 and grants.go:418. Replacing LimitsChanged(ctx, store.Holders(...)...) with LimitsChanged(ctx, owner) (where owner is "" on the manage path) survives SelfHostedLimitsSuite and LimitsSuite at each site.

Ready rows for SelfHostedLimitsSuite. Each passes on the head and fails under its mutant:

  • TestRowStaffChangeHoldsTheOwnersNextAdmission: the app in none has spent 1,000,000 under its own organization limit of 9,000,000. Staff PATCH the limit to 1,000,000, and the app's next search is 402.
  • TestRowStaffDeleteHoldsTheOwnersNextAdmission: the app's limit is 1,000,000 and its search is refused. Staff DELETE the limit, and the next search is 200.
  • TestRowStaffRevokeHoldsTheOwnersNextAdmission: the app has a limit of 1,000,000 and a grant of 9,000,000, and its search passes. Staff revoke the grant, and the next search is 402.
  • TestRowStaffUnrevokeHoldsTheOwnersNextAdmission: the app revokes its grant and its search is refused. Staff unrevoke the grant, and the next search is 200.

// A limit a release from before limits said whose they are wrote is shown to no customer until
// it is known whose it is.
if pgStore != nil {
go attributeLimits(ctx, pgStore, logger)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix, follow-up] R1.6 Starting attributeLimits is untested. No cmd/router test references attributeLimits or AttributeLimits, so deleting this line passes every test. Fix: a startup test where a NULL row gets attributed.


-- +goose Down
-- Fails, and changes nothing, while an organization and an app of one id both hold a place.
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS limits_one_per_level

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Nit] R1.7 If a first Down fails while two owners of one id hold a place, it leaves limits_one_per_level INVALID. A retry then skips the build (IF NOT EXISTS) and drops both new indexes, so no unique index is left. Fix: drop limits_one_per_level first, as Up does with its own indexes.

}
query := tx.NewSelect().Model((*LimitGrant)(nil)).Where("organization_id = ?", grant.OrganizationID)
query := tx.NewSelect().Model((*LimitGrant)(nil))
query = whereOwner(query, LimitOwner(grant.OrganizationID, *grant.Billed), false)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Nit] R1.9 The MaxLiveGrants count skips unattributed grants, so during the transition an owner can hold 20 live grants plus its unattributed ones. Separately, Unrevoke of an unattributed grant (:259, Holders(before)[0]) counts only the organization's grants.


// attributeLimits attributes the limits, resets and grants not known to be anyone's, now and
// every minute until the process stops, since the release before writes them while it runs.
func attributeLimits(ctx context.Context, pgStore *store.Store, logger *slog.Logger) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Nit] R1.10 This runs every minute on every router with no end condition. Each run re-reads the rows that can never be attributed (staff's rows for an unknown organization, an app recorded elsewhere, a row with no audit entry). Fix (ticket): stop it once the previous release is gone, or once no NULL rows remain.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants