Skip to content

Persisting Usage in Snapshots (History Rewrite Part III) - #2406

Merged
GAlexIHU merged 5 commits into
mainfrom
galexi/history-rewrite-3
Mar 11, 2025
Merged

GAlexIHU merged 5 commits into
mainfrom
galexi/history-rewrite-3

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented Mar 10, 2025 •

Copy link
Copy Markdown
Contributor

Overview

Part II

  • Adds usage information to snapshots (all known usage in the period of the snapshot up to that point)
  • As this cannot easily be backfilled in the database, a service wrapper is added around the repo that fills this information
  • Engine now calculates usage too. The result snapshot will have the correct usage information to be used alongside the balance information
  • Snapshot behavior is changed so snapshots can be created in the current period too. The grace period has been decreased from P1W to P1D (so late events are guaranteed to be included for up to 1D)

Notes

  • In practice, snapshots will eventually be created for all reset times, and calculations will start from there.
  • There is no guarantee that any recent snapshots will be created. A snapshot can only be created during a query from a history breakpoint, and the history only breaks if grants or the usage period changes. We could later introduce extra breakpoints in the history to solve for this, but that would mean more smaller queries to ClickHouse.

Summary by CodeRabbit

  • New Features

    • Introduced advanced entitlement settings with a configurable grace period for improved entitlement management.
    • Enhanced balance snapshot functionality by integrating detailed usage tracking, providing more accurate billing and usage reporting.
    • Updated default configurations and sample settings to include these new entitlement and usage parameters.
    • Added new methods to manage and query usage data effectively within the balance and entitlement systems.
  • Bug Fixes

    • Improved error handling in entitlement balance calculations to provide more specific feedback on failures.
  • Tests

    • Introduced unit tests for the GetLatestValidAt method of the SnapshotService, covering various scenarios for usage data handling.

@GAlexIHU GAlexIHU added the release-note/misc Miscellaneous changes label Mar 10, 2025
@GAlexIHU GAlexIHU self-assigned this Mar 10, 2025
@GAlexIHU
GAlexIHU requested a review from a team as a code owner March 10, 2025 14:17
@coderabbitai

coderabbitai Bot commented Mar 10, 2025 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

This pull request introduces a new entitlement configuration that includes a grace period, and it propagates this configuration across multiple components. Method signatures, constructors, and service dependencies are updated to accept a configuration struct. Additionally, a new usage tracking mechanism is added to balance snapshots by introducing a new type to record usage metrics. The changes include updates to database schemas, ORM layer functions, and test cases, as well as associated SQL migrations for the new “usage” column.

Changes

