Repository navigation
feat: add extend support for usage-based charges [credit_then_invoice settlement mode] - #4333
Conversation
📝 WalkthroughWalkthroughThis PR implements soft-deletion semantics for realization runs, native extend support for usage-based credit-then-invoice charges, gathering-line patching by charge ID, and consolidates test infrastructure around a new shared BaseSuite. Key changes include adding an ExpandDeletedRealizations flag with required dependency on ExpandRealizations, filtering deleted runs from rating/payment/balance flows, introducing gathering-line update patches, and removing temporary shrink/extend-to-delete-create workarounds. ChangesDeleted Realizations, Extend Support & Gathering-Line Patching
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
89ebcc3 to
074b976
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (5)
openmeter/billing/charges/usagebased/statemachine.go (1)
36-42: ⚡ Quick winConsider making this status check unexportable.
Right now, exporting a mutable slice is a footgun waiting to happen—even though it's only read from currently with
slices.Contains(), any consumer could accidentally mutate it and cause subtle bugs. A quick refactor to a helper function backed by unexported data is safer and clearer:IsMutableFinalRealizationStatus(Status) bool.💡 Suggested refactor
-// MutableFinalRealizationStatuses are the statuses that can have a mutable final invoices, so that -// we can just delete the line without having to be concerned about credit-notes. -var MutableFinalRealizationStatuses = []Status{ - StatusActiveFinalRealizationStarted, - StatusActiveFinalRealizationWaitingForCollection, - StatusActiveFinalRealizationProcessing, -} +// mutableFinalRealizationStatuses are the statuses that can have mutable final invoices. +var mutableFinalRealizationStatuses = map[Status]struct{}{ + StatusActiveFinalRealizationStarted: {}, + StatusActiveFinalRealizationWaitingForCollection: {}, + StatusActiveFinalRealizationProcessing: {}, +} + +func IsMutableFinalRealizationStatus(s Status) bool { + _, ok := mutableFinalRealizationStatuses[s] + return ok +}Then update the call in
creditheninvoice.go:313fromslices.Contains(usagebased.MutableFinalRealizationStatuses, s.Charge.Status)tousagebased.IsMutableFinalRealizationStatus(s.Charge.Status).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/billing/charges/usagebased/statemachine.go` around lines 36 - 42, The exported mutable slice MutableFinalRealizationStatuses is a footgun; replace it with an unexported slice (e.g., mutableFinalRealizationStatuses) and expose a helper IsMutableFinalRealizationStatus(Status) bool that checks membership, then update callers that currently use slices.Contains(usagebased.MutableFinalRealizationStatuses, s.Charge.Status) to call usagebased.IsMutableFinalRealizationStatus(s.Charge.Status) instead; update the slice declaration and the new helper function in statemachine.go and change the call site to use the new helper.openmeter/billing/charges/usagebased/service/lineengine.go (1)
277-289: 💤 Low valueTwo
clock.Now()calls in the same flow — consider sharing one timestamp
AllocateAt(line 280) and thedeletedAtargument tomarkMutableStandardLineRunDeleted(line 286) both callclock.Now()independently. In normal execution they'll differ only by microseconds, but it does mean credit-correction allocation and run deletion can carry slightly different timestamps in the same logical operation, which can be confusing in audit logs and tests. Easy to capture once.♻️ Proposed tweak
+ now := clock.Now() if _, err := e.service.runs.CorrectAllCredits(ctx, usagebasedrun.CorrectAllCreditRealizationsInput{ Charge: charge, Run: run, - AllocateAt: clock.Now(), + AllocateAt: now, CurrencyCalculator: currencyCalculator, }); err != nil { return fmt.Errorf("correcting credits for deleted usage based standard line[%s] run[%s]: %w", stdLine.ID, run.ID.ID, err) } - charge, err = e.markMutableStandardLineRunDeleted(ctx, charge, run, clock.Now()) + charge, err = e.markMutableStandardLineRunDeleted(ctx, charge, run, now)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/billing/charges/usagebased/service/lineengine.go` around lines 277 - 289, Capture a single timestamp once before calling e.service.runs.CorrectAllCredits and reuse it for both the CorrectAllCreditRealizationsInput.AllocateAt and the deletedAt argument passed to markMutableStandardLineRunDeleted so both operations share the exact same time; specifically, call clock.Now() into a local variable (e.g., now) and pass that variable to usagebasedrun.CorrectAllCreditRealizationsInput.AllocateAt and to markMutableStandardLineRunDeleted instead of calling clock.Now() twice.openmeter/billing/charges/invoiceupdater/invoiceupdate.go (1)
43-49: ⚡ Quick winAvoid a second full gathering-invoice scan here.
With this extra resolver, a patch batch that contains both delete-by-charge and update-by-charge work now does two back-to-back
ListGatheringInvoices(...ExpandLines)passes over the same customer data. On a billing DB path, I’d strongly prefer resolving both maps in one fetch / one walk.As per coding guidelines, "Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) should be vetted for potential performance bottlenecks."
Also applies to: 341-350
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/billing/charges/invoiceupdater/invoiceupdate.go` around lines 43 - 49, The two sequential calls to resolveGatheringLineDeletesByChargeID and resolveGatheringLineUpdatesByChargeID trigger two separate ListGatheringInvoices(...ExpandLines) scans; combine them into a single resolver that fetches gathering invoices once and applies both delete-by-charge and update-by-charge logic in one walk (e.g., create resolveGatheringLineDeletesAndUpdatesByChargeID or merge logic into resolveGatheringLineByChargeID) and replace the two calls with that single call; ensure the new function accepts the same ctx, customerID and patchesParsed (or both maps) and performs both maps' resolutions while iterating each invoice/line exactly once.test/credits/credit_then_invoice_test.go (1)
820-1233: ⚡ Quick winAdd one test for the post-issuing rejection boundary.
Nice coverage on the mutable-line and
active.awaiting_payment_settlementextend paths. What’s still missing is the explicit failure case once the run has already reachedactive.final_realization.issuingoractive.final_realization.completed. That boundary is the key guardrail that keeps sync from rewriting invoice-owned state, so a small negative test here would make this feature a lot safer.As per coding guidelines
**/*_test.go: Make sure the tests are comprehensive and cover the changes.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/credits/credit_then_invoice_test.go` around lines 820 - 1233, Add a negative test that verifies extend patches are rejected once a final run has reached the immutable issuing/completed boundary: implement a new test (e.g. TestUsageBasedCreditThenInvoiceExtendDuringIssuingOrCompletedRejectsExtend) modeled after the existing TestUsageBasedCreditThenInvoiceExtendPatchDuringAwaitingPaymentSettlement and TestUsageBasedCreditThenInvoiceExtendPatchDuringFinalRunCollectionKeepsAdvanceNoop; set up a final invoice and drive it to usagebased.StatusActiveFinalRealizationIssuing and/or usagebased.StatusActiveFinalRealizationCompleted (use BillingService.AdvanceInvoice/ApproveInvoice and RequireUsageBasedChargeStatus to reach those states), call mustExtendCharge with the extended end and assert the extend is rejected (expect an error or no-op per intended contract), then fetch the invoice and charge (GetInvoiceById, mustGetUsageBasedChargeByIDWithExpands) and assert the invoice line/run remain immutable (line not deleted, run.Type still final, run.DeletedAt nil), and assert ledger snapshot/booking unchanged using CreateLedgerSnapshot and AssertLedgerSnapshotUnchanged to ensure no ledger bookings were rewritten.openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go (1)
25-115: 💤 Low valueConsider adding error path tests (optional).
The happy path coverage is solid! As a nice-to-have enhancement, you could add tests for error scenarios like:
newUsageBasedChargeIntentwhen price is nilAddExtendwhen the existing item isn't aUsageBasedChargeGetterThese might be covered elsewhere or not critical for this PR scope, but they'd round out the test suite.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go` around lines 25 - 115, Add negative-path tests to cover creation and type-mismatch errors: write a test that calls newUsageBasedChargeIntent with a target whose Price is nil and asserts it returns the expected error, and write a test that calls collection.AddExtend with an existing persistedstate.Item that does not implement UsageBasedChargeGetter and asserts it returns the appropriate type error; place these tests alongside the existing ones (referencing newUsageBasedChargeIntent and AddExtend on the usage-based collection and the UsageBasedChargeGetter interface) so failures are exercised and asserted explicitly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In @.agents/skills/subscriptionsync/SKILL.md:
- Around line 145-149: Update the later "charge-semantics" bullet that still
claims the charge path "currently only create is supported" to reflect the new
behavior described in the "Charge-backed mutation notes": state that create and
delete plus period-shape changes are supported, that shrink and most extends are
emulated as delete+create, that usage-based `credit_then_invoice` extend is
emitted as a native charge patch, and that explicit prorate remains unsupported;
locate the copy mentioning "only create is supported" and replace it with a
concise summary matching the new notes.
In `@openmeter/billing/charges/invoiceupdater/invoiceupdate.go`:
- Around line 363-364: The patch updates line.ServicePeriod.To and
line.InvoiceAt but forgets to propagate the new end to subscription-backed
lines; update the same block in invoiceupdate.go to also set
line.Subscription.BillingPeriod.To = updatePatch.ServicePeriodTo (and if
present, line.Intent.BillingPeriod.To is already updated elsewhere, so ensure
the subscription's BillingPeriod.To mirrors updatePatch.ServicePeriodTo) so
subscription-backed gathering lines and functions like isCurrentBillingPeriod()
see the new range.
---
Nitpick comments:
In `@openmeter/billing/charges/invoiceupdater/invoiceupdate.go`:
- Around line 43-49: The two sequential calls to
resolveGatheringLineDeletesByChargeID and resolveGatheringLineUpdatesByChargeID
trigger two separate ListGatheringInvoices(...ExpandLines) scans; combine them
into a single resolver that fetches gathering invoices once and applies both
delete-by-charge and update-by-charge logic in one walk (e.g., create
resolveGatheringLineDeletesAndUpdatesByChargeID or merge logic into
resolveGatheringLineByChargeID) and replace the two calls with that single call;
ensure the new function accepts the same ctx, customerID and patchesParsed (or
both maps) and performs both maps' resolutions while iterating each invoice/line
exactly once.
In `@openmeter/billing/charges/usagebased/service/lineengine.go`:
- Around line 277-289: Capture a single timestamp once before calling
e.service.runs.CorrectAllCredits and reuse it for both the
CorrectAllCreditRealizationsInput.AllocateAt and the deletedAt argument passed
to markMutableStandardLineRunDeleted so both operations share the exact same
time; specifically, call clock.Now() into a local variable (e.g., now) and pass
that variable to usagebasedrun.CorrectAllCreditRealizationsInput.AllocateAt and
to markMutableStandardLineRunDeleted instead of calling clock.Now() twice.
In `@openmeter/billing/charges/usagebased/statemachine.go`:
- Around line 36-42: The exported mutable slice MutableFinalRealizationStatuses
is a footgun; replace it with an unexported slice (e.g.,
mutableFinalRealizationStatuses) and expose a helper
IsMutableFinalRealizationStatus(Status) bool that checks membership, then update
callers that currently use
slices.Contains(usagebased.MutableFinalRealizationStatuses, s.Charge.Status) to
call usagebased.IsMutableFinalRealizationStatus(s.Charge.Status) instead; update
the slice declaration and the new helper function in statemachine.go and change
the call site to use the new helper.
In
`@openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go`:
- Around line 25-115: Add negative-path tests to cover creation and
type-mismatch errors: write a test that calls newUsageBasedChargeIntent with a
target whose Price is nil and asserts it returns the expected error, and write a
test that calls collection.AddExtend with an existing persistedstate.Item that
does not implement UsageBasedChargeGetter and asserts it returns the appropriate
type error; place these tests alongside the existing ones (referencing
newUsageBasedChargeIntent and AddExtend on the usage-based collection and the
UsageBasedChargeGetter interface) so failures are exercised and asserted
explicitly.
In `@test/credits/credit_then_invoice_test.go`:
- Around line 820-1233: Add a negative test that verifies extend patches are
rejected once a final run has reached the immutable issuing/completed boundary:
implement a new test (e.g.
TestUsageBasedCreditThenInvoiceExtendDuringIssuingOrCompletedRejectsExtend)
modeled after the existing
TestUsageBasedCreditThenInvoiceExtendPatchDuringAwaitingPaymentSettlement and
TestUsageBasedCreditThenInvoiceExtendPatchDuringFinalRunCollectionKeepsAdvanceNoop;
set up a final invoice and drive it to
usagebased.StatusActiveFinalRealizationIssuing and/or
usagebased.StatusActiveFinalRealizationCompleted (use
BillingService.AdvanceInvoice/ApproveInvoice and RequireUsageBasedChargeStatus
to reach those states), call mustExtendCharge with the extended end and assert
the extend is rejected (expect an error or no-op per intended contract), then
fetch the invoice and charge (GetInvoiceById,
mustGetUsageBasedChargeByIDWithExpands) and assert the invoice line/run remain
immutable (line not deleted, run.Type still final, run.DeletedAt nil), and
assert ledger snapshot/booking unchanged using CreateLedgerSnapshot and
AssertLedgerSnapshotUnchanged to ensure no ledger bookings were rewritten.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: b8534cad-8bcf-484d-af78-eeec21538a81
⛔ Files ignored due to path filters (2)
openmeter/ent/db/chargeusagebasedruns_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns_update.gois excluded by!**/ent/db/**
📒 Files selected for processing (38)
.agents/skills/charges/SKILL.md.agents/skills/subscriptionsync/SKILL.mdopenmeter/billing/charges/flatfee/adapter.goopenmeter/billing/charges/invoiceupdater/invoiceupdate.goopenmeter/billing/charges/invoiceupdater/patch.goopenmeter/billing/charges/meta/charge.goopenmeter/billing/charges/meta/patchextend.goopenmeter/billing/charges/meta/patchextend_test.goopenmeter/billing/charges/service/patch.goopenmeter/billing/charges/service/patchtmp.goopenmeter/billing/charges/service/truncation_test.goopenmeter/billing/charges/usagebased/adapter/charge.goopenmeter/billing/charges/usagebased/adapter/realizationrun.goopenmeter/billing/charges/usagebased/realizationrun.goopenmeter/billing/charges/usagebased/realizationrun_test.goopenmeter/billing/charges/usagebased/service.goopenmeter/billing/charges/usagebased/service/create.goopenmeter/billing/charges/usagebased/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/creditheninvoice_test.goopenmeter/billing/charges/usagebased/service/lineengine.goopenmeter/billing/charges/usagebased/service/payments.goopenmeter/billing/charges/usagebased/service/rating/details.goopenmeter/billing/charges/usagebased/service_test.goopenmeter/billing/charges/usagebased/statemachine.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.goopenmeter/ent/schema/chargesusagebased.goopenmeter/ledger/customerbalance/calculation.gotest/billing/suite.gotest/credits/base.gotest/credits/credit_then_invoice_test.gotest/credits/creditgrant_test.gotest/credits/rating_test.gotest/credits/sanity_lifecycle_test.gotest/credits/sanity_test.gotest/credits/suite_test.go
💤 Files with no reviewable changes (4)
- openmeter/billing/charges/service/patch.go
- openmeter/billing/charges/service/truncation_test.go
- test/credits/suite_test.go
- openmeter/billing/charges/service/patchtmp.go
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@openmeter/billing/charges/usagebased/service/lineengine.go`:
- Around line 254-258: The error message returned when run.DeletedAt != nil is
misleading because we're in OnMutableStandardLinesDeleted and the line has
already been deleted; change the returned fmt.Errorf in that conditional (the
block referencing run.DeletedAt, stdLine.ID and run.ID.ID) to clearly state that
the realization run is already deleted and therefore the cleanup path should be
skipped (e.g. "realization run[%s] already deleted; skip cleanup for standard
line[%s]") so it no longer implies the line cannot be deleted.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: b32db00e-d940-432b-b23d-6a854794e53b
📒 Files selected for processing (8)
.agents/skills/subscriptionsync/SKILL.mdopenmeter/billing/charges/invoiceupdater/invoiceupdate.goopenmeter/billing/charges/usagebased/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/creditheninvoice_test.goopenmeter/billing/charges/usagebased/service/lineengine.goopenmeter/billing/charges/usagebased/statemachine.goopenmeter/billing/worker/subscriptionsync/service/creditsonly_test.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go
✅ Files skipped from review due to trivial changes (1)
- .agents/skills/subscriptionsync/SKILL.md
🚧 Files skipped from review as they are similar to previous changes (3)
- openmeter/billing/charges/invoiceupdater/invoiceupdate.go
- openmeter/billing/charges/usagebased/service/creditheninvoice.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go
Overview
Add support for extend for usage-based credit_then_invoice settlement mode.
To support credit_then_invoice subscriptions we still need:
Notes for reviewer
Summary by CodeRabbit
Documentation
New Features
Bug Fixes
Tests