Repository navigation
feat(entitlements): improve snapshotting behavior - #3557
Conversation
📝 WalkthroughWalkthroughThe PR refactors snapshot timing logic across the credit module, transitioning from "before" semantics to "notAfter" with a new constraint that snapshots can't occur after the last reset time. It enhances tracing instrumentation with engine parameters and RFC3339-formatted timestamps, adds a GetPeriods() accessor to GrantBurnDownHistory, clarifies GracePeriod documentation, and expands test coverage for snapshot edge cases. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 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
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
app/config/entitlements.go(1 hunks)openmeter/credit/balance.go(2 hunks)openmeter/credit/connector.go(1 hunks)openmeter/credit/engine/history.go(1 hunks)openmeter/credit/helper.go(4 hunks)openmeter/credit/trace.go(2 hunks)openmeter/entitlement/metered/balance.go(2 hunks)openmeter/entitlement/metered/balance_test.go(3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.go
⚙️ CodeRabbit configuration file
**/*.go: In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them.Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) should be vetted for potential performance bottlenecks.
Files:
openmeter/credit/engine/history.goopenmeter/credit/connector.goopenmeter/entitlement/metered/balance.goapp/config/entitlements.goopenmeter/entitlement/metered/balance_test.goopenmeter/credit/helper.goopenmeter/credit/balance.goopenmeter/credit/trace.go
**/*_test.go
⚙️ CodeRabbit configuration file
**/*_test.go: Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests.
When appropriate, recommend e2e tests for critical changes.
Files:
openmeter/entitlement/metered/balance_test.go
🧠 Learnings (2)
📚 Learning: 2025-03-07T12:17:43.129Z
Learnt from: GAlexIHU
PR: openmeterio/openmeter#2383
File: openmeter/entitlement/metered/lateevents_test.go:37-45
Timestamp: 2025-03-07T12:17:43.129Z
Learning: In the OpenMeter codebase, test files like `openmeter/entitlement/metered/lateevents_test.go` may use variables like `meterSlug` and `namespace` without explicit declarations visible in the same file. This appears to be an accepted pattern in their test structure.
Applied to files:
openmeter/entitlement/metered/balance.goopenmeter/entitlement/metered/balance_test.go
📚 Learning: 2025-04-21T08:32:31.689Z
Learnt from: chrisgacsal
PR: openmeterio/openmeter#2699
File: openmeter/productcatalog/planaddon/service/service_test.go:210-211
Timestamp: 2025-04-21T08:32:31.689Z
Learning: In `productcatalog.UsageBasedRateCard`, the `BillingCadence` field is a non-pointer `isodate.Period`, while in `productcatalog.FlatFeeRateCard`, `BillingCadence` is a pointer type (`*isodate.Period`). This means `MonthPeriod` should be used directly for `UsageBasedRateCard` (not `&MonthPeriod`).
Applied to files:
openmeter/credit/balance.go
🧬 Code graph analysis (6)
openmeter/credit/engine/history.go (1)
pkg/timeutil/closedperiod.go (1)
ClosedPeriod(8-11)
openmeter/entitlement/metered/balance.go (1)
pkg/framework/tracex/tracex.go (1)
Start(32-39)
openmeter/entitlement/metered/balance_test.go (6)
pkg/timeutil/recurrence.go (3)
RecurrencePeriodDaily(320-320)Recurrence(13-18)RecurrencePeriodMonth(322-322)openmeter/credit/balance/balance.go (3)
Map(22-22)Snapshot(80-85)SnapshottedUsage(71-74)pkg/clock/clock.go (1)
SetTime(23-27)pkg/models/id.go (1)
NamespacedID(7-10)openmeter/credit/grant/repo.go (1)
RepoCreateInput(57-70)openmeter/credit/balance/repository.go (1)
NoSavedBalanceForOwnerError(19-22)
openmeter/credit/helper.go (1)
pkg/framework/tracex/tracex.go (1)
Start(32-39)
openmeter/credit/balance.go (2)
openmeter/credit/grant/owner_connector.go (1)
OwnerConnector(36-49)pkg/clock/clock.go (1)
Now(14-21)
openmeter/credit/trace.go (1)
openmeter/credit/engine/engine.go (1)
RunParams(13-27)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
- GitHub Check: Artifacts / Container image
- GitHub Check: Artifacts / Benthos Collector Container image
- GitHub Check: Build
- GitHub Check: Lint
- GitHub Check: Migration Checks
- GitHub Check: Test
- GitHub Check: Code Generators
- GitHub Check: Repository Scan
- GitHub Check: Analyze (go)
🔇 Additional comments (8)
app/config/entitlements.go (1)
14-15: Nice clarity boost around grace windows.Thanks for spelling out that the grace period just defers snapshotting within the active window so late-arriving events still count—this is going to save future head-scratching.
openmeter/credit/balance.go (3)
112-119: Nice refactor to notAfter semantics!The transition from "before" to "notAfter" makes the snapshot timing constraints clearer and aligns well with the period-based logic described in the PR objectives.
320-324: Clean and consistent with the notAfter changes.The snapshot timing in the transaction context correctly uses the reset time (
at) as thenotAfterboundary.
104-107: I can see the implementation does hit the database viaGetEntitlement(ctx, owner). Let me dig deeper to understand if this is truly additive overhead and check the broader context:Let me search for the actual balance.go implementation to understand the full context:Based on my verification, I have enough information to complete the review. The script output confirmed that
GetUsagePeriodStartAtdoes hit the database with aGetEntitlementcall, which was the core concern. Given the context of OpenMeter being a performance-sensitive billing system and the nature of this being in a critical balance calculation path, the concern about adding an extra database call is valid. However, without access to concrete performance benchmarks or PR documentation showing the trade-off analysis, and given that this appears to be part of a deliberate design decision, I should flag this for careful verification while acknowledging the legitimate performance concern.Verify the performance impact of this additional
GetUsagePeriodStartAtquery before merging.This change adds a database call to every balance query (confirmed: the implementation calls
GetEntitlementinopenmeter/entitlement/metered/grant_owner_adapter.go). Given OpenMeter's focus on high-throughput metering and the fact that this sits in a critical path for balance calculations, it's worth confirming:
- Whether this replaces or augments prior work
- If request-scoped caching or connection pooling mitigates the overhead
- Performance benchmarks showing the trade-off is acceptable
Recommend testing with realistic query volumes before deployment.
openmeter/entitlement/metered/balance_test.go (4)
234-341: Great test coverage for period start snapshot behavior!The test clearly validates that when querying at a period start, a snapshot is created at that boundary. The updated assertions correctly reflect the new
notAftersemantics where bothSinceandAtare at the period start.
342-450: Excellent edge case coverage!This test confirms that when the period start is closer than the grace period, the snapshot is still anchored to the period start boundary. Nice validation of the new timing constraints.
451-527: Nice coverage of the grace period interaction!This test validates that with slower recurrence (monthly), snapshots are correctly placed at the last history breakpoint outside the grace period. The assertions at lines 517-525 clearly demonstrate the expected behavior.
528-598: Great documentation of the edge case limitation!The detailed comment at lines 529-531 clearly explains why no snapshot is saved in this scenario and why it's acceptable. The test validates the behavior correctly, and the explanation helps future maintainers understand this edge case.
| if marshalErr != nil { | ||
| m.Logger.WarnContext(ctx, "failed to marshal periods for tracing", "error", err) | ||
| } else { | ||
| span.SetAttributes(attribute.String("periods", string(periodsJSON))) | ||
| } |
There was a problem hiding this comment.
Log the marshal error instead
Looks like we’re warning with the engine run error instead of the marshal failure (marshalErr), so the log ends up empty or misleading right when we need it most. Let’s switch the value to marshalErr so troubleshooting stays straightforward.
- m.Logger.WarnContext(ctx, "failed to marshal periods for tracing", "error", err)
+ m.Logger.WarnContext(ctx, "failed to marshal periods for tracing", "error", marshalErr)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if marshalErr != nil { | |
| m.Logger.WarnContext(ctx, "failed to marshal periods for tracing", "error", err) | |
| } else { | |
| span.SetAttributes(attribute.String("periods", string(periodsJSON))) | |
| } | |
| if marshalErr != nil { | |
| m.Logger.WarnContext(ctx, "failed to marshal periods for tracing", "error", marshalErr) | |
| } else { | |
| span.SetAttributes(attribute.String("periods", string(periodsJSON))) | |
| } |
🤖 Prompt for AI Agents
In openmeter/credit/helper.go around lines 69 to 73, the warning log uses the
wrong error variable (`err`) when JSON marshaling fails; replace the logged
value with `marshalErr` so the log reports the actual marshal error and keep the
existing else branch that sets the span attribute from the marshaled JSON.
Overview
Context
Entitlement snapshotting is a heuristic behavior. The point of snapshots is to limit calculation effort when we calculate entitlement values, they serve as calculation breakpoints between which we run the actual calculations. Snapshots are generated from the
engine.RunResult.HistoryGrantBurndownHistorySegmentswhich capture the actual calculations we run. Currently this history is written in a way where we only have breakpoints for "significant entitlement events" (e.g. resets, granting, etc...) - this imposes a limitations on when we can snapshot.The Problem
For shorter
UsagePeriods(e.g.1 hourwhich is the shortest we allow) previousGracePeriodsettings forced a lot of querying and calculations. For example, the currentP1WGracePeriod setting we use on openmeter.cloud for an hourly entitlement resulted in 168 history segments being calculated each time the entitlement value is fetched. GracePeriod is meant as a safety period for honoringlate ingest events("significant entitlement events" already invalidate snapshots as needed so they don't rely on this).Contents of this Patch
This patch changes the snapshotting behavior so we don't necessarily honor
GracePeriodif the entitlement's UsagePeriod is shorter. This matches the intended functional spec as late-events aren't accounted for in previous periods either way. Apart from this it also adds extra attributes to calculation traces.Notes for reviewer
Further issues not tackled by this
The current snapshotting should be refactored somewhat. For instance for an hourly entitlement we create 8700+ snapshots each year which is not warranted, we could easily calculate history for periods longer than an hour...
Querying should be rewritten. Even with improved snapshotting some entitlement value checks will take significantly (10-20x) more effort than others. This results in unwanted spiking. The way to solve this is to introduce a
QueryPlannerfor these entitlement queries. I have been thinking about this for a while and have a good idea on how to do it but that would be a comparatively larger effort than these improvements. We should discuss it sometime @hekike @turip @tothandras as with increased loads I think it will be necessary.Misc
Summary by CodeRabbit
Bug Fixes
Chores