File(s) Change Summary
app/common/entitlement.go, openmeter/registry/builder/entitlement.go, app/config/config.go, app/config/config_test.go, app/config/entitlements.go, config.example.yaml, openmeter/subscription/testutils/{customer.go,service.go}, test/{app/stripe/testenv.go,app/testenv.go,billing/suite.go,customer/testenv.go} Added a new EntitlementsConfiguration with a GracePeriod field. Updates include modifying function signatures (e.g. NewEntitlementRegistry), adding a new ConfigureEntitlements function, and updating configuration defaults and YAML examples. Test setups are modified to pass the new entitlement configuration.
cmd/balance-worker/wire_gen.go, openmeter/billing/worker/subscription/sync_test.go, openmeter/credit/connector.go, test/entitlement/regression/framework_test.go, openmeter/entitlement/metered/{lateevents_test.go,utils_test.go} Refactored the credit connector to use a consolidated configuration struct (CreditConnectorConfig) that now includes a new BalanceSnapshotService, replacing direct repository injections.
openmeter/credit/adapter/{balance_snapshot.go,transaction.go}, openmeter/credit/balance/{balance.go,repository.go,service.go,usage.go}, openmeter/credit/engine/{history.go,run.go,reset_test.go,run_test.go} Introduced the SnapshottedUsage type and integrated usage data within balance snapshots. Methods and constructors are updated for transaction management, and new service and querier interfaces are added. Engine methods now factor in usage data when calculating balance history.
openmeter/ent/db/{balancesnapshot.go,balancesnapshot/balancesnapshot.go,balancesnapshot/where.go,balancesnapshot_create.go,balancesnapshot_update.go,migrate/schema.go,mutation.go}, openmeter/ent/schema/balance_snapshot.go Added a new nullable JSON column "usage" to the balance snapshots. Updates include new constants, adjustments to scanning/assignment logic, and enhancements to mutation methods for setting, retrieving, clearing, and resetting the usage field. SQL migration files are included to add/drop this column.
openmeter/entitlement/metered/{balance.go,balance_test.go,reset_test.go} Modified entitlement balance calculation to use the latest snapshot and its usage data. Test cases now work with the new balanceSnapshotService and validate the updated balance and usage fields.
openmeter/credit/{grant.go,helper.go}, tools/migrate/migrations/{20250307151454_balance-snapshot-usage.down.sql,20250307151454_balance-snapshot-usage.up.sql} Minor renames and refactoring for consistent naming conventions in repository/service references and helper methods. Added SQL migration scripts to add/drop the usage column from the balance_snapshots table.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 28566e8 and 13a75fc.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (60)
  • openmeter/billing/worker/subscription/sync_test.go (2 hunks)
  • openmeter/credit/adapter/balance_snapshot.go (2 hunks)
  • openmeter/credit/adapter/transaction.go (1 hunks)
  • openmeter/credit/balance.go (7 hunks)
  • openmeter/credit/balance/balance.go (1 hunks)
  • openmeter/credit/balance/repository.go (1 hunks)
  • openmeter/credit/balance/service.go (1 hunks)
  • openmeter/credit/balance/usage.go (1 hunks)
  • openmeter/credit/connector.go (3 hunks)
  • openmeter/credit/engine/history.go (2 hunks)
  • openmeter/credit/engine/reset_test.go (5 hunks)
  • openmeter/credit/engine/run.go (4 hunks)
  • openmeter/credit/engine/run_test.go (2 hunks)
  • openmeter/credit/grant.go (2 hunks)
  • openmeter/credit/helper.go (4 hunks)
  • openmeter/ent/db/balancesnapshot.go (4 hunks)
  • openmeter/ent/db/balancesnapshot/balancesnapshot.go (2 hunks)
  • openmeter/ent/db/balancesnapshot/where.go (1 hunks)
  • openmeter/ent/db/balancesnapshot_create.go (4 hunks)
  • openmeter/ent/db/balancesnapshot_update.go (2 hunks)
  • openmeter/ent/db/migrate/schema.go (3 hunks)
  • openmeter/ent/db/mutation.go (10 hunks)
  • openmeter/ent/schema/balance_snapshot.go (1 hunks)
  • openmeter/entitlement/metered/balance.go (1 hunks)
  • openmeter/entitlement/metered/balance_test.go (6 hunks)
  • openmeter/entitlement/metered/lateevents_test.go (3 hunks)
  • openmeter/entitlement/metered/reset_test.go (2 hunks)
  • openmeter/entitlement/metered/utils_test.go (3 hunks)
  • openmeter/registry/builder/entitlement.go (2 hunks)
  • test/entitlement/regression/framework_test.go (3 hunks)
  • tools/migrate/migrations/20250307151454_balance-snapshot-usage.down.sql (1 hunks)
  • tools/migrate/migrations/20250307151454_balance-snapshot-usage.up.sql (1 hunks)
  • app/common/entitlement.go (1 hunks)
  • app/config/config.go (1 hunks)
  • app/config/config_test.go (2 hunks)
  • app/config/entitlements.go (1 hunks)
  • cmd/balance-worker/wire_gen.go (2 hunks)
  • config.example.yaml (1 hunks)
  • openmeter/billing/worker/subscription/sync_test.go (1 hunks)
  • openmeter/credit/balance.go (12 hunks)
  • openmeter/credit/connector.go (1 hunks)
  • openmeter/credit/grant.go (8 hunks)
  • openmeter/credit/helper.go (4 hunks)
  • openmeter/entitlement/metered/balance_test.go (1 hunks)
  • openmeter/entitlement/metered/lateevents_test.go (2 hunks)
  • openmeter/entitlement/metered/utils_test.go (2 hunks)
  • openmeter/registry/builder/entitlement.go (3 hunks)
  • openmeter/subscription/testutils/customer.go (3 hunks)
  • openmeter/subscription/testutils/service.go (3 hunks)
  • test/app/stripe/testenv.go (3 hunks)
  • test/app/testenv.go (4 hunks)
  • test/billing/suite.go (3 hunks)
  • test/customer/testenv.go (3 hunks)
  • test/entitlement/regression/framework_test.go (2 hunks)
  • app/config/entitlements.go (1 hunks)
  • openmeter/credit/balance/service_test.go (1 hunks)
  • openmeter/credit/helper.go (1 hunks)
  • openmeter/credit/helper.go (1 hunks)
  • openmeter/credit/adapter/transaction.go (1 hunks)
  • openmeter/entitlement/metered/lateevents_test.go (1 hunks)
✨ 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.

@GAlexIHU

Copy link
Copy Markdown
Contributor Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Mar 10, 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: 3

🔭 Outside diff range comments (2)
openmeter/credit/balance.go (2)

41-108: 🛠️ Refactor suggestion

Implementation of GetBalanceSinceSnapshot.
This method cleanly computes the balance from the last snapshot. The flow looks logical, with well-structured error handling.

  • Consider removing or addressing the TODO about artificial history breakpoints so these tasks don’t get lost.
  • Verify that partial usage periods are handled correctly if snap.At is very close to at.

Do you want me to open a new issue to track the artificial history breakpoints TODO item?


190-314: 🛠️ Refactor suggestion

Comprehensive usage reset flow.
Reusing the engine to compute final usage before resetting is logical. A couple of suggestions:

  • Check for concurrency race conditions when resets happen in quick succession.
  • Verify thorough testing for edge cases, like resets near the boundary of the usage period.
🧹 Nitpick comments (9)
openmeter/credit/connector.go (1)

24-36: Consider adding basic field validation in CreditConnectorConfig.
All fields in this config struct are exported and may be set to nil or misconfigured. For robustness, consider validating critical references (e.g., repos, services) to avoid runtime panics.

 func NewCreditConnector(cfg CreditConnectorConfig) CreditConnector {
+   if cfg.GrantRepo == nil || cfg.BalanceSnapshotService == nil || cfg.TransactionManager == nil {
+       panic("CreditConnectorConfig: missing mandatory dependencies")
+   }
    return &connector{
        CreditConnectorConfig: cfg,
    }
 }
openmeter/credit/balance/usage.go (1)

22-37: Config struct is flexible but ensure concurrency safety.
Storing function references like DescribeOwner, GetDefaultParams is convenient for testing, but check that concurrency scenarios (parallel calls) are either unlikely or handled.

openmeter/credit/balance/service.go (1)

21-30: Config-driven approach is consistent but watch for nil fields.
SnapshotServiceConfig references external connectors and repos. Similar to the credit connector config, consider validating these dependencies if usage in production demands stability.

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

36-47: Consider modularizing the dependencies struct if it grows further.
These new fields align well with the transition to a service-based architecture. However, if this dependencies struct continues to expand, you might consider modularizing fields or using more specific test fixtures to avoid overly large dependency objects.

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

40-43: Expanded dependencies struct.
The updated fields for GrantRepo, BalanceSnapshotService, and GrantConnector appear consistent. Just be mindful of potential growth if more dependencies are added.

openmeter/credit/balance.go (2)

35-36: GetLastValidSnapshotAt interface extension.
This looks straightforward. Ensure all callers handle potential “no snapshot found” scenarios gracefully.


130-188: Ensure consistent rounding approach across methods.
GetBalanceForPeriod also rounds the period to the next minute. Consider centralizing this rounding logic to avoid duplication or divergence over time.

openmeter/credit/helper.go (2)

26-26: Consider using structured logging.
Using m.Logger.DebugContext(ctx, "message", "owner", owner.ID, "time", at) would be more consistent with key-value logs elsewhere in this file.

- m.Logger.Debug(fmt.Sprintf("no saved balance found for owner %s before %s, calculating from start of time", owner.ID, at))
+ m.Logger.DebugContext(ctx, "no saved balance found for owner",
+     "owner", owner.ID,
+     "before", at,
+     "detail", "calculating from start of time",
+ )

87-87: Minor grammatical fix in comment.

- // We build a custom UsageQuerier for our usecase here. The engine should only every query the one owner we fetched above.
+ // We build a custom UsageQuerier for our use case here. The engine should only ever query the one owner we fetched above.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 567eb70 and 28566e8.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (44)
  • app/common/entitlement.go (1 hunks)
  • app/config/config.go (1 hunks)
  • app/config/config_test.go (2 hunks)
  • app/config/entitlements.go (1 hunks)
  • cmd/balance-worker/wire_gen.go (2 hunks)
  • config.example.yaml (1 hunks)
  • openmeter/billing/worker/subscription/sync_test.go (2 hunks)
  • openmeter/credit/adapter/balance_snapshot.go (2 hunks)
  • openmeter/credit/adapter/transaction.go (1 hunks)
  • openmeter/credit/balance.go (13 hunks)
  • openmeter/credit/balance/balance.go (1 hunks)
  • openmeter/credit/balance/repository.go (1 hunks)
  • openmeter/credit/balance/service.go (1 hunks)
  • openmeter/credit/balance/usage.go (1 hunks)
  • openmeter/credit/connector.go (1 hunks)
  • openmeter/credit/engine/history.go (2 hunks)
  • openmeter/credit/engine/reset_test.go (5 hunks)
  • openmeter/credit/engine/run.go (4 hunks)
  • openmeter/credit/engine/run_test.go (2 hunks)
  • openmeter/credit/grant.go (8 hunks)
  • openmeter/credit/helper.go (5 hunks)
  • openmeter/ent/db/balancesnapshot.go (4 hunks)
  • openmeter/ent/db/balancesnapshot/balancesnapshot.go (2 hunks)
  • openmeter/ent/db/balancesnapshot/where.go (1 hunks)
  • openmeter/ent/db/balancesnapshot_create.go (4 hunks)
  • openmeter/ent/db/balancesnapshot_update.go (2 hunks)
  • openmeter/ent/db/migrate/schema.go (3 hunks)
  • openmeter/ent/db/mutation.go (10 hunks)
  • openmeter/ent/schema/balance_snapshot.go (1 hunks)
  • openmeter/entitlement/metered/balance.go (1 hunks)
  • openmeter/entitlement/metered/balance_test.go (6 hunks)
  • openmeter/entitlement/metered/lateevents_test.go (4 hunks)
  • openmeter/entitlement/metered/reset_test.go (2 hunks)
  • openmeter/entitlement/metered/utils_test.go (3 hunks)
  • openmeter/registry/builder/entitlement.go (3 hunks)
  • openmeter/subscription/testutils/customer.go (3 hunks)
  • openmeter/subscription/testutils/service.go (3 hunks)
  • test/app/stripe/testenv.go (3 hunks)
  • test/app/testenv.go (4 hunks)
  • test/billing/suite.go (3 hunks)
  • test/customer/testenv.go (3 hunks)
  • test/entitlement/regression/framework_test.go (4 hunks)
  • tools/migrate/migrations/20250307151454_balance-snapshot-usage.down.sql (1 hunks)
  • tools/migrate/migrations/20250307151454_balance-snapshot-usage.up.sql (1 hunks)
🔇 Additional comments (123)
tools/migrate/migrations/20250307151454_balance-snapshot-usage.up.sql (1)

1-2: Database schema change looks good

The migration adds a new nullable JSON column usage to the balance_snapshots table, which aligns with the PR objective of incorporating usage information into snapshots.

tools/migrate/migrations/20250307151454_balance-snapshot-usage.down.sql (1)

1-2: Down migration is correctly implemented

The down migration properly drops the usage column to revert the schema change if needed.

config.example.yaml (1)

57-58: Configuration change matches PR objectives

Adding the entitlements.gracePeriod configuration with P1D aligns with the PR objective of reducing the grace period from one week to one day, allowing late events to be included in snapshots for up to one day.

app/config/config_test.go (2)

17-17: Imported package appropriately added

The isodate package is correctly imported to support the new entitlements configuration with ISO 8601 duration format.


139-141: Test configuration updated correctly

The test expectations have been appropriately updated to include the new Entitlements configuration with the GracePeriod set to P1D, which maintains consistency with the example configuration and ensures tests will pass with the new configuration structure.

openmeter/ent/schema/balance_snapshot.go (1)

33-35: Good addition of usage field to support snapshots history

The new JSON field for storing usage data in snapshots is implemented correctly using the appropriate field type and configuration options. Making it immutable and optional aligns with the snapshot pattern.

openmeter/ent/db/balancesnapshot/balancesnapshot.go (2)

29-30: Good addition of the usage field constant

The field constant definition follows the established pattern in the codebase.


59-59: Good addition of usage field to Columns

The field is correctly added to the Columns slice, making it available for database operations.

app/config/config.go (1)

186-186: Good integration of entitlements configuration

The addition of entitlements configuration follows the pattern used for other components and supports the grace period changes mentioned in the PR.

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

184-190: Good implementation of snapshot usage testing

This test setup correctly creates a SnapshottedUsage instance with appropriate values to test usage persistence in snapshots.


196-196: Good integration of usage in starting snapshot

The test correctly includes the usage field in the starting snapshot parameters.


208-208: Good verification of usage persistence

The assertion correctly verifies that the original usage information is preserved in the result snapshot, with a helpful comment explaining the expected behavior.

openmeter/ent/db/balancesnapshot/where.go (1)

358-366: Implementation for the new Usage field query predicates

These new functions allow for querying whether the "usage" field is null or not in the database. This is a consistent addition following the same pattern as other nullable fields in the file (e.g., DeletedAtIsNil).

openmeter/credit/grant.go (4)

36-36: Field naming convention updates

The field referencing has been updated from m.grantRepo to m.GrantRepo, which appears to be part of a broader refactoring to standardize naming conventions for repository/service dependencies.


44-44: Consistent renaming of service references

The references to m.ownerConnector have been updated to m.OwnerConnector throughout the file. This is consistent with the other dependency renaming in this PR.

Also applies to: 53-53, 62-62, 128-128, 133-133


84-84: Repository to Service upgrade for balance snapshots

The references have been changed from m.balanceSnapshotRepo to m.BalanceSnapshotService, suggesting an architectural change from direct repository access to using a service wrapper, which aligns with the PR objectives of introducing a service wrapper around the repository.

Also applies to: 145-145


138-139: New property reference for granularity

The code now uses m.Granularity to truncate the timestamp, which likely comes from the new configuration structure. This ensures consistent time handling across the system.

test/app/stripe/testenv.go (1)

129-131: Grace period configuration change

The grace period has been reduced from one week to one day ("P1D") as specified in the PR objectives. This ensures that late events can be included in snapshots for up to one day, which is consistent with the PR's goal to modify snapshot behavior.

openmeter/ent/db/balancesnapshot_update.go (1)

127-129: Support for clearing the new Usage field

These additions handle the case when the Usage field needs to be cleared, ensuring proper SQL operations. The implementation follows the same pattern as the existing DeletedAt field clearing, maintaining code consistency.

Also applies to: 276-278

openmeter/credit/balance/balance.go (3)

71-74: Good addition of the SnapshottedUsage type.

This new type provides a clear way to track both usage metrics and their timestamps together, which aligns with the PR objective of enhancing snapshots with usage information.


76-78: Well-implemented utility method.

The IsZero() method provides a clean way to check if a usage record is effectively empty. This will be useful for conditional logic elsewhere in the codebase.


81-81: Good integration of the Usage field into the Snapshot struct.

The addition of the Usage field to the Snapshot struct properly integrates the new usage tracking functionality with the existing balance snapshot functionality.

openmeter/ent/db/balancesnapshot.go (4)

35-36: Good addition of the Usage field to the BalanceSnapshot struct.

The field is properly defined with appropriate JSON tags and pointer type, which allows for null values in the database.


74-74: Good update to scanValues for the new field.

The scanValues method is correctly updated to handle the new Usage field, ensuring it's properly processed when retrieved from the database.


144-151: Well-implemented assignValues logic for the Usage field.

The code correctly handles unmarshaling the Usage field from a byte slice, with proper error handling and nil checks. This ensures the field is correctly populated from database values.


231-233: Properly updated String method.

The String method is correctly updated to include the new Usage field, ensuring it's represented in string representations of the BalanceSnapshot entity.

openmeter/subscription/testutils/service.go (1)

80-82: Good implementation of the grace period configuration.

The code properly initializes the EntitlementsConfiguration with a grace period of "P1D" (1 day), which aligns with the PR objective of reducing the grace period from one week to one day to ensure that late events can be included in snapshots for up to one day.

openmeter/ent/db/balancesnapshot_create.go (3)

87-91: Well-implemented SetUsage method.

The SetUsage method follows the pattern of other setter methods in the file and properly integrates with the mutation system.


248-251: Good handling of the Usage field in createSpec.

The code properly handles setting the Usage field in the create specification and node, following the pattern used for other fields.


386-388: Consistent handling of Usage field in update logic.

The code correctly handles the Usage field in the update logic for both single and bulk operations, ensuring it's properly ignored when appropriate in upsert operations.

Also applies to: 652-654

test/customer/testenv.go (2)

9-9: New imports for configuration and ISO date handling

These imports support the new entitlements configuration with grace period functionality.

Also applies to: 20-20


87-89: Grace period reduced from 1 week to 1 day

The EntitlementsConfiguration is initialized with a grace period of "P1D" (1 day), aligning with the PR objective to reduce the grace period from one week to one day. This change ensures that late events can be included in snapshots for up to one day.

openmeter/credit/balance/repository.go (1)

13-13: Helpful documentation clarifies potential data limitations

This comment provides important information to consumers of the GetLatestValidAt method, explicitly stating that the returned Snapshot might not contain usage data. This aligns with the PR objective of incorporating usage information in snapshots.

cmd/balance-worker/wire_gen.go (2)

136-136: Configuration extraction for entitlements

Extracts the entitlements configuration from the main configuration object for clearer usage in dependency injection.


181-187: Updated EntitlementOptions with configuration struct

Added the EntitlementsConfiguration field to the EntitlementOptions struct, properly propagating the configuration to the entitlement registry. This change supports the PR objective of enhancing snapshots with usage information.

app/common/entitlement.go (1)

30-36: Dependency injection updated with entitlements configuration

The EntitlementOptions struct now includes the EntitlementsConfiguration parameter, ensuring that the grace period configuration is properly passed to the registry builder. This change supports consistent handling of grace periods across the application.

test/billing/suite.go (1)

19-19: Imported necessary packages and added EntitlementsConfiguration with a 1-day grace period.

The changes correctly implement the grace period reduction from one week to one day as mentioned in the PR objectives. This configuration is now passed to the entitlement registry during test suite setup.

Also applies to: 39-39, 106-108

openmeter/subscription/testutils/customer.go (1)

11-11: Configured EntitlementsConfiguration with consistent grace period.

These changes ensure that customer tests use the same one-day grace period, maintaining consistency with the changes in the main test suite.

Also applies to: 22-22, 74-76

test/app/testenv.go (1)

12-12: Applied EntitlementsConfiguration consistently across test environments.

The grace period configuration is properly applied in both the NewTestEnv and InitBillingService functions, ensuring consistent behavior throughout testing.

Also applies to: 33-33, 106-108, 238-240

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

73-82: Improved entitlement balance calculation using snapshots instead of periods.

The balance calculation logic has been refactored to first retrieve the last valid snapshot at a given time and then calculate the balance since that snapshot. This approach aligns with the PR objective of enhancing snapshot functionality to incorporate usage information.

The error handling has also been improved with more specific error messages that indicate which operation failed.


87-87: Updated usage calculation to use the snapshot's usage data directly.

This change ensures that the usage information accurately reflects what's stored in the snapshot, which is consistent with the PR objective of ensuring snapshots contain accurate usage information alongside balance data.

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

42-42: Return type updated from interface to concrete type

The function now returns a pointer to balanceSnapshotRepo instead of the balance.SnapshotRepo interface. This change aligns with the service wrapper approach introduced in this PR for incorporating usage information in snapshots.

app/config/entitlements.go (4)

13-15: New configuration struct for entitlements

This introduces the EntitlementsConfiguration struct with a GracePeriod field to support the grace period reduction from one week to one day mentioned in the PR.


19-25: Proper validation for the GracePeriod field

Good validation implementation that ensures the GracePeriod is both provided and valid.


30-37: Robust GetGracePeriod method with fallback

This method properly handles error cases by logging the parsing error and falling back to a default value of 1 day.


39-42: Default configuration for grace period

Sets the default grace period to "P1D" (1 day), which aligns with the PR's objective of reducing the grace period to ensure that late events can be included in snapshots for up to one day.

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

81-84: New Usage tracking in snapshots

Adding the SnapshottedUsage struct to StartingSnapshot allows for tracking usage since the last reset, supporting the PR's objective of enhancing snapshots with usage information.


105-107: Test assertions for usage data after reset

These assertions verify that usage data is correctly reset after a reset operation, ensuring the snapshot reflects zero usage and updates the Since timestamp to the reset time.


184-187: Test setup for usage tracking without reset

This initializes a SnapshottedUsage struct with existing usage data to test the scenario where no reset occurs.


207-209: Test assertions for continuous usage tracking

These assertions verify that when no reset occurs, the usage data accumulates correctly and the Since timestamp is preserved.


244-246: Test assertions for usage at reset time

Verifies that at the exact reset time, usage is zero and the Since timestamp is updated to match the reset time, enforcing the reset behavior.

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

236-236: Updated to use service instead of repository

The code now uses the new balanceSnapshotService instead of the direct repository, aligning with the service wrapper approach introduced in this PR.


252-252: Updated retrieval to use service

Consistently updated to use balanceSnapshotService for retrieving snapshots, maintaining the architectural change throughout the test file.

openmeter/billing/worker/subscription/sync_test.go (3)

21-21: Added new import for balance module

The addition of the credit/balance import is necessary for the new balance snapshot service functionality.


215-219: Balance snapshot service implementation

Good implementation of the new balance snapshot service which replaces direct access to the repository. This service wrapper approach ensures all access to the repository goes through a single point, allowing for consistent handling of usage data.


223-235: Improved parameter organization using configuration struct

The refactoring to use a configuration struct instead of individual parameters improves code maintainability and makes it easier to add new parameters in the future. The addition of the BalanceSnapshotService and SnapshotGracePeriod fields aligns with the PR objective of enhancing snapshot functionality.

openmeter/credit/adapter/balance_snapshot.go (6)

13-13: Added entutils import for transaction handling

This import is necessary for the transaction management improvements in this file.


22-22: Return concrete type instead of interface

The function now returns a concrete type instead of an interface. This is consistent with the service wrapper approach being implemented.


28-35: Transaction handling for InvalidateAfter method

Good implementation of transaction handling using the entutils package. This ensures the database operations are executed within a transaction context, improving data consistency.


37-58: Transaction handling for GetLatestValidAt method

Well-structured implementation of transaction handling for fetching data. The method maintains its existing error handling and return types while adding transaction support.


60-77: Transaction handling and Usage field in Save method

The Save method now uses transaction handling and sets the new Usage field in the balance snapshot entity. This is a key implementation aligned with the PR objective of incorporating usage information in snapshots.


79-89: Updated mapping function for Usage field

The mapping function now properly handles the new Usage field, ensuring it's correctly transferred from the database entity to the domain model when present.

openmeter/registry/builder/entitlement.go (4)

7-7: Added config package import

The new import is necessary for the EntitlementsConfiguration addition.


26-32: Added EntitlementsConfiguration to options struct

Good addition of configuration field to the options struct, enabling the configuration of entitlement-related settings such as grace period in a centralized way.


54-58: Created balance snapshot service

This change implements the service wrapper around the repository, which is a key part of the PR objectives. The service abstraction provides a good separation of concerns.


60-72: Refactored credit connector initialization

The change to use a configuration struct instead of individual parameters improves code maintainability and readability. The addition of the SnapshotGracePeriod from the configuration enables more flexibility in configuration.

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

12-12: Added balance package import

This import is necessary for using the new balance snapshot service.


28-28: Added isodate package import

This import is required for parsing the ISO 8601 duration format used for the grace period.


144-149: Implemented balance snapshot service in tests

The test has been properly updated to use the new balance snapshot service instead of working directly with the repository. This ensures the test reflects the new architecture.


152-164: Updated credit connector initialization

The test now properly uses the new configuration struct approach for initializing the credit connector, including setting a grace period of one week. This ensures consistency with the production code.


190-190: Updated return value in test setup

The setupMockedConnector function now correctly returns the balance snapshot service instead of the repository, aligning with the changes in the production code.

openmeter/credit/connector.go (2)

21-22: Good use of struct embedding for clarity and maintainability.
By embedding CreditConnectorConfig, the connector type inherits config fields directly, minimizing boilerplate. This promotes cleaner code and straightforward usage of config fields.


39-42: Constructor simplifies parameter passing.
Switching to a single CreditConnectorConfig parameter is well-structured and reduces method signature bloat. Great improvement in readability.

openmeter/credit/balance/usage.go (3)

1-20: Interface-based design and imports appear consistent.
The UsageQuerier interface and related imports set a clear contract for querying usage. Keeping it minimal but well-defined sets a good foundation for future extension.


39-123: Implementation of QueryUsage covers multiple aggregations thoroughly.

  • Good usage of alpacadecimal to preserve precision when subtracting unique counts.
  • Proper fallback to 0 usage when times match or no data is found.
  • Carefully handles different aggregator types (UniqueCount, Sum, Count).

Potential considerations:

  1. Negative usage: If usage at “from” unexpectedly exceeds usage at “to,” you may end up with negative values. Clarify if this scenario is possible or needs special handling.
  2. Inexact float: InexactFloat64() may cause rounding issues for large or high-precision usage values. Verify if slight floating-point deviations are acceptable.

Overall, the logic is straightforward and robust for typical usage patterns.

Do you need a script to confirm that negative usage never occurs under normal system operations?


125-134: Carefully handling row count in getValueFromRows.
Returning 0.0 for zero rows is logical for usage queries, and erroring out on multiple rows avoids ambiguous usage results. Ensure upstream queries can only yield at most one row under all aggregator scenarios.

openmeter/credit/balance/service.go (5)

1-19: Interface definitions neatly capture snapshot operations.
Methods for invalidation, retrieval, and saving form a coherent API for managing snapshot lifecycle. The private service() method is a standard trick to prevent accidental direct struct implementations.


32-49: Custom UsageQuerier instantiation is well-structured.
Composing a specialized UsageQuerier inside NewSnapshotService demonstrates good DI patterns. It localizes usage logic while leveraging the flexible config methods.


53-55: InvalidateAfter logic is straightforward.
Delegating directly to the repository is clean and easy to follow. No concerns here.


57-85: Late usage filling on retrieved snapshots might cause partial data if usage is already partially saved.
It’s correct to recalculate usage if res.Usage.IsZero(), but be aware of edge cases if usage was only partially saved. Confirm that subsequent saves will update the usage to prevent data drift.

If you’d like, I can generate a script to check for any partial usage patterns or confirm every snapshot eventually sets usage properly.


87-89: Simple pass-through of Save operation to the repo.
The layering with a dedicated Repo keeps this method small and specialized. Implementation is good.

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

44-50: Well-implemented handling of usage information between periods

This new code block correctly resets the snapshot usage information when starting a new period between resets. By initializing a new SnapshottedUsage with the correct period start time and zeroing out the usage, it ensures proper tracking of usage metrics across period boundaries.


85-85: Appropriately updated to pass usage information to history creation

The NewGrantBurnDownHistory function call was correctly updated to include the starting snapshot's usage information, ensuring usage metrics are properly incorporated into the history tracking.


215-215: Consistent implementation of usage data passing to history creation

This change is consistent with the pattern established earlier, passing the starting snapshot's usage information to the history creation function.


225-228: Comprehensive implementation of usage tracking in snapshots

The snapshot return value now properly includes usage information with:

  1. The original measurement period start time preserved via params.StartingSnapshot.Usage.Since
  2. Cumulative usage calculation by adding previous usage to what was recorded in the current history

This ensures that usage data is accurately preserved across multiple calculations and snapshots.

openmeter/ent/db/migrate/schema.go (2)

207-208: Appropriate schema update for usage tracking

The addition of the usage column as a JSON field to the BalanceSnapshotsColumns array is a good implementation choice to support the new SnapshottedUsage struct. Using a JSON type allows flexibility in the structure while maintaining the ability to query and index efficiently.


222-222: Correctly adjusted foreign key and index references

The foreign key reference and index definitions have been properly updated to reflect the new column position after adding the usage column. This prevents any schema inconsistencies that could lead to runtime errors.

Also applies to: 236-236, 241-241, 246-246

openmeter/entitlement/metered/balance_test.go (4)

263-270: Well-implemented architectural change from repository to service pattern

The code has been refactored to use balanceSnapshotService.Save instead of direct repository access, which is a good architectural improvement for better separation of concerns. The test correctly initializes the new Usage field structure with appropriate values.


283-295: Consistent service pattern implementation with proper assertions

This section continues the repository-to-service refactoring pattern and correctly asserts the expected structure of the retrieved snapshot, including the new Usage field with its components.


305-320: Thorough validation of snapshot data including usage tracking

The test correctly validates both the retrieval mechanism and the content of the retrieved snapshot, with specific assertions for the Usage field's Since and Usage properties. The test properly verifies that snapshots at reset times have zeroed usage values.


324-447: Well-designed test for usage tracking across periods

This new test case thoroughly validates the functionality of recording and retrieving usage data across different periods. It:

  1. Sets up grants spanning multiple periods
  2. Registers usage events in different periods
  3. Creates breakpoints in history with new grants
  4. Verifies that snapshots correctly record usage from the right starting point
  5. Validates that the total usage calculation is accurate across resets and periods

This is a comprehensive test that ensures the usage tracking functionality works as expected in a variety of scenarios.

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

31-31: Import usage looks good.
No concerns regarding the addition of the isodate import.


131-141: Double-check SnapshotGracePeriod consistency.
You're using a 1-week grace period here (P1W). If your current requirement is for a 1-day grace period, please ensure alignment in tests and production code to avoid confusion.


163-163: Field assignment looks correct.
No issues with adding snapshotService to the returned dependencies struct.

test/entitlement/regression/framework_test.go (4)

31-31: New import usage looks fine.
No concerns about adding isodate here.


123-128: Initialization of balanceSnapshotService.
The creation of balance.NewSnapshotService is correctly parameterized. Ensure appropriate test coverage for boundary scenarios.


131-142: Confirm grace period logic in CreditConnectorConfig.
You set the SnapshotGracePeriod to isodate.NewPeriod(...) for 1 day. This is presumably aligned with updated requirements, but verify consistency with any references to a 1-week grace period.


184-184: Balanced injection into dependencies.
Adding BalanceSnapshotService to your dependencies struct is straightforward and consistent with other fields.

openmeter/credit/balance.go (2)

25-26: New method signature for GetBalanceSinceSnapshot.
Defining a separate method for partial computations is a good addition. Keep an eye on consistent usage across the codebase.


110-128: Check the rounding logic in GetBalanceAt.
Truncating and then adding a minute may skip up to nearly a full minute of usage data. Verify that this behavior is intentional and aligned with the expected business rules.

openmeter/credit/helper.go (13)

14-14: No concerns about the new import.


19-22: Public method rename looks good.
The expanded doc comment and new name reflect the intent to provide a valid snapshot or fallback to recalculating from the start. This makes the function more self-explanatory.


28-28: OwnerConnector usage.
Switching to the exported OwnerConnector aligns with the uppercase naming convention. No issues found.


33-33: Active grants retrieval is consistent.
The call to ListActiveGrantsBetween matches the rest of the logic for snapshot backfill. Looks good.


88-111: UsageQuerier approach looks solid.
This design tightly scopes the queried owner to avoid cross-owner logic confusion. The inlined callback functions also make the usage flow more transparent. Good job.


121-122: Good direct delegation to usageQuerier.
No issues with querying usage in the provided time range as you’ve already validated bounds above.


138-139: Snapshot logic extraction is well-structured.
Separating out snapshotEngineResult enhances readability and reuse. No concerns here.


153-153: Saving snapshot within the segment loop looks correct.
The error handling is straightforward; no issues found regarding concurrency or deadlocks.


164-167: Inactive grants removal logic is consistent.
This ensures snapshots persist only relevant grants. Consider confirming test coverage for scenarios with few or many inactive grants.


169-171: Single-snapshot save.
Saving via a slice parameter is fine if the implementation expects multiple snapshots. No red flags spotted.


173-173: Consistent logging.
Good use of DebugContext for structured logs. All fields appear relevant.


175-176: Clean final return.
No further improvements needed.


147-148:

Details

✅ Verification successful

Double-check boundary condition.
Using !seg.From.After(snapParams.before) means segments starting exactly at snapParams.before will still be persisted. Confirm that this inclusive check is intentional.


🏁 Script executed:

#!/bin/bash
# Verify usage of inclusive boundary conditions across the code:
rg --context 3 "After\("

Length of output: 66017


Boundary Condition Verified: Inclusive Comparison is Intentional

After reviewing similar boundary checks across the codebase, it's clear that using !seg.From.After(snapParams.before) to include segments that start exactly at snapParams.before is consistent with our current design. This inclusive check aligns with comparable patterns (e.g., using !time.After(…) in several other modules) ensuring correct handling of edge cases such as backfilling, granting, and resetting.

  • Location: openmeter/credit/helper.go (Lines 147-148)
  • Summary: The code intentionally persists segments where seg.From is equal to snapParams.before, following the established convention elsewhere in the system.
openmeter/credit/engine/history.go (6)

69-69: New parameter for usageAtStart is logical.
Providing the initial usage in the constructor centralizes the usage initialization. This clarifies baseline usage for the entire history.


89-89: Returning usageAtStart is consistent.
Storing both segments and usage in the returned struct sets the foundation for refined usage tracking logic.


93-95: Expanding the struct to include usageAtStart is clear.
These fields ensure the history can account for preexisting usage.


96-118: New GetSnapshotAtStartOfSegment method is well-defined.
Logic to compute usage resets and overage at segment boundaries is straightforward. Make sure tests exist for edge cases (e.g., segmentIndex = 0 and final segment).


120-155: Usage reset logic is properly encapsulated.
Methodically searching for the last reset ensures that usage accumulates correctly. Double-check coverage for consecutive resets.


161-161: Renamed method clarifies intent.
TotalUsageInHistory is more descriptive and consistent with the rest of the usage-based naming.

openmeter/ent/db/mutation.go (4)

4442-4489: Implementation is consistent with existing patterns

The implementation of the usage field management methods (Set, Get, Clear, etc.) follows the established patterns in the codebase. The error handling in OldUsage properly checks for update operations and ID presence.


4713-4713: Capacity adjustment for the new field

The slice capacity has been increased from 9 to 10 to accommodate the new field. This is a good optimization to avoid unnecessary reallocations.


4732-4734: Fields method properly includes the usage field

The usage field is correctly added to the returned slice when it exists, consistent with how other fields are handled.


4764-4765: Field accessor methods are correctly implemented

The implementation of the Field, OldField, SetField, ClearedFields, ClearField, and ResetField methods has been updated to handle the new usage field consistently with the existing pattern.

Also applies to: 4793-4794, 4852-4858, 4940-4942, 4960-4962, 4989-4991

Comment thread openmeter/credit/connector.go Resolved
updated_at *time.Time
deleted_at *time.Time
grant_balances *balance.Map
usage **balance.SnapshottedUsage

@coderabbitai coderabbitai Bot Mar 10, 2025 •

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.

💡 Verification agent

🧩 Analysis chain

Double pointer usage seems unusual

The field usage is defined as **balance.SnapshottedUsage (double pointer). While this might be intentional for managing nil values, double pointers can make the code harder to reason about and increase the chance of nil-related bugs.

Consider whether a single pointer would be sufficient:

-	usage              **balance.SnapshottedUsage
+	usage              *balance.SnapshottedUsage

Let's verify the usage pattern:


🏁 Script executed:

#!/bin/bash
# Check how SnapshottedUsage is used elsewhere in the codebase
rg "balance.SnapshottedUsage" --type go -A 2 -B 2

Length of output: 9109


Action Required: Simplify pointer usage in mutation field

After verifying how balance.SnapshottedUsage is used throughout the codebase, it’s clear that a double pointer is unnecessary. The field is declared as **balance.SnapshottedUsage only in the mutation file, while elsewhere (e.g., in schema and snapshot structures) a single pointer is used. In the mutation's setter, you currently take a pointer (bu) and then store its address (using &bu), which complicates the code and risks nil-related bugs.

Please update the code as follows:

  • In openmeter/ent/db/mutation.go:
    • Change the field declaration from:
      -	usage              **balance.SnapshottedUsage
      +	usage              *balance.SnapshottedUsage
    • Update the setter accordingly:
      -func (m *BalanceSnapshotMutation) SetUsage(bu *balance.SnapshottedUsage) {
      -	m.usage = &bu
      -}
      +func (m *BalanceSnapshotMutation) SetUsage(bu *balance.SnapshottedUsage) {
      +	m.usage = bu
      +}

This change simplifies the code by eliminating the unnecessary double pointer and aligns the usage pattern with the rest of the codebase.

📝 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
usage **balance.SnapshottedUsage
// ... other parts of openmeter/ent/db/mutation.go ...
// BalanceSnapshotMutation represents a mutation for a balance snapshot.
type BalanceSnapshotMutation struct {
// ... other fields ...
- usage **balance.SnapshottedUsage
+ usage *balance.SnapshottedUsage
// ... other fields ...
}
// SetUsage updates the usage field for the balance snapshot mutation.
-func (m *BalanceSnapshotMutation) SetUsage(bu *balance.SnapshottedUsage) {
- m.usage = &bu
-}
+func (m *BalanceSnapshotMutation) SetUsage(bu *balance.SnapshottedUsage) {
+ m.usage = bu
+}
// ... remaining parts of the file ...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@tothandras lets add a CodeRabbit exclusion rule for generated code, this is funny to see but not too helpful

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.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Comment thread app/config/entitlements.go Outdated
return errors.New("gracePeriod is required")
}

if _, err := c.GracePeriod.Parse(); err != nil {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Let's also validate that it's a positive value.

Comment thread openmeter/credit/balance.go Resolved
}

if err := m.balanceSnapshotRepo.Save(ctx, params.owner, []balance.Snapshot{snap}); err != nil {
if _, err := m.saveSnapshot(ctx, snapParams, snap); err != nil {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We need to be careful regarding time truncation here. I think we are fine as grants and resets are truncated, but we must never store even with the new engine such a snapshot that is not truncated to an exact second.


err = m.balanceSnapshotRepo.WithTx(ctx, tx).Save(ctx, ownerID, []balance.Snapshot{startingSnap})
// Let's save the snapshot
snap, err = m.saveSnapshot(ctx, snapshotParams{

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

docs: We should also document that a reset causes the late events coming with times before the reset time to be not included in the entitlement history e.g. in case of an overflow.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That's not 100%. A late-event arriving before a reset will cause a historical inconsistency, i.e. if you were to "delete" the reset and do it again, it would yield a different result. This in practice means that programmatic and manual resets handle them differently. As late events are not properly addressed system-wise, I'd say this is out of scope for now.

GetLatestValidAt(ctx context.Context, owner models.NamespacedID, at time.Time) (Snapshot, error)
Save(ctx context.Context, owner models.NamespacedID, balances []Snapshot) error
// To make sure repo doesn't implement the service interface
service()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

:D

Comment thread openmeter/credit/balance/service.go Resolved
Comment thread openmeter/credit/helper.go Resolved
Comment thread openmeter/credit/helper.go Outdated

func (m *connector) saveSnapshot(ctx context.Context, params snapshotParams, snap balance.Snapshot) (balance.Snapshot, error) {
// Let's validate the timestamp
if snap.At.Truncate(m.Granularity) != snap.At {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please use equals.

turip
turip previously approved these changes Mar 11, 2025

@turip turip left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

One comment otherwise looks good.

Base automatically changed from galexi/history-rewrite-2 to main March 11, 2025 14:44
@GAlexIHU
GAlexIHU dismissed turip’s stale review March 11, 2025 14:44

The base branch was changed.

@GAlexIHU
GAlexIHU force-pushed the galexi/history-rewrite-3 branch from 939f527 to 820a7ce Compare March 11, 2025 14:47
turip
turip previously approved these changes Mar 11, 2025
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