Skip to content

fix: progressive billing timing issues - #2827

Merged
turip merged 1 commit into
mainfrom
fix/progressive-billing-related-timing-issues
May 15, 2025
Merged

turip merged 1 commit into
mainfrom
fix/progressive-billing-related-timing-issues

Conversation

@turip

@turip turip commented May 15, 2025 •

Copy link
Copy Markdown
Member

Overview

This patch unifies the locking mechanism (previously we were using customer and invoice locks), as most of progressive billing actions require multiple invoice locks.

The patch also fixes the issue that if a syncronization would yield an empty ubp line, then we threw an error.

The patch also makes sure that progressively billed split lines do not prevent the deletion of the gathering invoice.

Summary by CodeRabbit

  • New Features

    • Added new locking functionality to billing operations, ensuring safer concurrent updates for customer-specific actions.
    • Introduced methods to determine if invoice lines or periods are empty, with special handling for usage-based and fee lines.
  • Refactor

    • Centralized and streamlined invoice locking and transaction management, reducing redundant explicit locking calls.
    • Improved handling of invoice line splitting and deletion, preventing creation of empty lines and supporting line deletion.
  • Bug Fixes

    • Enhanced subscription synchronization to properly handle empty usage-based lines by deleting them instead of updating, preventing validation errors.
  • Tests

    • Added new tests for progressive billing cancellation scenarios and improved test clarity for invoice state assertions.

@coderabbitai

coderabbitai Bot commented May 15, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This change removes explicit invoice locking methods from the billing adapter and centralizes transactional and locking behavior within a new WithLock method on the billing service. It introduces new methods for line deletion and empty period detection, updates interfaces accordingly, and refactors invoice and line service logic to use the new locking and transaction patterns. Additional test cases and utility methods are added to enhance test coverage and maintainability.

Changes

File(s) Change Summary
openmeter/billing/adapter.go
openmeter/billing/adapter/invoice.go
Removed LockInvoicesForUpdate method from InvoiceAdapter interface and its implementation.
openmeter/billing/invoiceline.go Added NonDeletedLineCount method to LineChildren for counting valid, non-deleted lines.
openmeter/billing/service.go Added LockableService interface with WithLock method and embedded it in Service.
openmeter/billing/service/invoice.go Refactored to remove explicit invoice locking; now uses centralized transaction/locking via transcationForInvoiceManipulation. Control flow updated to fetch minimal invoice data for customer context before transactional operations.
openmeter/billing/service/invoiceline.go Updated to use transcationForInvoiceManipulation instead of the previous transaction function. Added logging for nil pre-split lines during association.
openmeter/billing/service/lineservice/feeline.go Added IsPeriodEmptyConsideringTruncations() method to feeLine type, always returning false.
openmeter/billing/service/lineservice/linebase.go Extended LineBase interface with Delete method and implemented it. Refactored Split to avoid creating/saving empty-period lines and to delete empty pre-split lines.
openmeter/billing/service/lineservice/service.go Removed UpsertLines method. Extended Line interface with IsPeriodEmptyConsideringTruncations().
openmeter/billing/service/lineservice/usagebasedline.go Added IsPeriodEmptyConsideringTruncations() to usageBasedLine, checking for empty period after truncation.
openmeter/billing/service/lock.go New file: Implements WithLock method on Service for customer-scoped transactional locking, using the internal transaction helper.
openmeter/billing/service/service.go Renamed TranscationForGatheringInvoiceManipulation to transcationForInvoiceManipulation and updated documentation.
openmeter/billing/worker/subscription/sync.go Wrapped subscription synchronization logic in WithLock. Updated patch handling to delete usage-based lines with empty periods instead of updating them.
openmeter/billing/worker/subscription/sync_test.go Added test for progressive billing cancellation. Refactored billing profile update logic and improved assertions for invoice deletion in tests.
openmeter/server/server_test.go Added WithLock method to NoopBillingService, implementing the LockableService interface with a no-op lock.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

@turip turip added release-note/bug-fix Release note: Bug Fixes area/billing labels May 15, 2025
This patch unifies the locking mechanism (previously we were using
customer and invoice locks), as most of progressive billing actions
require multiple invoice locks.

The patch also fixes the issue that if a syncronization would yield
an empty ubp line, then we threw an error.

The patch also makes sure that progressively billed split lines do
not prevent the deletion of the gathering invoice.
@turip
turip force-pushed the fix/progressive-billing-related-timing-issues branch from 0a91a42 to 6228d25 Compare May 15, 2025 20:19
@turip
turip marked this pull request as ready for review May 15, 2025 20:19
@turip
turip requested a review from a team as a code owner May 15, 2025 20:19
@turip
turip requested review from hekike and tothandras May 15, 2025 20:19
@turip
turip enabled auto-merge (squash) May 15, 2025 20:24

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

🔭 Outside diff range comments (1)
openmeter/billing/service/lineservice/linebase.go (1)

241-261: ⚠️ Potential issue

Possible orphaned parent when both child periods are empty

If both preSplitAtLine and postSplitAtLine evaluate to empty and are skipped, the parent remains with status split but zero children, leaving the invoice in an inconsistent state.

Recommend:

  1. Detect the “both children empty” case.
  2. Either revert the parent’s status back to valid or mark the parent for deletion as well.
🧹 Nitpick comments (5)
openmeter/billing/service/lock.go (1)

13-24: Implementation of the new WithLock method.

This implementation provides the core functionality for the unified locking mechanism mentioned in the PR objectives. It:

  1. Uses a transaction to ensure atomicity
  2. Delegates to the transcationForInvoiceManipulation helper to manage locking
  3. Properly logs rollbacks when errors occur
  4. Ensures consistent error propagation

The approach centralizes locking behavior for all invoice-related operations, which should help prevent the timing issues mentioned in the PR objectives.

However, there appears to be a minor typo in the helper function name:

-transcationForInvoiceManipulation
+transactionForInvoiceManipulation
openmeter/billing/service/service.go (1)

145-147: Renamed and updated helper function for invoice manipulation.

The function has been renamed from TranscationForGatheringInvoiceManipulation to transcationForInvoiceManipulation and made unexported, generalizing its purpose from gathering-specific to any invoice manipulation. The comment also reflects this generalization.

This change supports the PR objective to unify the locking mechanism by providing a single, consistent approach to transactional operations on invoices.

There's a typo in the function name:

-transcationForInvoiceManipulation
+transactionForInvoiceManipulation
openmeter/billing/worker/subscription/sync.go (1)

221-231: Reuse the new helper instead of duplicating empty-period logic

You manually check

patch.TargetState.Period.Truncate(billing.DefaultMeterResolution).IsEmpty()

but the freshly-added IsPeriodEmptyConsideringTruncations() already encapsulates this rule.
Using it keeps the behaviour in one place and avoids future drift.

-if patch.Op == patchOpUpdate && patch.TargetState.Type == billing.InvoiceLineTypeUsageBased {
-    if patch.TargetState.Period.Truncate(billing.DefaultMeterResolution).IsEmpty() {
+if patch.Op == patchOpUpdate && patch.TargetState.Type == billing.InvoiceLineTypeUsageBased {
+    lineSrv, _ := h.billingService.LineService().FromEntity(patch.TargetState) // pseudo helper
+    if lineSrv.IsPeriodEmptyConsideringTruncations() {
         patches = append(patches, h.getDeletePatchesForLine(line.Existing)...)
         continue
     }
 }
openmeter/billing/service/lineservice/linebase.go (2)

173-179: Delete causes an immediate round-trip per line – batch it when possible

Delete sets DeletedAt then calls Save, which in turn triggers UpsertInvoiceLines for a single line.
In tight loops (e.g. mass split/deletions) this multiplies network/DB calls.

You already have a TODO for bulk upserts; consider exposing an internal flag to accumulate pending mutations and flush once per operation.


269-277: Minor: early‐return to avoid unnecessary object allocations

When postSplitAtLine.IsPeriodEmptyConsideringTruncations() is true you still build the struct.
A quick guard before cloning would save allocations:

- postSplitAtLine := l.CloneForCreate(...)
- if !postSplitAtLine.IsPeriodEmptyConsideringTruncations() {
+ if candidate := l.CloneForCreate(...); !candidate.IsPeriodEmptyConsideringTruncations() {
+     postSplitAtLine := candidate
      postSplitAtLine, err := postSplitAtLine.Save(ctx)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3793e15 and 6228d25.

📒 Files selected for processing (15)
  • openmeter/billing/adapter.go (0 hunks)
  • openmeter/billing/adapter/invoice.go (0 hunks)
  • openmeter/billing/invoiceline.go (1 hunks)
  • openmeter/billing/service.go (3 hunks)
  • openmeter/billing/service/invoice.go (3 hunks)
  • openmeter/billing/service/invoiceline.go (2 hunks)
  • openmeter/billing/service/lineservice/feeline.go (1 hunks)
  • openmeter/billing/service/lineservice/linebase.go (5 hunks)
  • openmeter/billing/service/lineservice/service.go (1 hunks)
  • openmeter/billing/service/lineservice/usagebasedline.go (1 hunks)
  • openmeter/billing/service/lock.go (1 hunks)
  • openmeter/billing/service/service.go (1 hunks)
  • openmeter/billing/worker/subscription/sync.go (2 hunks)
  • openmeter/billing/worker/subscription/sync_test.go (4 hunks)
  • openmeter/server/server_test.go (1 hunks)
💤 Files with no reviewable changes (2)
  • openmeter/billing/adapter.go
  • openmeter/billing/adapter/invoice.go
🧰 Additional context used
🧬 Code Graph Analysis (6)
openmeter/billing/service.go (1)
openmeter/customer/customer.go (1)
  • CustomerID (74-74)
openmeter/billing/service/lineservice/usagebasedline.go (2)
openmeter/billing/invoiceline.go (1)
  • Period (83-86)
openmeter/billing/defaults.go (1)
  • DefaultMeterResolution (12-12)
openmeter/billing/invoiceline.go (2)
openmeter/billing/service/lineservice/service.go (1)
  • Line (157-172)
api/api.gen.go (1)
  • InvoiceLineStatusValid (406-406)
openmeter/billing/service/lock.go (4)
openmeter/billing/service.go (2)
  • LockableService (90-92)
  • Service (10-21)
openmeter/billing/service/lineservice/service.go (1)
  • Service (22-24)
openmeter/billing/service/service.go (1)
  • Service (23-38)
pkg/framework/transaction/transaction.go (1)
  • RunWithNoValue (23-28)
openmeter/billing/service/invoice.go (4)
openmeter/billing/invoice.go (5)
  • GetInvoiceByIdInput (534-537)
  • Invoice (329-340)
  • InvoiceID (207-207)
  • InvoiceExpand (213-223)
  • InvoiceExpandAll (225-230)
api/api.gen.go (2)
  • Invoice (3300-3408)
  • InvoiceExpand (3488-3488)
api/client/go/client.gen.go (2)
  • Invoice (3001-3109)
  • InvoiceExpand (3165-3165)
openmeter/customer/customer.go (1)
  • CustomerID (74-74)
openmeter/billing/service/lineservice/linebase.go (4)
openmeter/ent/db/billinginvoiceline/where.go (1)
  • DeletedAt (87-89)
openmeter/ent/db/billinginvoice/where.go (1)
  • DeletedAt (88-90)
pkg/clock/clock.go (1)
  • Now (14-21)
openmeter/billing/invoiceline.go (1)
  • InvoiceLineStatusValid (46-46)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: Lint
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (16)
openmeter/billing/service/lineservice/usagebasedline.go (1)

448-451: LGTM: Good implementation of IsPeriodEmptyConsideringTruncations

The implementation correctly truncates the period using the default meter resolution before checking if it's empty, which aligns with the PR objective of fixing empty UBP line handling during synchronization.

openmeter/billing/service/lineservice/feeline.go (1)

123-126: LGTM: Clear implementation with good documentation

The method correctly implements the interface by explicitly returning false for fee lines, with a helpful comment explaining that fee lines are not subject to truncation checks and can be empty (for one-time fees).

openmeter/billing/invoiceline.go (1)

695-700: LGTM: Well-implemented line counting method

This method effectively counts non-deleted lines with valid status, specifically ignoring split lines as noted in the comment. This supports the PR objective of ensuring that progressively billed split lines don't block invoice deletion.

openmeter/server/server_test.go (1)

1489-1492: LGTM: Properly implemented no-op lock method for testing

The implementation correctly satisfies the LockableService interface by simply executing the provided function without applying any actual locking, which is appropriate for a test implementation. This supports the unified locking mechanism introduced in this PR.

openmeter/billing/service/invoiceline.go (2)

65-65: Function call renamed to align with refactored locking mechanism.

The function call has been updated from TranscationForGatheringInvoiceManipulation to transcationForInvoiceManipulation as part of the broader refactoring to centralize transactional and locking behavior.


321-323: Added handling for empty UBP lines during synchronization.

This check prevents errors when an empty UBP line is encountered during synchronization by logging a warning instead of proceeding with an empty line. This directly addresses one of the objectives in the PR to fix "a problem where synchronization could result in an empty UBP line, which previously caused an error to be thrown."

openmeter/billing/service.go (3)

7-7: Added customer package import to support new interface.

Added import for the customer package, which is needed for the CustomerID type used in the new LockableService interface.


16-16: Extending Service interface with new locking functionality.

The Service interface now embeds the LockableService interface, making locking capabilities part of the core billing service contract. This aligns with the PR objective to unify the locking mechanism used during progressive billing processes.


90-92: New interface for centralized locking mechanisms.

This new LockableService interface provides a clean abstraction for customer-scoped locking operations. The WithLock method allows execution of arbitrary functions within a transaction that holds an update lock on the customer record, centralizing concurrency control and eliminating the need for separate locks for customers and invoices as mentioned in the PR objectives.

openmeter/billing/service/lineservice/linebase.go (1)

299-316: Deletion path updates period fields but never persists them

When the pre-split line becomes empty you call Delete, which saves the line with DeletedAt set but also includes the newly-mutated PeriodEnd/InvoiceAt.
That’s fine, yet if the adapter rejects updates on deleted rows you might lose those period corrections.
Please check adapter semantics; if updates are ignored after soft-delete, assign DeletedAt before period mutation or drop the period updates.

openmeter/billing/service/invoice.go (4)

240-246: Consider correcting the miss-spelt helper name and add an explanatory comment

transcationForInvoiceManipulation is invoked here, but the word “transaction” is misspelled.
Even if the helper is defined with the same typo, the naming inconsistency adds friction for future readers and makes the code harder to grep for.

-	return transcationForInvoiceManipulation(
+	// Unified helper that wraps a DB‐transaction and a customer-level lock
+	return transactionForInvoiceManipulation(

If the helper is intentionally misspelled to keep compatibility with other files, please add a short TODO explaining that the name will be normalised in a later cleanup to avoid propagating the typo through new code.
[ suggest_optional_refactor ]


603-606: Potential micro-optimisation: avoid an extra round-trip for customer lookup

GetInvoiceByID is called solely to obtain the CustomerID so that a lock can be acquired later.
Because billing.InvoiceID already embeds Namespace and ID, you could save one DB call by:

  1. Extracting the customer ID directly (if it is derivable from the ULID/name structure); or
  2. Passing the invoice ID into the locking helper and letting the helper fetch the minimal header internally.

Not critical, but worth considering because this path is executed for every state-machine operation.
[ suggest_optional_refactor ]


611-622: Verify nested transaction / lock interaction to prevent dead-locks

withLockedInvoiceStateMachine wraps its callback inside transactionForInvoiceManipulation, which itself most likely:

  1. Begins a DB transaction (via transaction.Run), and
  2. Acquires a customer-level lock (WithLock).

The same pattern is already wrapped by an outer transaction.Run in callers such as AdvanceInvoice and RetryInvoice, so we end up with a transaction-in-transaction situation:

└─ outer transaction.Run
   └─ withLockedInvoiceStateMachine
      └─ transactionForInvoiceManipulation
         └─ (inner) transaction.Run + lock

Depending on the adapter implementation, starting a nested DB transaction can silently start a new connection (OK) or try to issue BEGIN twice on the same connection (error) or escalate to a save-point (OK but unexpected). Likewise, if WithLock uses advisory locks, obtaining the same lock twice from the same session may block.

Please double-check that:

• transaction.Run is re-entrant / starts save-points, or
• transactionForInvoiceManipulation detects an existing tx in the context and re-uses it.

Otherwise we risk sporadic dead-locks or “transaction already in progress” errors under load.
[ request_verification ]


877-934: Repeat of the miss-spelt helper & opportunity to deduplicate line re-loads

The same typo (transcationForInvoiceManipulation) appears here. See earlier comment about renaming.

Additionally, UpdateInvoice:

  1. Fetches invoice once (lines 861-867) to discover its status.
  2. Immediately refetches the same invoice (lines 878-887) inside the transaction.

If the first fetch only serves the “is Gathering?” branch decision, consider moving that logic into the transactional callback and removing the first query altogether to cut DB I/O in half.

This small change will also ensure the status check happens under the same lock, eliminating a narrow race where the invoice could change state between the two reads.
[ suggest_optional_refactor ]

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

1701-1896: Well-structured test for handling subscription cancellation during progressive billing

This new test correctly verifies a key objective from the PR: ensuring that progressively billed split lines don't block the deletion of the gathering invoice during subscription cancellation.

The test simulates a real-world scenario by:

  1. Setting up progressive billing
  2. Creating a subscription with a usage-based rate card
  3. Progressively billing for one day
  4. Cancelling the subscription right after
  5. Verifying that the gathering invoice is properly cleaned up

I like that you're testing the edge case where cancellation happens very quickly after progressive billing (using just 10ms difference), which helps ensure correct handling in timing-sensitive scenarios.


1487-1494: Good refactoring of profile update logic

The new updateProfile method nicely encapsulates the common profile update logic into a reusable helper method. Taking a function parameter for modifications provides a flexible approach that simplifies the calling code and makes future changes easier to manage.

Comment on lines +162 to +165
// IsPeriodEmptyConsideringTruncations returns true if the line has an empty period. This is different from Period.IsEmpty() as
// this method does any truncation for usage based lines.
IsPeriodEmptyConsideringTruncations() bool

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

❓ Verification inconclusive

Ensure downstream implementations conform to the new interface contract

IsPeriodEmptyConsideringTruncations() has been added to Line.
Please double-check that all concrete line types, test fakes, and mocks compile after this change (CI will catch it, but a quick go vet ./... locally avoids round-trips).
If any external packages implement Line, they will also need a shim.


🏁 Script executed:

#!/bin/bash
# Compile-time check that every type satisfying Line implements the new method.
go vet ./...

Length of output: 28103


Build failures block interface verification – fix undefined Kafka types first

go vet ./... is failing with multiple undefined Kafka types in pkg/kafka (e.g. kafka.ConfigMap, kafka.LogEvent, kafka.TopicSpecification, etc.), so the vet run cannot confirm that all Line implementations include the new IsPeriodEmptyConsideringTruncations() method. Please:

  • Update the Kafka imports or dependencies to the correct module path (for example, github.com/confluentinc/confluent-kafka-go/v2/kafka) so that pkg/kafka compiles cleanly.
  • Re-run go vet ./... and ensure it passes without errors.
  • Once the build is green, double-check that every concrete Line type, test fake, and mock implements IsPeriodEmptyConsideringTruncations().
🤖 Prompt for AI Agents
In openmeter/billing/service/lineservice/service.go around lines 162 to 165, the
new method IsPeriodEmptyConsideringTruncations() was added to the Line
interface, but go vet fails due to undefined Kafka types in pkg/kafka. First,
fix the Kafka import paths or dependencies in pkg/kafka to point to the correct
module (e.g., github.com/confluentinc/confluent-kafka-go/v2/kafka) so the
package compiles cleanly. Then rerun go vet ./... to confirm no errors remain.
After the build is clean, verify that all concrete Line implementations, test
fakes, and mocks implement the new method IsPeriodEmptyConsideringTruncations()
to satisfy the updated interface.

Comment on lines +119 to +135
return h.billingService.WithLock(ctx, customer.CustomerID{
Namespace: subs.Subscription.Namespace,
ID: subs.Subscription.CustomerId,
}, func(ctx context.Context) error {
plan, err := h.calculateSyncPlan(ctx, subs, asOf)
if err != nil {
return err
}

if plan == nil {
return nil
}
if plan == nil {
return nil
}

patches, err := h.getPatchesFromPlan(plan, subs, currency)
if err != nil {
return nil
}
patches, err := h.getPatchesFromPlan(plan, subs, currency)
if err != nil {
return err
}

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.

🛠️ Refactor suggestion

Lock everything that mutates billing state – move the profile read inside the lock

GetCustomerOverride is executed before WithLock.
If the customer is modified concurrently between the read and the lock, the plan may be built from stale data, defeating the purpose of the lock.

Consider wrapping the profile fetch inside the WithLock closure so that the whole read-plan-apply sequence is atomic.

🤖 Prompt for AI Agents
In openmeter/billing/worker/subscription/sync.go around lines 119 to 135, the
call to GetCustomerOverride happens before acquiring the lock with WithLock,
which risks reading stale customer data if concurrent modifications occur. To
fix this, move the profile fetch (GetCustomerOverride) inside the WithLock
closure so that reading the profile, calculating the plan, and applying patches
all happen atomically within the lock, ensuring consistent and up-to-date
billing state.

@turip
turip merged commit 1705591 into main May 15, 2025
@turip
turip deleted the fix/progressive-billing-related-timing-issues branch May 15, 2025 20:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants