Repository navigation
perf: make balance calculation linear in entitlement reset count - #4827
Conversation
balancesnapshot_namespace_owner_id_at is partial on deleted_at IS NULL, and Postgres only uses a partial index when the query predicate implies the index predicate. InvalidateAfter omitted it, so the planner fell back to the namespace-only index. Adding it also avoids restamping already-invalidated rows. Runs on every grant create and void.
📝 WalkthroughWalkthroughThe change adds indexed timeline helpers, updates usage-period recurrence operations, removes the usage querier default-parameter callback, reuses closed periods during credit runs, and excludes deleted balance snapshots from invalidation. ChangesTimeline and usage-period handling
Credit query and snapshot updates
Estimated code review effort: 3 (Moderate) | ~20 minutes Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
pkg/timeutil/timeline.go (1)
99-113: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse an upper-bound search API for the timeline lookup.
LastIndexNotAfterreturnsfirstAfter - 1, but theslices.BinarySearchFunccomparator returns-1for equal timestamps instead of0, sofoundis always false and this sits outside the comparator contract. Usesort.Searchto find the first entry afterat, then subtract one.Proposed fix
+import "sort" + func (t Timeline[T]) LastIndexNotAfter(at time.Time) int { - firstAfter, _ := slices.BinarySearchFunc(t.times, at, func(e Timed[T], target time.Time) int { - if e.GetTime().After(target) { - return 1 - } - - return -1 - }) - - return firstAfter - 1 + return sort.Search(len(t.times), func(i int) bool { + return t.times[i].GetTime().After(at) + }) - 1 }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/timeutil/timeline.go` around lines 99 - 113, Update Timeline.LastIndexNotAfter to use sort.Search for an upper-bound lookup: find the first index whose timestamp is strictly after at, then return that index minus one. Remove the slices.BinarySearchFunc call and preserve the existing -1 result when every entry is after at, including correct handling of equal timestamps.Source: MCP tools
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@openmeter/entitlement/usageperiod.go`:
- Around line 102-107: The Validate method in UsagePeriod must preserve the
validation contract by wrapping each recurrence validation error with its
recurrence field path and returning the joined result through
models.NewNillableGenericValidationError. Update the errs construction and final
return in Validate, including the empty-recurrence error, while keeping the
existing validation behavior unchanged.
---
Nitpick comments:
In `@pkg/timeutil/timeline.go`:
- Around line 99-113: Update Timeline.LastIndexNotAfter to use sort.Search for
an upper-bound lookup: find the first index whose timestamp is strictly after
at, then return that index minus one. Remove the slices.BinarySearchFunc call
and preserve the existing -1 result when every entry is after at, including
correct handling of equal timestamps.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 2bb90030-319e-4fee-b734-318e1ce81f60
📒 Files selected for processing (8)
openmeter/credit/adapter/balance_snapshot.goopenmeter/credit/balance/service.goopenmeter/credit/balance/usage.goopenmeter/credit/engine/run.goopenmeter/credit/helper.goopenmeter/entitlement/usageperiod.gopkg/timeutil/timeline.gopkg/timeutil/timeline_test.go
💤 Files with no reviewable changes (1)
- openmeter/credit/helper.go
| if u.recs.Len() == 0 { | ||
| errs = append(errs, errors.New("UsagePeriod must have at least one recurrence")) | ||
| } | ||
|
|
||
| hour := datetime.NewISODuration(0, 0, 0, 0, 1, 0, 0) | ||
| for i := range u.recs.GetTimes() { | ||
| for i := range u.recs.Len() { |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Return the required validation error type with field context.
This updated Validate method still appends unwrapped errors and returns raw errors.Join(errs...) on Line 121. Wrap errors with their recurrence field path and return models.NewNillableGenericValidationError(errors.Join(errs...)). This preserves the validation contract for callers.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@openmeter/entitlement/usageperiod.go` around lines 102 - 107, The Validate
method in UsagePeriod must preserve the validation contract by wrapping each
recurrence validation error with its recurrence field path and returning the
joined result through models.NewNillableGenericValidationError. Update the errs
construction and final return in Validate, including the empty-recurrence error,
while keeping the existing validation behavior unchanged.
Source: Coding guidelines
slices.BinarySearchFunc documents its precondition as a partition but does not specify which index it returns when no element compares equal, so relying on it for a first-strictly-after search leans on the current lower-bound implementation. sort.Search guarantees exactly that predicate, including the len(times) result that makes the -1 sentinel correct.
Problem
UsagePeriod.GetResetTimelineInclusivewas quadratic in an entitlement's usage-reset count, which grows without bound with account age. Balance calculation walks it several times per run, so old high-cadence entitlements blew the 30s message processing timeout. In one 16h production window the balance worker dead-lettered 294 messages, allfailed to describe owner <id>: context deadline exceeded— the deadline always tripped beforeengine.Run, i.e. the whole budget went to metadata resolution rather than the balance math.The failures were concentrated on ~16 entitlements in 2 namespaces that failed every hour, permanently. They are not slow; they are superlinear in a quantity that grows with wall-clock time.
Two independent causes, both loop-shaped:
Timeline.GetTimes()allocates a fresh slice on every call, and was evaluated inside loop conditions —usageperiod.go(3 sites) andengine/run.goviaGetClosedPeriods()(2 sites).GetUsagePeriodInputAt's loop variable was captured by the returned closure, forcing a heap allocation per iteration of an O(n) scan that is itself called O(n) times. This was the dominant term: 88% of allocations.The cost lands as CPU, not memory. The churn is transient garbage reclaimed continuously, so it never becomes RSS — it shows up as GC mark workers burning cores.
Changes
perf(credit): iterations optimizationTimeline.Len()— allocation-free, for use in loop conditions.Timeline.LastIndexNotAfter()— binary search over the ascending-sorted invariantNewTimelineguarantees, replacing the reverse linear scan inGetUsagePeriodInputAtand eliminating the closure capture.GetClosedPeriods()out of two loop conditions inengine.Run.perf(credit): drop redundant owner fetch from the usage querierQueryUsagecalled bothGetDefaultParamsandDescribeOwner, but at both (only) construction sitesGetDefaultParamswasDescribeOwner(...).DefaultQueryParams— literally so in the snapshot service, and closed over the same prefetched owner inbuildEngineForOwner. Redundant since #2406 introduced it. On the snapshot usage-backfill path inGetLatestValidAtthis halves the owner lookups, each of which is four uncached Postgres queries.perf(credit): let InvalidateAfter use the balance snapshot indexbalancesnapshot_namespace_owner_id_atis partial ondeleted_at IS NULL, and Postgres only uses a partial index when the query predicate implies the index predicate.InvalidateAfteromitted it, so the planner fell back to the namespace-only index. Runs on every grant create and void.Numbers
Reset timeline resolution, median of 3 runs at
-benchtime=10x, same machine, baseline measured in a worktree at the parent commit:That is 451× faster and ~3,000× less allocation at one year of hourly resets.
The scaling is the substantive result. Going from 1,000 to 8,760 resets (8.76× more): before, time grew 71.8× ≈ 8.76² — quadratic. After, 9.1× ≈ 8.76 — linear.
CPU profile at 1,000 resets:
gcBgMarkWorker/gcDrainA single-goroutine workload pulling 163% CPU is GC mark workers running on other cores — which is why this presents as CPU pressure with flat memory.
The benchmark used to produce these figures was intentionally not committed.
Correctness
LastIndexNotAfteris covered by a differential test asserting it matches the previous reverse scan for every probe across every timeline size, including duplicate-timestamp ties (which must resolve to the last of the tied group to preserve the old semantics).Green and unchanged:
openmeter/credit/...,openmeter/entitlement/...,pkg/timeutil/...,test/credits,test/entitlement/regression,test/billing,test/subscription.golangci-lintreports 0 issues.Note the OM-400 unit_config regime check in
GetLastValidSnapshotAtis untouched — only the number of owner fetches changed, never the comparison.Follow-ups (not in this PR)
failed to describe owner %serror strings inhelper.goandbalance.goare byte-identical, so logs alone cannot distinguish them.snapshotEngineResulttakesSELECT ... FOR UPDATE NOWAITin a transaction that commits beforesaveSnapshotruns, so the lock guards nothing while costing round-trips on every read.ListInScopeEntitlementsmaterialises an entire namespace's entitlements before processing;ProcessEntitlementsthen walks them serially.pool_max_connsis unset, defaulting tomax(4, NumCPU).Summary by CodeRabbit
Bug Fixes
Performance
Reliability
Greptile Summary
The PR makes entitlement balance calculation linear in the reset count while reducing redundant owner lookups and enabling the balance-snapshot partial index.
Confidence Score: 5/5
The PR appears safe to merge.
No blocking failure remains; the previously reported comparator-contract issue is resolved by the monotonic predicate passed to sort.Search.
Important Files Changed
Reviews (3): Last reviewed commit: "style: comments" | Re-trigger Greptile
Context used: