Skip to content

perf(admin): batch quota usage lookups for the policy list - #445

Open
misswell wants to merge 1 commit into
astaxie:mainfrom
misswell:codex/quota-usage-batch
Open

misswell wants to merge 1 commit into
astaxie:mainfrom
misswell:codex/quota-usage-batch

Conversation

@misswell

@misswell misswell commented Nov 23, 2026 •

Copy link
Copy Markdown

Summary

GET /api/admin/resources/quota-policies resolves current usage one policy at a time. Each GetQuotaPolicyUsage call issues its own database clock query, reads the quota timezone setting, then performs up to four bucket reads (day and month, direct and aggregated). With a few hundred policies that is thousands of round trips, and the admin list becomes slow enough to time out on a busy deployment.

This change resolves the whole list through one read-only snapshot with a bounded number of queries.

Related Issue

N/A

Changes

  • Add readQuotaPolicyUsages, which resolves many quota-policy targets at once.
  • Read the clock and timezone settings once per request instead of once per policy.
  • Fetch per-user and per-key buckets with chunked IN (...) queries, chunked at 400 IDs so statements stay below SQLite's and PostgreSQL's parameter limits.
  • Aggregate API-key-attributed usage for all users in one grouped query instead of one aggregate per user.
  • Preserve the existing semantics: a legacy row with empty attribution still wins over the attributed row, key buckets still count toward their owner, all_users and empty scope IDs stay unsupported, and counters merge by max.
  • Keep Store implementations that override GetQuotaPolicyUsage working: the batch path only applies to *GormStore, and every other store keeps per-target calls.
  • Fall back to per-row lookups if the batch fails, so one bad row cannot hide usage for the rows that would have succeeded.
  • Add tests for result parity with single lookups, the query budget over 4,800 targets, cancellation propagation, and wrapper overrides.

Type of Change

  • Bug fix
  • New feature
  • Refactor or maintenance
  • Documentation
  • Deployment or configuration
  • Other: performance

Verification

  • go build ./... passes.
  • go vet ./internal/server passes.
  • go test ./internal/server -run 'TestQuotaPolicy|TestUserQuota|TestDefaultUserQuota|TestQuotaTimezone|TestAdminResources' -count=1 passes.
  • New tests: TestQuotaPolicyUsageBatchMatchesSingleLookups (parity with GetQuotaPolicyUsage for 4,807 targets and a query-count ceiling), TestQuotaPolicyUsageBatchPropagatesCancellation, TestQuotaPolicyUsageBatchHonorsStoreOverrides.
  • gofmt -l reports no files; git diff --check passes.

Compatibility, Security, and Operations

  • No API or response-shape change; the same current_usage field is populated.
  • Read-only work moves into a repeatableRead read-only transaction, consistent with the existing usage and billing snapshot reads. A long policy list therefore observes one consistent snapshot instead of a shifting one.
  • The fallback keeps the previous behavior when the batch fails, at the old query cost, so a regression degrades performance rather than correctness.
  • No new configuration, environment variables, or migrations.

Checklist

  • The PR title and body are written in English.
  • Tests were added or updated for behavior changes, or the reason they are unnecessary is documented.
  • No credentials, local .env files, databases, backups, or runtime logs are included.
  • Environment variable changes are synchronized across examples, Compose, start.sh, and deployment documentation where applicable.
  • Shared user-facing behavior is documented consistently in English, Simplified Chinese, and Japanese where applicable.
  • data/model-catalog.yaml remains tracked and catalog changes were reviewed where applicable.
  • git diff --check passes.

Listing quota policies called GetQuotaPolicyUsage once per row, and each
call ran its own database clock query, timezone settings read, and up to
four quota-bucket reads. A few hundred policies therefore produced
thousands of round trips and made the admin list slow enough to time out.

Resolve all rows through one read-only repeatable-read snapshot: one clock
and timezone lookup, chunked IN queries for the per-user and per-key
buckets, and one grouped aggregate for usage attributed to API keys. The
chunk size keeps each statement well below SQLite's and PostgreSQL's
parameter limits, so the number of queries stays bounded as the list
grows. Store wrappers that override GetQuotaPolicyUsage still receive
per-row calls, and a failed batch falls back to the previous per-row
behavior so a single bad row cannot hide the others.
@misswell

Copy link
Copy Markdown
Author

CI shows action_required instead of running — that's the first-time-contributor approval gate, so no job has started yet. Could a maintainer approve the workflow runs?

I pre-ran the equivalent checks locally at this exact head (1dcb22a0): gofmt -l clean, go vet ./..., golangci-lint v2.12.2 with 0 issues, and the full 4-shard backend suite via node tools/test-backend-shard.mjs N 4.

Happy to adjust anything if you'd rather see a different shape.

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.

1 participant