Skip to content

feat(entitlements): improve snapshotting behavior - #3557

Merged
GAlexIHU merged 1 commit into
mainfrom
feat/entitlements/snapshotting-improvements
Oct 30, 2025
Merged

GAlexIHU merged 1 commit into
mainfrom
feat/entitlements/snapshotting-improvements

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented Oct 30, 2025 •

Copy link
Copy Markdown
Contributor

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.History GrantBurndownHistorySegments which 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 hour which is the shortest we allow) previous GracePeriod settings forced a lot of querying and calculations. For example, the current P1W GracePeriod 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 honoring late 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 GracePeriod if 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...

  • We should probably also mandate some gap-size between snapshots when saving (e.g. no two snapshots closer than a week)
  • We could add background jobs that clean up old snapshots as they are not a functional requirement

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 QueryPlanner for 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

  • This patch doesn't actually introduce more snapshotting compared to before (so no increase in system load) just creates them sooner

Summary by CodeRabbit

  • Bug Fixes

    • Improved snapshot timing calculations to accurately handle grace periods in credit balance tracking.
  • Chores

    • Enhanced observability with improved tracing attributes and timestamp formatting standardization.
    • Expanded test coverage for entitlement balance snapshots across multiple periods and edge cases.

@GAlexIHU
GAlexIHU requested a review from a team as a code owner October 30, 2025 16:26
@GAlexIHU GAlexIHU added the release-note/bug-fix Release note: Bug Fixes label Oct 30, 2025
@coderabbitai

coderabbitai Bot commented Oct 30, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The 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

Cohort / File(s) Summary
Configuration Updates
app/config/entitlements.go
Added inline documentation to the GracePeriod field describing it as a period where values won't be snapshotted, effectively including late events.
Snapshot Timing Refactor
openmeter/credit/balance.go, openmeter/credit/connector.go
Replaced snapshot "before" field with "notAfter" semantics throughout. New getSnapshotNotAfter(lastResetAt, at) method in connector.go computes snapshot time via grace period negation and clamps to lastResetAt to prevent snapshots after the last reset. Updated snapshot parameter passing in ResetUsageForOwner and GetBalanceSinceSnapshot.
History API
openmeter/credit/engine/history.go
Added GetPeriods() method to GrantBurnDownHistory that returns a slice of timeutil.ClosedPeriod collected from internal segments.
Tracing & Instrumentation
openmeter/credit/helper.go, openmeter/credit/trace.go, openmeter/entitlement/metered/balance.go
Enhanced runEngineInSpan to tag tracing spans with engine run parameters and history periods as JSON. Added WithEngineParams() method to ctrace for OpenTelemetry attributes. Updated WithPeriod() to format timestamps as RFC3339. Added tracing attributes (entitlement_id, at) to GetEntitlementBalance span.
Test Coverage
openmeter/entitlement/metered/balance_test.go
Expanded test suite with new cases covering snapshot creation at period starts, grace period breakpoints with/without prior snapshots, and balance/usage calculations across multiple periods. Updated expected snapshot timestamps to reflect period-start semantics.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Snapshot timing refactor: The transition from "before" to "notAfter" with the lastResetAt clamping logic requires careful reasoning across balance.go and connector.go to ensure correctness.
  • Tracing additions: Mostly repetitive attribute tagging across multiple files; review these for consistency with RFC3339 formatting and JSON marshaling error handling in helper.go.
  • Test expansion: Balance_test.go has significant new test cases; verify edge cases around grace period boundaries and period-start snapshot creation align with the new getSnapshotNotAfter behavior.

Possibly related PRs

Suggested reviewers

  • turip
  • tothandras

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "feat(entitlements): improve snapshotting behavior" directly captures the main objective of the changeset. All modifications across the eight files—from snapshot timing logic (balance.go, connector.go), to tracing enhancements (trace.go, helper.go), to test coverage (balance_test.go)—are unified around improving how entitlement snapshots are handled. The title uses conventional commit format with a clear scope (entitlements) and action verb (improve), making it concise yet specific enough that a teammate scanning the history would understand this PR addresses snapshot behavior improvements.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/entitlements/snapshotting-improvements

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 and usage tips.

@GAlexIHU
GAlexIHU enabled auto-merge (squash) October 30, 2025 16:30

@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

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 58c348d and aec893d.

📒 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.go
  • openmeter/credit/connector.go
  • openmeter/entitlement/metered/balance.go
  • app/config/entitlements.go
  • openmeter/entitlement/metered/balance_test.go
  • openmeter/credit/helper.go
  • openmeter/credit/balance.go
  • openmeter/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.go
  • openmeter/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 the notAfter boundary.


104-107: I can see the implementation does hit the database via GetEntitlement(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 GetUsagePeriodStartAt does hit the database with a GetEntitlement call, 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 GetUsagePeriodStartAt query before merging.

This change adds a database call to every balance query (confirmed: the implementation calls GetEntitlement in openmeter/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 notAfter semantics where both Since and At are 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.

Comment on lines +69 to +73
if marshalErr != nil {
m.Logger.WarnContext(ctx, "failed to marshal periods for tracing", "error", err)
} else {
span.SetAttributes(attribute.String("periods", string(periodsJSON)))
}

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.

⚠️ Potential issue | 🟡 Minor

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.

Suggested change
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/bug-fix Release note: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants