-
Notifications
You must be signed in to change notification settings - Fork 197
feat: bulk customer usage attribution lookup performance and correctness #4686
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
gergely-kurucz-konghq
merged 13 commits into
main
from
feat/bulk-customer-usage-attribution-lookup-perf
Jul 23, 2026
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
c6ec6eb
perf(customer): rewrite bulk usage attribution lookup as UNION ALL
gergely-kurucz-konghq 5f490d3
fix(customer): resolve usage-attribution key precedence deterministic…
gergely-kurucz-konghq 309ceee
test(e2e): add governance namespace-scale benchmark
gergely-kurucz-konghq a80164a
fix(e2e): sort decoy tiers so benchmark labels match seeded namespace…
gergely-kurucz-konghq 5c74c6a
fix(customer): drop unreachable created_at guard from bulk usage attr…
gergely-kurucz-konghq 9ed2ef6
docs(customer): simplify comments added on this branch
gergely-kurucz-konghq f853f27
fix(customer): apply deleted_at grace window uniformly in usage-attri…
gergely-kurucz-konghq d86a0e7
refactor(customer): unify usage-attribution lookup on one predicate, …
gergely-kurucz-konghq 3e64d2f
test(customer): add bulk usage-attribution service tests; share resol…
gergely-kurucz-konghq 194b1e1
test(customer): split usage-attribution benchmarks by layer
gergely-kurucz-konghq 84e266c
test(customer): adapt usage-attribution tests to migrated test harness
gergely-kurucz-konghq 7fff147
refactor(customer): drop unused logger from customer service
gergely-kurucz-konghq 2468628
refactor(customer): return map[string]*Customer from GetCustomersByUs…
gergely-kurucz-konghq File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
| package e2e | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "net/http" | ||
| "os" | ||
| "slices" | ||
| "sort" | ||
| "strconv" | ||
| "testing" | ||
|
|
||
| "github.com/jackc/pgx/v5/pgxpool" | ||
| "github.com/oklog/ulid/v2" | ||
| "github.com/stretchr/testify/require" | ||
|
|
||
| v3sdk "github.com/openmeterio/openmeter/api/v3/client" | ||
| ) | ||
|
|
||
| const ( | ||
| defaultGovernanceBenchNamespaceDecoys = 100_000 | ||
| governanceBenchNamespaceDecoysEnv = "GOV_BENCH_NAMESPACE_DECOYS" | ||
| ) | ||
|
|
||
| // BenchmarkGovernanceQueryNamespaceScale isolates the effect of total namespace | ||
| // size on governance query latency, independent of the customers/features axes | ||
| // BenchmarkGovernanceQuery already covers. It fixes a small, constant query | ||
| // load (100 customers, matching the OAS customer-key cap, x 1 feature) so the | ||
| // entitlement GetAccess fan-out cost stays flat across sub-benchmarks, and | ||
| // varies only how many other (never-queried) customers/subjects exist in the | ||
| // namespace. | ||
| // | ||
| // This targets the customer usage-attribution resolution path: pre-UNION-ALL, | ||
| // a large decoy count made GetCustomersByUsageAttribution seq-scan the | ||
| // customers table (see #4684 and the follow-up bulk fix); this benchmark shows | ||
| // whether decoy count still moves total request latency post-fix. Decoy | ||
| // counts accumulate across sub-benchmarks (0 -> 10k -> N), so each step only | ||
| // seeds the incremental delta. | ||
| // | ||
| // Decoys are seeded directly via SQL (not HTTP, which would dominate setup | ||
| // time) and require direct Postgres access alongside OPENMETER_ADDRESS (see | ||
| // initE2EPostgresPool). Set GOV_BENCH_NAMESPACE_DECOYS to change the top | ||
| // decoy count from the default 100,000. | ||
| func BenchmarkGovernanceQueryNamespaceScale(b *testing.B) { | ||
| client := initClient(b) | ||
| v3 := newV3Client(b) | ||
| pool := initE2EPostgresPool(b) | ||
|
|
||
| const ( | ||
| queryCustomers = 100 | ||
| queryFeatures = 1 | ||
| ) | ||
|
|
||
| custKeys, featKeys := seedGovernanceFixture(b, client, queryCustomers, queryFeatures) | ||
| namespace := getCustomerNamespaceByKey(b, pool, custKeys[0]) | ||
| decoyRun := uniqueKey("gov_bench_ns_decoy") | ||
|
|
||
| // Sorted and deduplicated so the cumulative seeding below stays monotonically | ||
| // increasing regardless of GOV_BENCH_NAMESPACE_DECOYS: an override below the | ||
| // hardcoded 10_000 tier would otherwise seed 10_000 first, then skip seeding | ||
| // for the smaller tier (seeded > target) while still reporting that smaller, | ||
| // now-incorrect decoy count as the benchmark's label. | ||
| decoyCounts := []int{0, 10_000, governanceBenchNamespaceDecoyCount(b)} | ||
| sort.Ints(decoyCounts) | ||
| decoyCounts = slices.Compact(decoyCounts) | ||
|
|
||
| reqBody := v3sdk.GovernanceQueryRequest{ | ||
| Customer: v3sdk.GovernanceQueryRequestCustomers{Keys: custKeys}, | ||
| Feature: &v3sdk.GovernanceQueryRequestFeatures{Keys: featKeys}, | ||
| } | ||
|
|
||
| seeded := 0 | ||
| for _, target := range decoyCounts { | ||
| b.Run(fmt.Sprintf("decoys=%d", target), func(b *testing.B) { | ||
| if target > seeded { | ||
| seedNamespaceDecoys(b, pool, namespace, decoyRun, seeded, target) | ||
| seeded = target | ||
| } | ||
|
|
||
| // Warm-up + correctness gate: a wrong result (e.g. missing customers) | ||
| // would make the latency number meaningless. | ||
| resp, err := v3.Governance.QueryAccess(b.Context(), reqBody, v3sdk.GovernanceQueryResultListParams{}) | ||
| v3.requireStatus(http.StatusOK, err) | ||
| require.Lenf(b, resp.Data, queryCustomers, "expected %d resolved customers", queryCustomers) | ||
|
|
||
| b.ReportAllocs() | ||
| b.ResetTimer() | ||
| for i := 0; i < b.N; i++ { | ||
| if _, err := v3.Governance.QueryAccess(b.Context(), reqBody, v3sdk.GovernanceQueryResultListParams{}); err != nil { | ||
| b.Fatalf("governance query failed: %v", err) | ||
| } | ||
| if s := v3.statuses.last(); s != http.StatusOK { | ||
| b.Fatalf("governance query returned %d", s) | ||
| } | ||
| } | ||
| b.StopTimer() | ||
| b.ReportMetric(float64(target), "decoys") | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func governanceBenchNamespaceDecoyCount(b *testing.B) int { | ||
| b.Helper() | ||
|
|
||
| value := os.Getenv(governanceBenchNamespaceDecoysEnv) | ||
| if value == "" { | ||
| return defaultGovernanceBenchNamespaceDecoys | ||
| } | ||
|
|
||
| count, err := strconv.Atoi(value) | ||
| if err != nil || count < 1 { | ||
| b.Fatalf("%s must be a positive integer, got %q", governanceBenchNamespaceDecoysEnv, value) | ||
| } | ||
|
|
||
| return count | ||
| } | ||
|
|
||
| func getCustomerNamespaceByKey(tb testing.TB, pool *pgxpool.Pool, key string) string { | ||
| tb.Helper() | ||
|
|
||
| var namespace string | ||
| err := pool.QueryRow( | ||
| tb.Context(), | ||
| `SELECT namespace FROM customers WHERE key = $1`, | ||
| key, | ||
| ).Scan(&namespace) | ||
| require.NoError(tb, err) | ||
|
|
||
| return namespace | ||
| } | ||
|
|
||
| // seedNamespaceDecoys bulk-inserts decoy customers (and one subject key each) | ||
| // directly via SQL, numbered (from, to] under the given per-benchmark-run | ||
| // prefix, so repeated calls with a growing `to` only seed the incremental | ||
| // delta, and separate benchmark runs never collide on the same key even if | ||
| // the database was not reset in between. Decoys are never included in a | ||
| // governance query; they exist purely to grow the namespace the resolution | ||
| // query has to search. ANALYZE keeps planner stats current, matching the | ||
| // customer adapter's own usage-attribution benchmark. | ||
| func seedNamespaceDecoys(tb testing.TB, pool *pgxpool.Pool, namespace, runPrefix string, from, to int) { | ||
| tb.Helper() | ||
|
|
||
| n := to - from | ||
| ids := make([]string, n) | ||
| keys := make([]string, n) | ||
| subjectKeys := make([]string, n) | ||
|
|
||
| for i := range n { | ||
| ids[i] = ulid.Make().String() | ||
| keys[i] = fmt.Sprintf("%s_%d", runPrefix, from+i) | ||
| subjectKeys[i] = keys[i] + "_subj" | ||
| } | ||
|
|
||
| rctx := tb.Context() | ||
|
|
||
| _, err := pool.Exec(rctx, ` | ||
| INSERT INTO customers (id, namespace, created_at, updated_at, name, key) | ||
| SELECT id, $1, now(), now(), key, key | ||
| FROM unnest($2::text[], $3::text[]) AS t(id, key) | ||
| `, namespace, ids, keys) | ||
| require.NoError(tb, err) | ||
|
|
||
| _, err = pool.Exec(rctx, ` | ||
| INSERT INTO customer_subjects (namespace, subject_key, created_at, customer_id) | ||
| SELECT $1, subject_key, now(), customer_id | ||
| FROM unnest($2::text[], $3::text[]) AS t(subject_key, customer_id) | ||
| `, namespace, subjectKeys, ids) | ||
| require.NoError(tb, err) | ||
|
|
||
| _, err = pool.Exec(rctx, "ANALYZE customers") | ||
| require.NoError(tb, err) | ||
| _, err = pool.Exec(rctx, "ANALYZE customer_subjects") | ||
| require.NoError(tb, err) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.