Skip to content

perf: make balance calculation linear in entitlement reset count - #4827

Merged
tothandras merged 5 commits into
mainfrom
perf/reset-timeline-linear
Aug 3, 2026
Merged

tothandras merged 5 commits into
mainfrom
perf/reset-timeline-linear

Conversation

@tothandras

@tothandras tothandras commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Problem

UsagePeriod.GetResetTimelineInclusive was 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, all failed to describe owner <id>: context deadline exceeded — the deadline always tripped before engine.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) and engine/run.go via GetClosedPeriods() (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 optimization

  • Timeline.Len() — allocation-free, for use in loop conditions.
  • Timeline.LastIndexNotAfter() — binary search over the ascending-sorted invariant NewTimeline guarantees, replacing the reverse linear scan in GetUsagePeriodInputAt and eliminating the closure capture.
  • Hoist GetClosedPeriods() out of two loop conditions in engine.Run.

perf(credit): drop redundant owner fetch from the usage querier
QueryUsage called both GetDefaultParams and DescribeOwner, but at both (only) construction sites GetDefaultParams was DescribeOwner(...).DefaultQueryParams — literally so in the snapshot service, and closed over the same prefetched owner in buildEngineForOwner. Redundant since #2406 introduced it. On the snapshot usage-backfill path in GetLatestValidAt this halves the owner lookups, each of which is four uncached Postgres queries.

perf(credit): let InvalidateAfter use the balance snapshot index
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. 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:

resets time bytes/op allocs/op
100 1.28 ms → 0.19 ms 3.3 MB → 81 KB 12,135 → 1,430
1,000 104 ms → 1.8 ms 309 MB → 869 KB 1,021,132 → 14,040
8,760 (1 year hourly) 7,484 ms → 16.6 ms 23.5 GB → 7.8 MB 76,926,253 → 122,745

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:

before after
total CPU samples 3,940 ms (163% CPU) 70 ms (34.6% CPU)
gcBgMarkWorker / gcDrain 540 ms below threshold

A 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

LastIndexNotAfter is 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-lint reports 0 issues.

Note the OM-400 unit_config regime check in GetLastValidSnapshotAt is untouched — only the number of owner fetches changed, never the comparison.

Follow-ups (not in this PR)

  • The two failed to describe owner %s error strings in helper.go and balance.go are byte-identical, so logs alone cannot distinguish them.
  • snapshotEngineResult takes SELECT ... FOR UPDATE NOWAIT in a transaction that commits before saveSnapshot runs, so the lock guards nothing while costing round-trips on every read.
  • ListInScopeEntitlements materialises an entire namespace's entitlements before processing; ProcessEntitlements then walks them serially.
  • Postgres pool_max_conns is unset, defaulting to max(4, NumCPU).

Summary by CodeRabbit

  • Bug Fixes

    • Prevented already-deleted balance snapshots from being selected for invalidation.
    • Usage queries now consistently apply each owner’s configured default parameters.
    • Improved recurrence handling for usage periods, including boundary and reset scenarios.
  • Performance

    • Optimized usage-period recurrence lookups to reduce unnecessary computation and memory usage.
  • Reliability

    • Improved timeline handling for empty timelines, duplicate timestamps, and exact time boundaries.

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.

  • Adds allocation-free timeline length and upper-bound lookup operations.
  • Reuses closed periods during engine execution instead of repeatedly materializing them.
  • Uses the already-described owner’s default query parameters.
  • Restricts snapshot invalidation to active snapshots.

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

Filename Overview
pkg/timeutil/timeline.go Adds allocation-free length access and a contract-correct upper-bound search over constructor-sorted timeline entries.
pkg/timeutil/timeline_test.go Covers empty timelines, inclusive boundaries, duplicate timestamps, and differential equivalence with the former reverse scan.
openmeter/entitlement/usageperiod.go Replaces allocating timeline reads and linear recurrence lookup while preserving effective-recurrence semantics.
openmeter/credit/engine/run.go Materializes closed periods once and consistently uses that slice for iteration and final-period detection.
openmeter/credit/balance/usage.go Derives streaming defaults from the owner already fetched for meter metadata.
openmeter/credit/balance/service.go Removes the redundant owner-backed default-parameter callback from snapshot-service wiring.
openmeter/credit/helper.go Simplifies owner-specific engine wiring after default query parameters moved to the existing owner description.
openmeter/credit/adapter/balance_snapshot.go Limits invalidation to undeleted snapshots so the applicable partial database index can be used.

Reviews (3): Last reviewed commit: "style: comments" | Re-trigger Greptile

Context used:

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.
@tothandras
tothandras requested a review from a team as a code owner August 1, 2026 13:01
@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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.

Changes

Timeline and usage-period handling

Layer / File(s) Summary
Timeline indexing helpers and validation
pkg/timeutil/timeline.go, pkg/timeutil/timeline_test.go
Timeline now provides Len and inclusive LastIndexNotAfter lookup. Tests cover boundaries, duplicate timestamps, empty timelines, and differential results.
Usage-period recurrence operations
openmeter/entitlement/usageperiod.go
Usage-period operations use timeline counts and indexed recurrence lookup instead of repeatedly materializing recurrence times.

Credit query and snapshot updates

Layer / File(s) Summary
Owner query-parameter wiring
openmeter/credit/balance/usage.go, openmeter/credit/balance/service.go, openmeter/credit/helper.go
The usage querier no longer accepts GetDefaultParams. QueryUsage uses owner.DefaultQueryParams after describing the owner.
Credit period and snapshot handling
openmeter/credit/engine/run.go, openmeter/credit/adapter/balance_snapshot.go
Run reuses the closed-period collection. Snapshot invalidation excludes deleted snapshots.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested reviewers: galexihu

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the primary performance improvement: making balance calculation linear in entitlement reset count.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/reset-timeline-linear

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Comment thread pkg/timeutil/timeline.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
pkg/timeutil/timeline.go (1)

99-113: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use an upper-bound search API for the timeline lookup.

LastIndexNotAfter returns firstAfter - 1, but the slices.BinarySearchFunc comparator returns -1 for equal timestamps instead of 0, so found is always false and this sits outside the comparator contract. Use sort.Search to find the first entry after at, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4613041 and 08af263.

📒 Files selected for processing (8)
  • openmeter/credit/adapter/balance_snapshot.go
  • openmeter/credit/balance/service.go
  • openmeter/credit/balance/usage.go
  • openmeter/credit/engine/run.go
  • openmeter/credit/helper.go
  • openmeter/entitlement/usageperiod.go
  • pkg/timeutil/timeline.go
  • pkg/timeutil/timeline_test.go
💤 Files with no reviewable changes (1)
  • openmeter/credit/helper.go

Comment on lines +102 to +107
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() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ 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

@tothandras tothandras added the release-note/misc Miscellaneous changes label Aug 1, 2026
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.
@tothandras
tothandras requested a review from GAlexIHU August 3, 2026 09:03

@GAlexIHU GAlexIHU left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

thx!

@tothandras
tothandras merged commit 04651cb into main Aug 3, 2026
27 checks passed
@tothandras
tothandras deleted the perf/reset-timeline-linear branch August 3, 2026 12:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/misc Miscellaneous changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants