Skip to content

feat: add extend support for usage-based charges [credit_then_invoice settlement mode] - #4333

Merged
turip merged 4 commits into
mainfrom
chore/cerdit-then-invoice-extend
May 10, 2026
Merged

turip merged 4 commits into
mainfrom
chore/cerdit-then-invoice-extend

Conversation

@turip

@turip turip commented May 10, 2026 •

Copy link
Copy Markdown
Member

Overview

Add support for extend for usage-based credit_then_invoice settlement mode.

To support credit_then_invoice subscriptions we still need:

  • usagebased shrink
  • flat fee extend/shrink

Notes for reviewer

Summary by CodeRabbit

  • Documentation

    • Clarified charge and subscription sync docs: usage-based extension rules, deleted-realization handling, and charge-backed mutation semantics.
  • New Features

    • Native support for extending service periods on credit-then-invoice usage charges with correct reclassification and invoice adjustments.
    • Gathering-line updates can now be targeted by charge ID for pending invoice adjustments.
  • Bug Fixes

    • Deleted realizations are excluded from billing/credit calculations and expansions unless explicitly requested.
    • Expanded validation for dependent expansion options.
  • Tests

    • Added and reorganized test suites covering extend/delete behaviors and reconciliation paths.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 10, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This 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.

Changes

Deleted Realizations, Extend Support & Gathering-Line Patching

Layer / File(s) Summary
Expansion Model & Validation
openmeter/billing/charges/meta/charge.go, openmeter/billing/charges/flatfee/adapter.go, openmeter/billing/charges/usagebased/service.go, openmeter/billing/charges/usagebased/service_test.go
Add ExpandDeletedRealizations constant and enforce dependency: callers must request ExpandRealizations when they want deleted realizations; validation fails if only ExpandDeletedRealizations is provided.
Realization Run Schema & Mutations
openmeter/ent/schema/chargesusagebased.go, openmeter/billing/charges/usagebased/realizationrun.go, openmeter/billing/charges/usagebased/adapter/realizationrun.go, openmeter/billing/charges/usagebased/realizationrun_test.go
Remove Immutable() constraint from realization run type field; add Type field to UpdateRealizationRunInput; filter deleted realizations (DeletedAt != nil) from billing-metered-quantity calculations.
Gathering-Line Patch Operations
openmeter/billing/charges/invoiceupdater/patch.go, openmeter/billing/charges/invoiceupdater/invoiceupdate.go
Add PatchOpUpdateGatheringLineByChargeID operation to update gathering lines by charge ID with new ServicePeriodTo; implement resolveGatheringLineUpdatesByChargeID to convert and apply updates to generic invoice lines.
PatchExtend Validation
openmeter/billing/charges/meta/patchextend.go, openmeter/billing/charges/meta/patchextend_test.go
Tighten NewServicePeriodTo validation to require strict "after" (not equal); add comprehensive unit tests for extend-patch validation scenarios.
Usage-Based Extend & Final-Run Handling
openmeter/billing/charges/usagebased/statemachine.go, openmeter/billing/charges/usagebased/service/creditheninvoice.go, openmeter/billing/charges/usagebased/service/creditheninvoice_test.go
Add helper to identify mutable final-realization statuses; implement ExtendCharge method to handle native extend (including reclassification of final runs); add UnsupportedExtendOperation to reject extends on immutable final realizations owned by invoice callbacks.
Deleted-Run Filtering Across Services
openmeter/billing/charges/usagebased/adapter/charge.go, openmeter/billing/charges/usagebased/service/rating/details.go, openmeter/billing/charges/usagebased/service/payments.go, openmeter/billing/charges/usagebased/service/lineengine.go, openmeter/ledger/customerbalance/calculation.go
Filter deleted realizations from realization expansion, detailed-rating eligibility, payment-settlement checks, mutable-line deletion validation, and realized-credit calculations; skip deleted runs in line-engine state updates.
Usage-Based Charge Creation Refactoring
openmeter/billing/charges/usagebased/service/create.go
Refactor gathering-line construction to accept explicit service-period and invoice-at parameters; split into period-aware helper for flexibility.
Temporary Workaround Removal
openmeter/billing/charges/service/patch.go, openmeter/billing/charges/service/patchtmp.go, openmeter/billing/charges/service/truncation_test.go
Delete temporary shrink/extend-to-delete-create mapping helpers; remove calls and related test coverage.
Reconciler Charge Mutations
openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go, openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go, openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go, openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go
Implement proper emulated-replacement pattern (delete+create) for flat-fee and usage-based shrink/extend; add native extend-patching for credit-then-invoice settlement mode; include comprehensive tests for all mutation scenarios and charge types.
InvoiceUpdater Integration
openmeter/billing/charges/invoiceupdater/invoiceupdate.go
Integrate resolving of gathering-line updates by charge ID into ApplyPatches flow and propagate contextual errors.
Line-Engine & Charge State Updates
openmeter/billing/charges/usagebased/service/lineengine.go
Refine mutable-standard-line deletion behavior: reject double-deletion attempts, recompute charge.State.AdvanceAfter after deletions, and deduplicate charge ID lists before fetching.
Balance/Payments/Rating Adjustments
openmeter/ledger/customerbalance/calculation.go, openmeter/billing/charges/usagebased/service/payments.go, openmeter/billing/charges/usagebased/service/rating/details.go
Ignore deleted realizations when computing realized credits, checking invoiced-run settlement, and determining eligibility/requirements for detailed-rating lines.
Ent Schema Change
openmeter/ent/schema/chargesusagebased.go
Remove Immutable() constraint from ChargeUsageBasedRuns.type field to allow updating run Type.
Test Infrastructure: BaseSuite
test/billing/suite.go, test/credits/base.go
Introduce shared BaseSuite test harness with ledger initialization, balance-querying helpers, charge-intent constructors, ledger-snapshot utilities, and revenue-recognition support.
Test Refactoring: CreditThenInvoiceTestSuite
test/credits/credit_then_invoice_test.go
Rewrite credit-then-invoice test suite to use BaseSuite and ledger-snapshot pattern; add comprehensive delete/extend scenarios for pending gathering lines, mutable standard invoice lines, and immutable standard invoice lines.
Test Refactoring: Suite Migrations
test/credits/creditgrant_test.go, test/credits/rating_test.go, test/credits/sanity_lifecycle_test.go, test/credits/sanity_test.go, test/credits/suite_test.go
Migrate multiple suites to embed BaseSuite; remove old CreditsTestSuite harness; update tests to use exported BaseSuite helpers and constructors.
Documentation
.agents/skills/charges/SKILL.md, .agents/skills/subscriptionsync/SKILL.md
Clarify deleted-realization filtering rules, native extend support for credit-then-invoice, and emulated-replacement semantics for charge-backed period mutations.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Suggested reviewers

  • tothandras
  • GAlexIHU
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main feature addition: extend support for usage-based charges in credit_then_invoice settlement mode, which is the core objective reflected throughout the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/cerdit-then-invoice-extend

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

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@turip turip changed the title Chore/cerdit then invoice extend feat: add extend support for usage-based charges [credit_then_invoice settlement mode] May 10, 2026
@turip turip added release-note/feature Release note: Exciting New Features area/billing labels May 10, 2026
@turip
turip force-pushed the chore/cerdit-then-invoice-extend branch from 89ebcc3 to 074b976 Compare May 10, 2026 16:53
@turip
turip marked this pull request as ready for review May 10, 2026 16:55
@turip
turip requested a review from a team as a code owner May 10, 2026 16:55

@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

🧹 Nitpick comments (5)
openmeter/billing/charges/usagebased/statemachine.go (1)

36-42: ⚡ Quick win

Consider 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:313 from slices.Contains(usagebased.MutableFinalRealizationStatuses, s.Charge.Status) to usagebased.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 value

Two clock.Now() calls in the same flow — consider sharing one timestamp

AllocateAt (line 280) and the deletedAt argument to markMutableStandardLineRunDeleted (line 286) both call clock.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 win

Avoid 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 win

Add one test for the post-issuing rejection boundary.

Nice coverage on the mutable-line and active.awaiting_payment_settlement extend paths. What’s still missing is the explicit failure case once the run has already reached active.final_realization.issuing or active.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 value

Consider 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:

  • newUsageBasedChargeIntent when price is nil
  • AddExtend when the existing item isn't a UsageBasedChargeGetter

These 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

📥 Commits

Reviewing files that changed from the base of the PR and between b2e7c9d and 074b976.

⛔ Files ignored due to path filters (2)
  • openmeter/ent/db/chargeusagebasedruns_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns_update.go is excluded by !**/ent/db/**
📒 Files selected for processing (38)
  • .agents/skills/charges/SKILL.md
  • .agents/skills/subscriptionsync/SKILL.md
  • openmeter/billing/charges/flatfee/adapter.go
  • openmeter/billing/charges/invoiceupdater/invoiceupdate.go
  • openmeter/billing/charges/invoiceupdater/patch.go
  • openmeter/billing/charges/meta/charge.go
  • openmeter/billing/charges/meta/patchextend.go
  • openmeter/billing/charges/meta/patchextend_test.go
  • openmeter/billing/charges/service/patch.go
  • openmeter/billing/charges/service/patchtmp.go
  • openmeter/billing/charges/service/truncation_test.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/realizationrun.go
  • openmeter/billing/charges/usagebased/realizationrun.go
  • openmeter/billing/charges/usagebased/realizationrun_test.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/service/create.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice_test.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/usagebased/service/payments.go
  • openmeter/billing/charges/usagebased/service/rating/details.go
  • openmeter/billing/charges/usagebased/service_test.go
  • openmeter/billing/charges/usagebased/statemachine.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go
  • openmeter/ent/schema/chargesusagebased.go
  • openmeter/ledger/customerbalance/calculation.go
  • test/billing/suite.go
  • test/credits/base.go
  • test/credits/credit_then_invoice_test.go
  • test/credits/creditgrant_test.go
  • test/credits/rating_test.go
  • test/credits/sanity_lifecycle_test.go
  • test/credits/sanity_test.go
  • test/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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 074b976 and cb61b25.

📒 Files selected for processing (8)
  • .agents/skills/subscriptionsync/SKILL.md
  • openmeter/billing/charges/invoiceupdater/invoiceupdate.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice_test.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/usagebased/statemachine.go
  • openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go
  • openmeter/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

@turip
turip merged commit 45e1532 into main May 10, 2026
42 of 43 checks passed
@turip
turip deleted the chore/cerdit-then-invoice-extend branch May 10, 2026 18:06

This branch was previously deployed

1 inactive deployment
dev — cb61b25e Deployed May 10, 2026 by turip via Migration Checks #14237
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants