Skip to content

fix: interim payment errors for progressively billed usage-based items - #4665

Merged
turip merged 2 commits into
mainfrom
feat/usagebased-paid-trigger-cleanup
Jul 8, 2026
Merged

turip merged 2 commits into
mainfrom
feat/usagebased-paid-trigger-cleanup

Conversation

@turip

@turip turip commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

Summary

  • fix progressively billed usage-based items so:
    • fully credited interim invoices do not remain waiting for fiat payment settlement
    • progressively billed lines with interim payments do not fail due to not being able to tirgger payment
  • move charge finalization after payment recording back onto the normal guarded TriggerNext advancement path
  • remove the dedicated all_payments_settled trigger now that flat-fee and usage-based settlement both use normal charge advancement

Why

Progressively billed usage-based items can produce interim invoice lines that are fully covered by credits and do not require a fiat payment transaction. Those lines were able to leave the charge waiting for payment settlement even though there was no payment to settle, which could surface as payment-processing errors for interim invoices.

The charge state machine already has the correct guarded advancement rules. This change records the line payment state first, then lets the standard advancement loop settle the charge into the correct final state when all invoiced usage is settled or no fiat transaction is required.

Validation

  • go test -tags=dynamic -count=1 ./openmeter/billing/charges/flatfee/service
  • go test -tags=dynamic -count=1 ./openmeter/billing/charges/usagebased/service
  • env POSTGRES_HOST=127.0.0.1 go test -tags=dynamic -count=1 ./openmeter/billing/charges/service -run 'TestInvoicable|TestUsageBased'
  • env POSTGRES_HOST=127.0.0.1 go test -tags=dynamic -count=1 ./test/credits
  • make test-nocache

Summary by CodeRabbit

  • Bug Fixes

    • Charging flows now progress to the final state more reliably after payments are settled.
    • Invoice and credit-then-invoice scenarios now complete as final instead of lingering in an awaiting-settlement state.
  • Tests

    • Updated coverage to reflect the new finalization behavior across multiple billing scenarios.
    • Adjusted test case names and expectations to match the updated charge lifecycle.

Greptile Summary

This PR updates payment settlement for credit-then-invoice charges. The main changes are:

  • Replaces the dedicated all_payments_settled trigger with guarded TriggerNext advancement.
  • Finalizes fully credited usage-based invoice runs without waiting for a fiat payment.
  • Applies the same normal advancement path to flat-fee payment settlement.
  • Updates billing and credit integration tests for the new final charge state.

Confidence Score: 5/5

This looks safe to merge.

  • No blocking issues found in the changed code.

Important Files Changed

Filename Overview
openmeter/billing/charges/usagebased/service/payments.go Records usage-based payment settlement and then resumes normal charge advancement.
openmeter/billing/charges/usagebased/service/creditheninvoice.go Moves awaiting-payment-settlement finalization onto the guarded TriggerNext transition.
openmeter/billing/charges/flatfee/service/lineengine.go Uses normal state-machine advancement after flat-fee payment settlement.
openmeter/billing/charges/flatfee/service/creditheninvoice.go Removes the dedicated settlement trigger from the flat-fee finalization state.
openmeter/billing/charges/meta/triggers.go Removes the unused all_payments_settled trigger constant.
openmeter/billing/charges/service/invoicable_test.go Updates the fully credited usage-based invoice expectation to final.
test/credits/credit_then_invoice_test.go Updates credit-then-invoice integration expectations for no-fiat final invoices.

Reviews (2): Last reviewed commit: "test(billing): expect no-fiat usage char..." | Re-trigger Greptile

Context used (3)

  • Context used - CLAUDE.md (source)
  • Context used - AGENTS.md (source)
  • Context used - api/spec/AGENTS.md (source)

@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR removes the shared TriggerAllPaymentsSettled trigger and switches flatfee and usagebased settlement flows to advance state machines with TriggerNext and AdvanceUntilStateStable. Related credit-then-invoice tests now expect the final charge state.

Changes

Payment settlement state advancement

Layer / File(s) Summary
Remove shared trigger constant
openmeter/billing/charges/meta/triggers.go
Deletes the exported TriggerAllPaymentsSettled trigger constant from the meta triggers list.
Flatfee state machine & handler
openmeter/billing/charges/flatfee/service/creditheninvoice.go, openmeter/billing/charges/flatfee/service/lineengine.go
Switches the final-state Permit transition to meta.TriggerNext, and updates OnPaymentSettled to call AdvanceUntilStateStable after refetching, dropping the old trigger-firing path.
Usagebased state machine & handler
openmeter/billing/charges/usagebased/service/creditheninvoice.go, openmeter/billing/charges/usagebased/service/payments.go
Switches the final-state Permit transition to meta.TriggerNext, removes the unused meta import, and updates recordPaymentSettled to always create a patched state machine and call AdvanceUntilStateStable, removing the prior gated trigger flow.
Test expectation updates
openmeter/billing/charges/service/invoicable_test.go, test/credits/credit_then_invoice_test.go
Updates final-state assertions across invoicable and credit-then-invoice scenarios to expect StatusFinal, and renames the affected credit-then-invoice scenarios to match the no-fiat final-invoice path.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant LineEngine
  participant Charge
  participant StateMachine

  LineEngine->>Charge: RefetchCharge / update realization run
  LineEngine->>StateMachine: AdvanceUntilStateStable
  StateMachine->>StateMachine: Permit TriggerNext -> StatusFinal
Loading

Possibly related PRs

  • openmeterio/openmeter#4145: Introduced the shared AdvanceUntilStateStable state-machine path that this PR now uses instead of the removed trigger.
  • openmeterio/openmeter#4351: Touches the same credit-then-invoice settlement flow and the awaiting-payment-settlement transitions.

Suggested reviewers: tothandras

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title matches the main fix: preventing interim payment errors and allowing progressively billed usage-based items to finalize correctly.
✨ 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 feat/usagebased-paid-trigger-cleanup

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.

@turip
turip marked this pull request as ready for review July 8, 2026 10:13
@turip
turip requested a review from a team as a code owner July 8, 2026 10:13
@turip

turip commented Jul 8, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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/payments.go`:
- Around line 103-109: The payment-settled advancement in payments.go is too
broad because AdvanceUntilStateStable on advancementStateMachine can fire
non-settlement TriggerNext transitions as well. Add a status guard around the
generic advancement path in the payment-settlement callback so it only runs when
the charge is in the settlement state, keeping the state machine advancement
focused on settlement finalization and avoiding unintended lifecycle moves for
older or parallel lines.
🪄 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: 144790c1-5213-4eb6-9791-ff3bffc43c9a

📥 Commits

Reviewing files that changed from the base of the PR and between 822c369 and 6e98211.

📒 Files selected for processing (6)
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/meta/triggers.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/payments.go
💤 Files with no reviewable changes (2)
  • openmeter/billing/charges/meta/triggers.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go

@turip turip changed the title Use normal advancement for charge payment settlement Fix interim payment errors for progressively billed usage-based items Jul 8, 2026
@turip turip changed the title Fix interim payment errors for progressively billed usage-based items fix: interim payment errors for progressively billed usage-based items Jul 8, 2026
@turip turip added release-note/bug-fix Release note: Bug Fixes and removed release-note/bugfix labels Jul 8, 2026

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
test/credits/credit_then_invoice_test.go (2)

4219-4221: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Stale "given" comment contradicts the updated assertion.

The given comment says "the charge is awaiting payment settlement," but line 4204 now asserts usagebased.StatusFinal. This comment should reflect the finalized state.

📝 Suggested comment update
 	s.Run("when the charge shrink patch targets the immutable invoice period", func() {
 		// given:
-		// - the invoice line is immutable and the charge is awaiting payment settlement
+		// - the invoice line is immutable and the charge is finalized without fiat payment
🤖 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 4219 - 4221, The
scenario setup comment in the `s.Run("when the charge shrink patch targets the
immutable invoice period", ...)` test is stale and no longer matches the
assertion state. Update the `given` comment near the immutable invoice period
setup so it reflects that the charge is finalized (`usagebased.StatusFinal`)
instead of saying it is awaiting payment settlement, keeping the test narrative
aligned with the actual setup.

4608-4615: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Stale subtest name and "then" comment contradict the updated assertion.

The subtest is named "given a final standard invoice line awaiting payment settlement" and the then comment says "the charge is waiting for payment settlement," but line 4683 now asserts usagebased.StatusFinal. These should be updated to match the new no-fiat finalization behavior.

📝 Suggested comment updates
-	s.Run("given a final standard invoice line awaiting payment settlement", func() {
+	s.Run("given a final standard invoice line after no-fiat finalization", func() {
 		// given:
 		// - a ledger-backed customer has enough credits to cover usage
 		// - usage is visible inside the original service period
 		// when:
 		// - the standard invoice is collected and approved
 		// then:
-		// - the final run has invoice usage booked and the charge is waiting for payment settlement
+		// - the final run has invoice usage booked and the charge is finalized without fiat payment
🤖 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 4608 - 4615, The
subtest name and the trailing “then” comment in the credits finalization test no
longer match the actual assertion in this scenario. Update the test description
around the subtest in credit_then_invoice_test.go to reflect the new no-fiat
finalization behavior and align it with the `usagebased.StatusFinal` assertion
in the final run, so the name and comments describe that the usage-based charge
is finalized rather than waiting for payment settlement.
🤖 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.

Outside diff comments:
In `@test/credits/credit_then_invoice_test.go`:
- Around line 4219-4221: The scenario setup comment in the `s.Run("when the
charge shrink patch targets the immutable invoice period", ...)` test is stale
and no longer matches the assertion state. Update the `given` comment near the
immutable invoice period setup so it reflects that the charge is finalized
(`usagebased.StatusFinal`) instead of saying it is awaiting payment settlement,
keeping the test narrative aligned with the actual setup.
- Around line 4608-4615: The subtest name and the trailing “then” comment in the
credits finalization test no longer match the actual assertion in this scenario.
Update the test description around the subtest in credit_then_invoice_test.go to
reflect the new no-fiat finalization behavior and align it with the
`usagebased.StatusFinal` assertion in the final run, so the name and comments
describe that the usage-based charge is finalized rather than waiting for
payment settlement.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7d3a4627-5d8a-41c4-ae71-7562540878ea

📥 Commits

Reviewing files that changed from the base of the PR and between 6e98211 and b746d1f.

📒 Files selected for processing (1)
  • test/credits/credit_then_invoice_test.go

@turip
turip merged commit 967ff27 into main Jul 8, 2026
26 checks passed
@turip
turip deleted the feat/usagebased-paid-trigger-cleanup branch July 8, 2026 10:58
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