Skip to content

fix(billing): support credit-only period patches - #4597

Merged
turip merged 3 commits into
mainfrom
fix/credits-only-patch-extend
Jun 29, 2026
Merged

turip merged 3 commits into
mainfrom
fix/credits-only-patch-extend

Conversation

@turip

@turip turip commented Jun 29, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Support direct shrink/extend patch reconciliation for credit-only flat-fee and usage-based charges.
  • Move targeted credit-only period patches away from emulated replacement behavior.
  • For credit-only usage-based patches, void existing realization runs, persist the charge back to active, and advance from the patched service-period end.

Validation

  • env POSTGRES_HOST=127.0.0.1 go test -count=1 -tags=dynamic ./pkg/statelessx ./openmeter/billing/charges/meta ./openmeter/billing/charges/flatfee/... ./openmeter/billing/charges/usagebased/... ./openmeter/billing/worker/subscriptionsync/service/...
  • nix develop --impure .#ci -c make lint-go-fast

Summary by CodeRabbit

  • New Features
    • Expanded end-user support for extending and shrinking credit-only charges across additional lifecycle statuses.
    • Charge period updates now more consistently propagate to related service, billing, and invoice timing.
  • Bug Fixes
    • Credit allocations now reconcile against existing credit runs rather than creating new ones unnecessarily.
    • Period-change events for credit-only settlement now emit native shrink/extend patches.
    • Mid-period cancellations preserve the remaining charge identity and align post-cancellation state expectations.
  • Tests
    • Added and updated test coverage for period patching, final-realization boundaries, and native patch emission.

@turip
turip requested a review from a team as a code owner June 29, 2026 08:56
@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 88d27a9f-a411-4d58-8c84-386f6a1b2aa7

📥 Commits

Reviewing files that changed from the base of the PR and between a2111af and d2ae57a.

📒 Files selected for processing (1)
  • pkg/statelessx/actions.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/statelessx/actions.go

📝 Walkthrough

Walkthrough

Adds native Extend/Shrink handling for credits-only flat-fee and usage-based charges, wires the triggers into their state machines, removes emulated-replacement fallback paths in the reconciler, and updates tests to assert the new patch and cancellation behavior.

Changes

Native Extend/Shrink for credits-only charges

Layer / File(s) Summary
Shared patch/action utilities
openmeter/billing/charges/meta/patch.go, pkg/statelessx/actions.go
Adds PatchAction[T] and AllOfWithParameters[T] helpers used by the new trigger wiring.
Flat-fee credits-only state machine
openmeter/billing/charges/flatfee/service/creditsonly.go
Wires extend/shrink triggers, adds period patching with proration recalculation, and reconciles existing credit realizations when a run already exists.
Usage-based credits-only state machine
openmeter/billing/charges/usagebased/service/creditsonly.go, openmeter/billing/charges/usagebased/service/creditheninvoice.go
Wires extend/shrink triggers across lifecycle states, adds period-patch handlers with run voiding and persistence, and renames the internal apply-period result type.
Reconciler: emit native credit-only patches
openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go, openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go
Removes settlement-mode-based emulated replacement paths so shrink/extend always emit native patches.
Usage-based credits-only tests
openmeter/billing/charges/usagebased/service/creditsonly_test.go
Adds tests for trigger availability and extend/shrink behavior across created and final-realization states, with in-memory persistence helpers.
Reconciler and cancellation tests
openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go, openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go
Updates patch-emission assertions and mid-period cancellation expectations for flat-fee and usage-based charges.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 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 4.17% 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 clearly matches the main change: billing support for credit-only period patches.
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.
✨ 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 fix/credits-only-patch-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.

@greptile-apps

greptile-apps Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds native period patching for credit-only billing charges. The main changes are:

  • Flat-fee credit-only charges now handle shrink and extend patches directly.
  • Usage-based credit-only charges now void existing realization runs before continuing from the updated period end.
  • Subscription sync now emits native shrink and extend patches instead of delete-and-recreate replacements.
  • Tests now cover credit-only patch emission, cancellation behavior, and usage-based realization 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/worker/subscriptionsync/service/reconciler/patchcharge_test.go The reconciler tests now expect native credit-only patch emission and use flat-fee intent helpers for flat-fee fixtures.
openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go Flat-fee shrink and extend reconciliation now emits native period patches.
openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go Usage-based shrink and extend reconciliation now emits native period patches.
openmeter/billing/charges/flatfee/service/creditsonly.go Credit-only flat-fee state handling now accepts period patches and reconciles existing credit realizations.
openmeter/billing/charges/usagebased/service/creditsonly.go Credit-only usage-based state handling now accepts period patches, voids existing runs, and returns the charge to active state.

Reviews (3): Last reviewed commit: "fix: lint import grouping" | Re-trigger Greptile

@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 (4)
openmeter/billing/charges/usagebased/service/creditsonly_test.go (1)

31-40: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add the repo’s short given / when / then markers at the top of these subtests.

These are non-trivial lifecycle subtests, so it’d be good to start each body with the expected intent comments.

As per coding guidelines, For service and lifecycle subtests, start non-trivial subtest bodies with concise given/when/then intent comments.

Also applies to: 50-88

🤖 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/creditsonly_test.go` around
lines 31 - 40, The credits-only lifecycle subtests in the test function using
newCreditsOnlyStateMachineForTest should begin each non-trivial t.Run body with
the repo’s concise given/when/then intent markers. Add the short given/when/then
comments at the top of the affected subtests before the CanFire assertions so
the lifecycle intent is clear and consistent with the coding guidelines.

Source: Coding guidelines

pkg/statelessx/actions.go (1)

9-9: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Drop lo.Map here and use the same plain loop shape as AllOf.

This version adds an extra dependency use, builds a temporary []error, and recreates WithParameters[T] wrappers on every call. A small loop is easier to read and matches the rest of this file.

As per coding guidelines, Prefer standard library slices and maps helpers for common collection operations, and use github.com/samber/lo only when it clearly improves pointer literals or transformations.

Suggested refactor
-	"github.com/samber/lo"
-
 	"github.com/openmeterio/openmeter/pkg/models"
 )
@@
 func AllOfWithParameters[T models.Validator](fn ...func(context.Context, T) error) func(context.Context, ...any) error {
+	actions := make([]func(context.Context, ...any) error, 0, len(fn))
+	for _, f := range fn {
+		actions = append(actions, WithParameters[T](f))
+	}
+
 	return func(ctx context.Context, args ...any) error {
-		return errors.Join(
-			lo.Map(fn, func(fn func(context.Context, T) error, _ int) error {
-				return WithParameters[T](fn)(ctx, args...)
-			})...,
-		)
+		var outErr error
+		for _, action := range actions {
+			if err := action(ctx, args...); err != nil {
+				outErr = errors.Join(outErr, err)
+			}
+		}
+
+		return outErr
 	}
 }

Also applies to: 56-62

🤖 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 `@pkg/statelessx/actions.go` at line 9, Remove the unnecessary lo.Map usage
from the affected helper in actions.go and rewrite it with the same
straightforward loop pattern used by AllOf. Update the function that builds the
[]error result to append directly inside the loop instead of creating an
intermediate slice and recreating WithParameters[T] wrappers on each call,
keeping the implementation simple and consistent with the rest of the file.

Sources: Coding guidelines, Path instructions

openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go (1)

963-966: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Refresh the test narrative for native patch behavior.

These assertions now expect the same charge to remain active, advance from the cancellation boundary, and have no realizations. The Then block above still describes the old recreated-charge/pre-cancellation-realization flow, so it’s worth updating to match. As per coding guidelines, “preserve existing explanatory comments unless the code change makes them false, stale, or misleading.”

🤖 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/creditsonly_test.go` around
lines 963 - 966, The test narrative in the surrounding `Then` block is stale
because the assertions for `afterShrinkCharge` now describe native patch
behavior: the same charge stays active, advances from the cancellation boundary,
and has no realizations. Update the explanatory comments in
`creditsonly_test.go` around the `afterShrinkCharge` assertions so they match
the current flow and no longer mention a recreated charge or pre-cancellation
realizations.

Source: Coding guidelines

openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go (1)

177-177: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep the flat-fee fixture typed as flat-fee.

This helper builds a chargesflatfee.Charge, but accepting chargesusagebased.Intent makes the fixture easy to misuse and obscures which fields matter for flat-fee tests. A small flat-fee-specific intent helper would keep this cleaner. As per coding guidelines, “Keep helper functions honest and narrow.”

🤖 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`
at line 177, The flat-fee test helper is too loosely typed because
newChargePatchTestFlatFeeItemWithIntent accepts chargesusagebased.Intent even
though it builds a chargesflatfee.Charge; update this fixture to use a
flat-fee-specific intent type or add a dedicated flat-fee intent helper so the
signature matches its purpose. Adjust the related test setup in
newChargePatchTestFlatFeeItemWithIntent and any callers so the helper stays
narrow and only exposes the flat-fee fields needed by these tests.

Source: Coding guidelines

🤖 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/creditsonly_test.go`:
- Around line 24-43: The new credits-only period patch test only covers
finalization statuses, so extend
TestCreditsOnlyPeriodPatchIsConfiguredForFinalRealizationBoundaries to also
exercise usagebased.StatusCreated and usagebased.StatusActive through
newCreditsOnlyStateMachineForTest. Verify CanFire for both meta.TriggerShrink
and meta.TriggerExtend on those states as well, so the configureStates wiring
for the created/active patch paths is covered.

In `@openmeter/billing/charges/usagebased/service/creditsonly.go`:
- Around line 55-56: `creditsOnlyStateMachine` currently routes `TriggerExtend`
and `TriggerShrink` through `persistActivePeriodPatch()`, which force-sets the
charge to `StatusActive` and rewrites `AdvanceAfter` even when the charge is
still `usagebased.StatusCreated`. Update the `ExtendCharge`/`ShrinkCharge`
handling in `creditsonly.go` so the `StatusCreated` path is special-cased before
`persistActivePeriodPatch()` is called, or split it into a separate
created-state branch that only updates the intended patch fields. Keep the
`StatusCreated` lifecycle state and scheduling unchanged until activation, and
only apply the active-period patch logic for non-created statuses.

---

Nitpick comments:
In `@openmeter/billing/charges/usagebased/service/creditsonly_test.go`:
- Around line 31-40: The credits-only lifecycle subtests in the test function
using newCreditsOnlyStateMachineForTest should begin each non-trivial t.Run body
with the repo’s concise given/when/then intent markers. Add the short
given/when/then comments at the top of the affected subtests before the CanFire
assertions so the lifecycle intent is clear and consistent with the coding
guidelines.

In `@openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go`:
- Around line 963-966: The test narrative in the surrounding `Then` block is
stale because the assertions for `afterShrinkCharge` now describe native patch
behavior: the same charge stays active, advances from the cancellation boundary,
and has no realizations. Update the explanatory comments in
`creditsonly_test.go` around the `afterShrinkCharge` assertions so they match
the current flow and no longer mention a recreated charge or pre-cancellation
realizations.

In
`@openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go`:
- Line 177: The flat-fee test helper is too loosely typed because
newChargePatchTestFlatFeeItemWithIntent accepts chargesusagebased.Intent even
though it builds a chargesflatfee.Charge; update this fixture to use a
flat-fee-specific intent type or add a dedicated flat-fee intent helper so the
signature matches its purpose. Adjust the related test setup in
newChargePatchTestFlatFeeItemWithIntent and any callers so the helper stays
narrow and only exposes the flat-fee fields needed by these tests.

In `@pkg/statelessx/actions.go`:
- Line 9: Remove the unnecessary lo.Map usage from the affected helper in
actions.go and rewrite it with the same straightforward loop pattern used by
AllOf. Update the function that builds the []error result to append directly
inside the loop instead of creating an intermediate slice and recreating
WithParameters[T] wrappers on each call, keeping the implementation simple and
consistent with the rest of the file.
🪄 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: c9190610-9f5e-411a-9b5d-956787812a4e

📥 Commits

Reviewing files that changed from the base of the PR and between 5b9c743 and e424392.

📒 Files selected for processing (10)
  • openmeter/billing/charges/flatfee/service/creditsonly.go
  • openmeter/billing/charges/meta/patch.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/service/creditsonly_test.go
  • openmeter/billing/worker/subscriptionsync/service/creditsonly_test.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
  • pkg/statelessx/actions.go

@turip turip added release-note/bug-fix Release note: Bug Fixes release-note/feature Release note: Exciting New Features area/billing labels Jun 29, 2026
@turip
turip merged commit 1d4286f into main Jun 29, 2026
41 of 42 checks passed
@turip
turip deleted the fix/credits-only-patch-extend branch June 29, 2026 11:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing release-note/bug-fix Release note: Bug Fixes release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants