Skip to content

Balance & Usage Consistency (History Rewrite Part II) - #2383

Merged
GAlexIHU merged 8 commits into
mainfrom
galexi/history-rewrite-2
Mar 11, 2025
Merged

GAlexIHU merged 8 commits into
mainfrom
galexi/history-rewrite-2

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented Mar 7, 2025 •

Copy link
Copy Markdown
Contributor

Overview

Changes metered/balance to use credit's history calculation. This way period's usage information is only queried once & is consistent with balance and grant information.

  • As a side-effect, snapshots generated for the current usage period will be ignored in the calculations, effectively making the calculations slower (Part III will address this)
  • includes some bugfixes around current period calculation

Summary by CodeRabbit

  • New Features

    • Enhanced active grant filtering now includes grants effective at period endpoints for more accurate tracking.
    • Improved balance and usage reporting for credits and entitlements, delivering more consistent and detailed information.
    • Refined usage period calculation and reset processing for entitlements to improve precision in tracking metrics.
  • Tests

    • Expanded test coverage to validate late event handling and ensure balance consistency under various scenarios.
    • Updated tests to align with new balance retrieval methods and data structures.
    • Streamlined tests to focus on usage events and their impact on grant balances.

@GAlexIHU GAlexIHU added the release-note/bug-fix Release note: Bug Fixes label Mar 7, 2025
@GAlexIHU
GAlexIHU requested a review from a team as a code owner March 7, 2025 11:29
@coderabbitai

coderabbitai Bot commented Mar 7, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This update spans several modules. In the credit package, a new condition was added to include grants effective at the query’s end time, and the balance retrieval interface was revised by replacing old methods with new ones that return a detailed engine result. The grant burn down history now uses a singular history instance with a new snapshot method, and tests were updated to access history via a Segments() method. In the entitlement package, balance methods are restructured to utilize the updated credit interface, and new logic in usage period calculation and tests for late events, resets, and voiding has been introduced.

Changes

File(s) Change Summary
openmeter/credit/adapter/grant.go Added an extra SQL query condition in ListActiveGrantsBetween to include grants effective at the to time.
openmeter/credit/balance.go Removed GetBalanceOfOwner/GetBalanceHistoryOfOwner; added GetBalanceAt/GetBalanceForPeriod returning engine.RunResult with standardized error handling.
openmeter/credit/engine/[engine.go, history.go, reset_test.go, run.go, run_test.go, helper.go] Updated grant burn down history management: changed RunResult.History from an array to a singular instance, added the ToSnapshot method, revised NewGrantBurnDownHistory signature, renamed variables, and modified tests to use History.Segments().
openmeter/entitlement/metered/balance.go Revised GetEntitlementBalance and GetEntitlementBalanceHistory to use GetBalanceForPeriod, changing error handling and accessing balance data from snapshots.
openmeter/entitlement/metered/grant_owner_adapter.go Enhanced GetUsagePeriodStartAt with entitlement parsing and a decision branch to return either the measurement start or the current period start time.
openmeter/entitlement/metered/[lateevents_test.go, reset_test.go, utils_test.go] Introduced late events tests, updated reset tests to use GetBalanceAt with an added resetTime parameter, and expanded test dependencies with a new creditConnector field.
test/entitlement/regression/scenario_test.go Removed snapshot balance creation and the grant1 variable; replaced with usage event additions and updated void time management in voiding scenarios.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Comment thread openmeter/credit/adapter/grant.go Resolved
Comment thread openmeter/credit/balance.go Resolved
@GAlexIHU
GAlexIHU force-pushed the galexi/history-rewrite branch from ec3e9fb to 37b2c68 Compare March 7, 2025 11:34
@GAlexIHU
GAlexIHU force-pushed the galexi/history-rewrite-2 branch from fd3c4a0 to 9284c3a Compare March 7, 2025 11:58
@GAlexIHU

GAlexIHU commented Mar 7, 2025

Copy link
Copy Markdown
Contributor Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Mar 7, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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 (3)
openmeter/credit/engine/engine.go (1)

31-31: Improved encapsulation of history data

The change from []GrantBurnDownHistorySegment to GrantBurnDownHistory represents a better design approach by encapsulating the segments within a dedicated type. This improves the API by providing controlled access to the segments via methods rather than exposing the array directly.

openmeter/credit/balance.go (1)

118-127: Consider adding error validation for empty period.

The method properly handles time rounding for period.To, but there's no validation that the period is non-empty (From <= To).

 func (m *connector) GetBalanceForPeriod(ctx context.Context, ownerID models.NamespacedID, period timeutil.Period) (engine.RunResult, error) {
 	m.logger.Debug("calculating history for owner", "owner", ownerID.ID, "period", period)
 
 	var def engine.RunResult
 
+	// Validate period is not empty
+	if period.From.After(period.To) {
+		return def, fmt.Errorf("invalid period: From (%s) is after To (%s)", period.From, period.To)
+	}
+
 	// To include the current last minute lets round it trunc to the next minute
 	if trunc := period.To.Truncate(time.Minute); trunc.Before(period.To) {
 		period.To = trunc.Add(time.Minute)
openmeter/entitlement/metered/balance.go (1)

234-240: Consider adding specific error handling for owner not found.

Similar to the GetEntitlementBalance method, you might want to handle OwnerNotFoundError specifically here as well.

 historyRes, err := e.balanceConnector.GetBalanceForPeriod(ctx, owner.NamespacedID, timeutil.Period{
 	From: periodToQueryEngine.From,
 	To:   periodToQueryEngine.To,
 })
 if err != nil {
+	if _, ok := err.(*grant.OwnerNotFoundError); ok {
+		return nil, engine.GrantBurnDownHistory{}, &entitlement.NotFoundError{EntitlementID: entitlementID}
+	}
 	return nil, engine.GrantBurnDownHistory{}, fmt.Errorf("failed to get balance history: %w", err)
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 37b2c68 and 9284c3a.

📒 Files selected for processing (14)
  • openmeter/credit/adapter/grant.go (1 hunks)
  • openmeter/credit/balance.go (5 hunks)
  • openmeter/credit/engine/engine.go (1 hunks)
  • openmeter/credit/engine/history.go (2 hunks)
  • openmeter/credit/engine/reset_test.go (4 hunks)
  • openmeter/credit/engine/run.go (4 hunks)
  • openmeter/credit/engine/run_test.go (6 hunks)
  • openmeter/credit/helper.go (1 hunks)
  • openmeter/entitlement/metered/balance.go (4 hunks)
  • openmeter/entitlement/metered/grant_owner_adapter.go (2 hunks)
  • openmeter/entitlement/metered/lateevents_test.go (1 hunks)
  • openmeter/entitlement/metered/reset_test.go (10 hunks)
  • openmeter/entitlement/metered/utils_test.go (2 hunks)
  • test/entitlement/regression/scenario_test.go (1 hunks)
🔇 Additional comments (37)
openmeter/credit/adapter/grant.go (1)

177-177: Correctly includes grants effective at period end

Adding the condition to include grants that are effective exactly at the query end time (to) ensures proper inclusion of all relevant grants in the calculation.

openmeter/credit/helper.go (1)

217-217: Simplified access to history segments

This change correctly leverages the new GrantBurnDownHistory type by directly accessing its segments through the Segments() method, eliminating the need for additional object creation and error handling that was likely present in the previous implementation.

openmeter/entitlement/metered/reset_test.go (3)

325-335: Updated test to use new balance structure

The test has been properly updated to reflect changes in the balance API, now accessing balances through creditBalance.Snapshot.Balances rather than directly through creditBalance.Balances.


397-407: Updated test to use new balance structure

Tests are correctly updated to reflect the new structure of the balance data returned by GetBalanceAt.


469-479: Updated test to use new balance structure

The test is properly updated to access balance data through the new structure, maintaining consistency with the API changes.

openmeter/credit/engine/run_test.go (4)

129-129: Updated history access pattern.

The code now uses the new Segments() method to access history data instead of directly accessing the underlying array. This change aligns with the structural modifications in the History field of the RunResult struct.


311-315: History access pattern updated consistently.

The history access pattern has been correctly updated to use the Segments() method throughout the test cases. This ensures consistency with the new data structure.


345-348: Properly migrated to new History access pattern.

All test assertions have been properly migrated to access history segments through the Segments() method.


798-876: History accessor pattern consistently applied.

The changes consistently apply the new pattern across all test assertions, ensuring that the tests align with the underlying implementation changes in the History data structure.

openmeter/entitlement/metered/grant_owner_adapter.go (2)

131-134: Added entitlement parsing with proper error handling.

Good addition of entitlement parsing with appropriate error handling to ensure invalid entitlements don't cause runtime issues.


149-162: Enhanced period calculation logic.

The new logic correctly differentiates between the first usage period and subsequent periods, which helps ensure consistency with balance and grant information. This aligns with the PR objective of ensuring usage information is queried only once.

The implementation:

  1. Calculates the first period using the original anchor and activation time
  2. Checks if the current period matches the first period
  3. Returns the appropriate start time based on the period comparison
openmeter/entitlement/metered/utils_test.go (2)

46-47: Added creditConnector to dependencies struct.

This addition aligns with the modifications in the balance retrieval logic elsewhere in the codebase.


157-158: Including creditConnector in returned dependencies.

Properly included the creditConnector in the returned dependencies structure, ensuring it's available for tests that need access to the updated balance retrieval functionality.

openmeter/credit/engine/reset_test.go (5)

102-103: Updated history access pattern.

The code now uses the Segments() method to access history data rather than directly accessing the array, consistent with the structural changes in the History field of the RunResult struct.


104-116: Consistently updated history access pattern.

All assertions have been consistently updated to use the Segments() method for accessing history segments, ensuring proper alignment with the updated data structure.


152-167: History access pattern updated consistently.

The method for accessing history segments has been properly updated throughout the assertions in this test case, maintaining consistency with the new data structure approach.


194-198: History accessor updated correctly.

Length check and termination reason assertions properly migrated to use the new Segments() method.


227-231: History assertions updated with detailed error messages.

The test includes a detailed error message in the assertion, which is helpful for debugging if the test fails. The termination reason checks also use the new Segments() method consistently.

test/entitlement/regression/scenario_test.go (2)

345-349: Improved approach to testing grant deduction based on priority.

The added usage event with its associated comment provides clarity on how the priority-based deduction should work, making the test more comprehensive.


354-357: Good enhancement for test accuracy.

Storing the void time in a variable and adding a usage event before voiding the grant is a good approach to test the correct temporal ordering of operations. This helps verify that the system correctly handles usage events that occur before a grant is voided.

openmeter/credit/engine/history.go (2)

69-76: Well-designed snapshot method addition.

This new ToSnapshot method nicely encapsulates the conversion from a history segment to a snapshot, improving code organization and reusability.


78-99: Good change from pointer to value return type.

Switching from returning a pointer to returning a value type for NewGrantBurnDownHistory is a good practice that makes the function more predictable and reduces the need for nil checks.

openmeter/entitlement/metered/lateevents_test.go (2)

31-55: Well-designed test infrastructure for simulating late events.

The inconsistentCreditConnector implementation is a clever way to inject events before and after the balance retrieval calls, allowing the test to verify consistency in the face of late-arriving events.


57-230: Comprehensive test for balance consistency with late events.

This thorough test case verifies that balance calculations remain consistent even when events arrive late, directly addressing the PR's objective of maintaining consistency between balance and usage information.

The assertion on line 229 effectively verifies that the balance, usage, and overage values correctly sum to the total grant amount, which is a crucial invariant.

openmeter/credit/engine/run.go (4)

41-41: Improved variable naming for clarity.

Renaming history to historySegments provides better context about the variable's contents and purpose.


58-58: Updated history access pattern.

Changing from direct append to using runRes.History.Segments() shows a more structured approach to accessing history segments, aligning with the new GrantBurnDownHistory design.


77-81: Enhanced error handling for history creation.

Adding proper error handling when creating the grant burn down history improves robustness and makes debugging easier by providing specific error messages.


207-211: Consistent error handling pattern.

Applying the same error handling pattern for history creation in both methods maintains consistency throughout the codebase.

openmeter/credit/balance.go (4)

26-31: Interface changes align with PR objectives.

The interface has been revised to use new methods that return more comprehensive engine.RunResult data instead of simple snapshots, aligning with the goal to ensure consistency between balance and usage data.


38-46: Time rounding logic ensures completeness.

The rounding logic ensures that partial usage in the last minute is included in calculations by rounding up to the next minute if needed.


98-102: Important grant filtering logic.

This code ensures that inactive grants at query time are excluded from results, which is consistent with the handling in regular snapshotting code as noted in your previous comments.


140-153: Initial balance calculation approach is efficient.

Using GetBalanceAt to obtain the starting snapshot for the period and then continuing calculation from that point is a good optimization pattern.

openmeter/entitlement/metered/balance.go (5)

58-62: Time rounding is now consistent with balance connector.

The rounding logic ensures partial usage in the last minute is included and correctly notes this won't affect usage period boundaries.


74-83: Good adaptation to new interface with proper error handling.

The code now uses the new GetBalanceForPeriod method with appropriate period parameters and correctly handles OwnerNotFoundError by converting it to an entitlement-specific error.


87-89: Updated result field access.

The code correctly adapts to the new structure by accessing balance, usage, and overage from their appropriate locations in the result.


243-243: Adaptation to new history structure.

Correctly accessing segments from the new history structure in the result.


346-346: Return value adaptation.

Returning the history directly from the result is consistent with the interface changes.

@GAlexIHU

GAlexIHU commented Mar 7, 2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Mar 7, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Base automatically changed from galexi/history-rewrite to main March 7, 2025 12:36
@GAlexIHU
GAlexIHU force-pushed the galexi/history-rewrite-2 branch from 9284c3a to 047f1ba Compare March 7, 2025 12:38

@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: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9284c3a and 047f1ba.

📒 Files selected for processing (14)
  • openmeter/credit/adapter/grant.go (1 hunks)
  • openmeter/credit/balance.go (5 hunks)
  • openmeter/credit/engine/engine.go (1 hunks)
  • openmeter/credit/engine/history.go (2 hunks)
  • openmeter/credit/engine/reset_test.go (4 hunks)
  • openmeter/credit/engine/run.go (4 hunks)
  • openmeter/credit/engine/run_test.go (6 hunks)
  • openmeter/credit/helper.go (1 hunks)
  • openmeter/entitlement/metered/balance.go (4 hunks)
  • openmeter/entitlement/metered/grant_owner_adapter.go (2 hunks)
  • openmeter/entitlement/metered/lateevents_test.go (1 hunks)
  • openmeter/entitlement/metered/reset_test.go (10 hunks)
  • openmeter/entitlement/metered/utils_test.go (2 hunks)
  • test/entitlement/regression/scenario_test.go (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
openmeter/entitlement/metered/lateevents_test.go (1)
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.
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: CI
  • GitHub Check: Analyze (go)
🔇 Additional comments (46)
openmeter/credit/engine/engine.go (1)

31-31: Type change enhances history structure.

The History field is now a single GrantBurnDownHistory object rather than an array of segments. This structured approach centralizes history management and provides better encapsulation of history segments.

openmeter/credit/helper.go (1)

217-217: Changed to use the new Segments() method.

Updated to access history segments through the new method, which aligns with the structural changes to the History field in the RunResult struct.

openmeter/credit/adapter/grant.go (1)

177-177: Added condition to include grants effective at period end.

This change ensures that grants becoming effective exactly at the end time of the period are correctly included in the query results, which is necessary for consistent balance calculations.

openmeter/credit/engine/reset_test.go (1)

102-102: Updated to use the new Segments() method in tests.

All test assertions now access history segments through the Segments() method instead of directly. This change maintains consistency with the structural changes to the History field in the RunResult struct.

Also applies to: 105-107, 110-110, 113-115, 152-152, 155-158, 161-161, 164-166, 194-194, 196-197, 227-227, 229-230

openmeter/entitlement/metered/reset_test.go (3)

324-334: API usage update looks good

The test properly adopts the new GetBalanceAt method instead of GetBalanceOfOwner and correctly accesses the balance information via the Snapshot field.


397-406: Consistent API usage

The test consistently follows the pattern of using GetBalanceAt and accessing values through Snapshot.Balances.


469-478: API usage consistently applied across test cases

Good job maintaining consistency across all test cases with the new approach to accessing balance data.

openmeter/entitlement/metered/utils_test.go (2)

46-46: Added creditConnector to dependencies struct

Good addition of the creditConnector field to the dependencies struct to support the updated API usage in the tests.


157-157: Updated setup for creditConnector

The dependencies return statement properly includes the new creditConnector reference, keeping the code consistent with struct definition.

openmeter/credit/engine/run_test.go (1)

129-129: Migration to Segments() method for accessing history

The test has been properly updated to use the new Segments() method for accessing history data instead of directly accessing the History field. This change is consistent throughout the file and maintains the test assertions correctly.

Also applies to: 311-314, 345-348, 439-445, 866-876

openmeter/entitlement/metered/grant_owner_adapter.go (2)

131-134: Added proper parsing and error handling

Good addition of code to parse the entitlement into a metered variable with appropriate error handling.


149-162: Enhanced logic for first usage period calculation

This is a meaningful enhancement that correctly distinguishes between the first usage period and subsequent periods. The code:

  1. Calculates the first period using the original anchor and activation time
  2. Compares if current period equals first period
  3. Returns measurement start time for the first period, otherwise returns the current period start

The implementation is well-commented and maintains the original functionality while adding the new logic.

test/entitlement/regression/scenario_test.go (2)

345-349: Good use of comments to clarify expected behavior

The added comments help developers understand the test logic: this usage event is expected to be deducted from grant 2 due to priority rules. Clear comments like these improve test readability and maintainability.


354-357: Good refactoring for more reliable tests

Storing the void time in a variable and adding a usage event before voiding the grant provides a more consistent testing approach. This aligns with the PR goal of ensuring usage information for a period is queried only once.

openmeter/entitlement/metered/lateevents_test.go (2)

32-45: Well-structured mock for testing late events

The inconsistentCreditConnector is a good approach for testing how the system handles events that arrive during balance calculation. By adding events before and after the actual balance query, this effectively tests the consistency mechanisms.

I'm leveraging your team's established pattern of using package-scoped variables like meterSlug in test files.


57-231: Comprehensive test for balance calculation consistency

This test thoroughly verifies that balance and usage values remain consistent even when late events arrive during calculation. This directly addresses the PR objective of utilizing history calculation to ensure usage information is queried only once.

The test structure follows good practices:

  1. Clear setup with helper functions
  2. Proper cleanup with defer statements
  3. Explicit assertions that validate the balance calculation consistency
openmeter/credit/engine/history.go (2)

69-76: Useful addition of ToSnapshot method

Adding the ToSnapshot method to GrantBurnDownHistorySegment provides a clean way to convert a history segment to a snapshot. This supports the PR goal of modifying the balance functionality to utilize history calculation.


78-99: Good refactoring from pointer to value return

Changing NewGrantBurnDownHistory to return a value instead of a pointer makes the code more consistent and aligns with modern Go practices for small structs. The error handling is also properly updated to return a zero value instead of nil.

openmeter/credit/engine/run.go (4)

41-42: Improved variable naming

Renaming history to historySegments makes the code more descriptive and clarifies that this variable holds segments rather than the complete history object.


57-59: Updated history segments handling

This change properly uses the new Segments() method to access the history segments, aligning with the structural changes in the history implementation.


77-81: Proper error handling added

Adding error handling for NewGrantBurnDownHistory improves robustness by ensuring that any issues with history creation are properly caught and reported.


207-211: Consistent error handling pattern

The error handling for NewGrantBurnDownHistory follows the same pattern as in the main Run method, ensuring consistency throughout the codebase.

openmeter/entitlement/metered/balance.go (5)

58-62: Verify rounding-up approach for minute boundary.
These lines force the timestamp to the next minute boundary when it's not already aligned. Ensure this logic aligns with the intended business rule (i.e., capturing partial usage in the last minute).


74-82: Use of GetBalanceForPeriod and error path looks good.
The new code properly translates an OwnerNotFoundError into an entitlement.NotFoundError, maintaining a clear hierarchy of errors.


87-89: Field usage aligns with the new engine result.
The usage and overage fields are now sourced from the RunResult struct. Looks consistent with the updated design.


243-243: Segments retrieval aligns with the updated History struct.
Accessing segments from historyRes.History.Segments() is consistent with the new engine approach.


346-346: Returning the final computed windows and History looks correct.
This ensures both the per-window breakdown and the overall burn-down history are provided to the caller.

openmeter/credit/balance.go (19)

26-33: New interface methods provide clearer period-based balance retrieval.
Replacing the old methods with GetBalanceAt, GetBalanceForPeriod, and the updated ResetUsageForOwner signature is a solid step toward unifying the logic.


38-42: Implementation for GetBalanceAt appears correct.
The approach to round up to the nearest minute and maintain a default engine.RunResult for error scenarios is reasonable. Double-check off-by-one minute edge cases.


51-51: No issues with immediate error return.
Graceful fallback to def ensures consistency in the return type under error conditions.


62-62: Same pattern of returning a default on error.
This matches the overall error-handling approach.


67-67: No further concerns here.


73-73: No further concerns here.


81-81: No further concerns here.


95-97: No major issues with the error return path.


98-101: Ensure inactive grant removal is accurate.
Double-check that removeInactiveGrantsFromSnapshotAt correctly identifies grants that should remain active at the given time.


111-111: Error return consistency maintained.


115-115: Final return of run result is aligned with the new flow.
No issues identified.


119-124: Method-level documentation and definitions look consistent.
Declaring a default engine.RunResult before the logic is consistent with the rest of the file.


125-126: Rounding up the period’s end time.
As with the other rounding logic, verify that this approach captures the complete usage in that final minute.


132-132: No further concerns here.


137-137: No further concerns here.


141-148: Integration with GetBalanceAt and grants retrieval.
These calls look appropriate for retrieving the starting snapshot and grants required to compute the period usage.


152-156: Snapshot update for grants becoming active exactly at the start.
Filling in missing grants ensures the snapshot stays consistent with the period’s actual entitlements.


174-174: No further concerns for error handling here.


177-177: Final return of result.
This wraps up the period-based calculation correctly.

turip
turip previously approved these changes Mar 7, 2025
Comment thread openmeter/credit/balance.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: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 047f1ba and 721067b.

📒 Files selected for processing (1)
  • openmeter/credit/balance.go (5 hunks)
🔇 Additional comments (23)
openmeter/credit/balance.go (23)

38-38: Implementation introduced.

The new method signature for GetBalanceAt is clear; no issues identified.


51-51: Error return looks good.

Returning an empty RunResult plus the encountered error is consistent with the existing pattern.


61-62: Error handling is consistent.

Looks good; the context-specific error message provides clarity.


67-67: Error handling is consistent.

No issues spotted; message is descriptive.


71-71: Grant listing logic.

The repository call for active grants in the specified time range is straightforward.


73-73: Error handling is consistent.

No issues here; consistent error messaging.


81-81: Return on engine build error.

Looks good; returning immediately on engine build failure is appropriate.


95-96: Balance calculation error fallback.

Checks and returns are properly handled.


98-101: Ensuring snapshot consistency by removing inactive grants.

This is a sensible addition. It helps maintain accurate snapshot data.


111-111: Snapshot error path.

Consistent handling of snapshot engine errors.


115-115: Successful return.

Looks correct; returning the computed result.


122-122: Repeated default result pattern.

Same observation as before: consider inlining the default return instead of defining a variable.


131-132: Reset timeline retrieval.

Error handling is consistent and descriptive.


137-137: Describing owner error path.

Looks fine; thorough error message.


141-143: Fetching initial snapshot for period start.

Calling GetBalanceAt from within GetBalanceForPeriod is logical; no concerns.


147-147: Grant retrieval extended range.

Correctly retrieves grants spanning the entire period.


149-149: Error fallback.

No issues; consistent usage.


152-153: Snapshot extraction.

Extracting the starting snapshot from the previous run result is straightforward.


156-156: Populate snapshot with newly active grants.

Appropriate logic to ensure completeness of the snapshot.


160-160: Engine build error fallback.

Same consistent pattern; no issues spotted.


167-167: Passing snapshot in RunParams.

Implementation follows established pattern.


174-174: Final balance error case.

Good coverage with an informative error message.


177-177: Return final engine result.

End of method logic is clear and consistent.

Comment thread openmeter/credit/balance.go Resolved
Comment thread openmeter/credit/balance.go Resolved
Comment thread openmeter/credit/balance.go Resolved
Comment thread openmeter/credit/balance.go Resolved
@GAlexIHU
GAlexIHU force-pushed the galexi/history-rewrite-2 branch from 721067b to 85058b7 Compare March 10, 2025 14:01

@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: 0

🧹 Nitpick comments (3)
openmeter/credit/balance.go (2)

38-41: Consider adding more context to method documentation.

While the documentation comment explains the method's purpose, it would be helpful to add information about edge cases, performance characteristics, or why calculating from the latest valid snapshot is important for users of this interface.


118-119: Function documentation could be more specific.

The comment describes what the function does but doesn't explain when to use this method versus GetBalanceAt or what "exactly match the provided period" means in practical terms for callers.

openmeter/credit/engine/history.go (1)

78-78: Consider method receiver consistency

The return type of NewGrantBurnDownHistory has been changed from a pointer to a value, but the methods on GrantBurnDownHistory (lines 105-120) still use pointer receivers. This creates inconsistency in how the struct is handled.

If the intent is to use value semantics, consider updating the method receivers:

-func (g *GrantBurnDownHistory) Segments() []GrantBurnDownHistorySegment {
+func (g GrantBurnDownHistory) Segments() []GrantBurnDownHistorySegment {

Or if pointer semantics are preferred (for performance with larger structs):

-func NewGrantBurnDownHistory(segments []GrantBurnDownHistorySegment) (GrantBurnDownHistory, error) {
+func NewGrantBurnDownHistory(segments []GrantBurnDownHistorySegment) (*GrantBurnDownHistory, error) {

This would ensure consistent handling across the codebase.

Also applies to: 94-94, 98-98

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 721067b and 567eb70.

📒 Files selected for processing (14)
  • openmeter/credit/adapter/grant.go (1 hunks)
  • openmeter/credit/balance.go (5 hunks)
  • openmeter/credit/engine/engine.go (1 hunks)
  • openmeter/credit/engine/history.go (2 hunks)
  • openmeter/credit/engine/reset_test.go (4 hunks)
  • openmeter/credit/engine/run.go (4 hunks)
  • openmeter/credit/engine/run_test.go (6 hunks)
  • openmeter/credit/helper.go (1 hunks)
  • openmeter/entitlement/metered/balance.go (4 hunks)
  • openmeter/entitlement/metered/grant_owner_adapter.go (2 hunks)
  • openmeter/entitlement/metered/lateevents_test.go (1 hunks)
  • openmeter/entitlement/metered/reset_test.go (10 hunks)
  • openmeter/entitlement/metered/utils_test.go (2 hunks)
  • test/entitlement/regression/scenario_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (9)
  • openmeter/credit/engine/engine.go
  • openmeter/credit/adapter/grant.go
  • openmeter/credit/helper.go
  • openmeter/entitlement/metered/utils_test.go
  • openmeter/credit/engine/run.go
  • openmeter/entitlement/metered/balance.go
  • openmeter/credit/engine/run_test.go
  • openmeter/entitlement/metered/reset_test.go
  • openmeter/credit/engine/reset_test.go
🧰 Additional context used
🧠 Learnings (1)
openmeter/entitlement/metered/lateevents_test.go (1)
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.
🔇 Additional comments (11)
openmeter/credit/balance.go (4)

26-31: Interface updates improve clarity with explicit period-based methods.

The updated BalanceConnector interface now uses explicit methods for time-specific balance retrieval (GetBalanceAt and GetBalanceForPeriod), replacing the less descriptive methods. This makes the API more intuitive and aligns with the actual use cases.


98-102: Ensuring consistency by filtering inactive grants.

This new code handles an important edge case by removing grants that are no longer active at the query time, which is required for treating RunResults as virtual snapshots.


123-126: Time rounding logic duplicated between methods.

The time rounding logic appears in both GetBalanceAt and GetBalanceForPeriod. Consider extracting this to a helper function to avoid duplication and make future maintenance easier.


139-143: Good reuse of existing functionality.

Using GetBalanceAt to establish the starting point for period calculation is an efficient approach that minimizes code duplication and ensures consistency between the two methods.

test/entitlement/regression/scenario_test.go (1)

345-357: Test improvements with more realistic usage scenarios.

The test has been improved by adding actual usage events instead of manipulating snapshots directly. This approach better mimics real-world usage patterns and provides a more accurate test of the system's behavior. The added comments explaining the expected grant deduction behavior also improve code readability.

openmeter/entitlement/metered/grant_owner_adapter.go (1)

131-162: Enhanced period calculation logic correctly handles first usage period.

This change improves the accuracy of usage period calculations by correctly handling the first usage period separately from subsequent periods. The implementation now properly distinguishes between:

  1. The first period (when the entitlement becomes active) - returning the measurement start time
  2. Subsequent periods - returning the current period's start time

This ensures that usage is correctly measured from when the entitlement becomes active rather than from the period start for the first period.

openmeter/entitlement/metered/lateevents_test.go (3)

31-55: Well-designed test mock for simulating late events.

The inconsistentCreditConnector implementation is a good approach for testing late event handling. By adding events both before and after the balance calculation, it simulates the real-world scenario where events might arrive late or out of order.


57-89: Test setup is thorough and well-structured.

The test setup code defines clear helper functions for creating features and entitlements, making the test readable and maintainable. The use of a yearly interval in the default setup is a good choice for testing as it minimizes the chance of period boundaries affecting the test.


187-230: Test validates key business logic requirement.

This test effectively validates that the balance and usage calculations remain consistent even when events arrive late. The assertion checking that g1.Amount == entBalance.UsageInPeriod + entBalance.Balance - entBalance.Overage is particularly valuable as it ensures the core business logic remains correct regardless of event timing.

openmeter/credit/engine/history.go (2)

69-76: Clean implementation of ToSnapshot method

The addition of the ToSnapshot method to convert a segment's initial state into a balance.Snapshot is well-implemented. This facilitates consistency with the balance interfaces mentioned in the PR objectives.


78-99:

Details

✅ Verification successful

Verify all callers have been updated

The change from returning a pointer to returning a value requires all callers to be updated accordingly. Please verify that all code that calls NewGrantBurnDownHistory has been properly updated to handle the value return instead of a pointer.


🏁 Script executed:

#!/bin/bash
# Find all callers of NewGrantBurnDownHistory
echo "Searching for callers of NewGrantBurnDownHistory:"
rg "NewGrantBurnDownHistory\(" --type go

Length of output: 458


Action Required: Confirmed Caller Updates

All instances of NewGrantBurnDownHistory have been verified. The two call sites in openmeter/credit/engine/run.go are updated to handle a value return rather than a pointer, and no pointer-based accesses (e.g., using ->) are detected.

  • Caller in openmeter/credit/engine/run.go using history, err := NewGrantBurnDownHistory(historySegments)
  • Caller in openmeter/credit/engine/run.go using history, err := NewGrantBurnDownHistory(segments)

No further changes are required.

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