Skip to content

feat: usage based patching - #4053

Merged
turip merged 3 commits into
mainfrom
feat/usage-based-patching
Apr 1, 2026
Merged

turip merged 3 commits into
mainfrom
feat/usage-based-patching

Conversation

@turip

@turip turip commented Apr 1, 2026 •

Copy link
Copy Markdown
Member

Overview

Add support for usage-based patching.

Notes for reviewer

Summary by CodeRabbit

  • New Features

    • Charges can be deleted and removed from subscriptions.
    • Added ability to trigger patch operations to modify charge state and parameters.
  • Behavior Changes

    • Subscription cancellation now cleans up usage-based charges and updates realizations at cancellation boundary.
    • Deleted status introduced for usage-based charges.
  • Bug Fixes

    • Credit refund corrections are generated during charge deletion when configured.
  • Tests

    • New tests cover cancellation and mid-period deletion behavior.

@coderabbitai

coderabbitai Bot commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

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: 694e388d-73e9-4e5d-98f5-281d4cc607a2

📥 Commits

Reviewing files that changed from the base of the PR and between 43bfebe and c279cda.

📒 Files selected for processing (1)
  • openmeter/billing/charges/usagebased/service/triggers.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • openmeter/billing/charges/usagebased/service/triggers.go

📝 Walkthrough

Walkthrough

Adds deletion and patch-triggering for usage-based charges: new adapter and service methods (DeleteCharge, TriggerPatch), state-machine StatusDeleted transition with optional credit-correction generation, invocable-charge bridge for usage-based charges, and tests covering cancellation scenarios.

Changes

Cohort / File(s) Summary
Interface Contracts
openmeter/billing/charges/usagebased/adapter.go, openmeter/billing/charges/usagebased/service.go
Added DeleteCharge to ChargeAdapter and TriggerPatch to UsageBasedService.
State Machine & Behavior
openmeter/billing/charges/usagebased/statemachine.go, openmeter/billing/charges/usagebased/service/creditsonly.go
Added StatusDeleted, allowed delete trigger transitions from multiple states, implemented DeleteCharge entry action which may generate credit refund corrections, and removed unused Trigger alias/vars.
Service Logic & Triggers
openmeter/billing/charges/usagebased/service/triggers.go, openmeter/billing/charges/usagebased/service/statemachine.go
Added TriggerPatch, withLockedCharge, getStateMachineConfigForPatch; refactored AdvanceCharge to use locking helper; updated FireAndActivate to accept variadic args.
Adapter Implementation
openmeter/billing/charges/usagebased/adapter/charge.go
Implemented DeleteCharge to mark charge deleted in a transaction, update statuses/metadata, and call meta-adapter deletion.
Invocable Charge Layer
openmeter/billing/charges/service/helpers.go
Added usageBasedInvocableCharge implementing InvocableCharge to enable patching via invocable abstraction.
Worker Tests & Reconciler
openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go, openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go
Added tests for cancellation scenarios; removed AddDelete/AddShrink/AddExtend placeholder methods from usage-based charge collection.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant Service as UsageBasedService
    participant StateMachine as StateMachine
    participant Adapter as Adapter
    participant Meta as MetaAdapter

    Client->>Service: TriggerPatch(chargeID, patch)
    Service->>Service: withLockedCharge(lock & load charge)
    Service->>Service: getStateMachineConfigForPatch(charge)
    Service->>StateMachine: FireAndActivate(trigger, args...)
    StateMachine->>Service: invoke DeleteCharge callback (if delete)
    Service->>Service: optionally generate credit corrections
    Service->>Adapter: DeleteCharge(charge)
    Adapter->>Adapter: set DeletedAt, status->Deleted, persist
    Adapter->>Meta: DeleteRegisteredCharge(chargeID)
    Meta-->>Adapter: ack
    Adapter-->>Service: ack
    Service->>Service: refetchCharge()
    Service-->>Client: return updated (deleted) charge
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

release-note/feature

Suggested reviewers

  • tothandras
  • GAlexIHU
  • solkimicreb
🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: usage based patching' clearly and concisely describes the main feature being added across the changeset—support for patching usage-based charges through new trigger mechanisms and state transitions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ 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 feat/usage-based-patching

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 force-pushed the feat/usage-based-patching branch from 6ba0114 to 9c96dfc Compare April 1, 2026 14:54
@turip turip changed the title Feat/usage based patching feat: usage based patching Apr 1, 2026
@turip turip added release-note/misc Miscellaneous changes area/billing labels Apr 1, 2026
@turip
turip marked this pull request as ready for review April 1, 2026 14:56
@turip
turip requested a review from a team as a code owner April 1, 2026 14:56
Base automatically changed from feat/subs-sync-charge-delete to main April 1, 2026 14:56
@turip
turip force-pushed the feat/usage-based-patching branch from 9c96dfc to 43bfebe Compare April 1, 2026 14:58

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@openmeter/billing/charges/usagebased/adapter/charge.go`:
- Around line 117-121: The soft-delete of the registered charge must run inside
the same DB transaction as update.Save to avoid drift; change the call site in
charge.go to invoke a meta-adapter method that operates on the current tx (e.g.,
DeleteRegisteredChargeTx or DeleteRegisteredCharge(ctx, tx)) instead of the
existing standalone DeleteRegisteredCharge, and update
openmeter/billing/charges/meta/adapter/charges.go to add a Tx-aware variant (or
overload) that uses the provided transaction rather than starting its own;
ensure the new Tx-aware method is used here so both update.Save and the
registered-charge delete are committed/rolled back together.

In `@openmeter/billing/charges/usagebased/service/creditsonly.go`:
- Around line 125-147: The refund corrections are committed with
s.Adapter.CreateRunCreditRealization inside the loop and the charge is deleted
later with s.Adapter.DeleteCharge, which can leave refunds persisted if the
delete fails; wrap the create-corrections + delete into a single atomic
operation by adding a new transactional adapter method (e.g.,
Adapter.CreateRunCreditRealizationsAndDeleteCharge or Adapter.WithTx(func(tx
AdapterTx) { CreateRunCreditRealization(tx, ...); DeleteCharge(tx, ...) })) and
call that instead of separate CreateRunCreditRealization/DeleteCharge calls;
update service handler usage to pass all corrections for a run and invoke the
new transactional method so both persistence of corrections and deletion of
s.Charge succeed or roll back together.

In `@openmeter/billing/charges/usagebased/service/triggers.go`:
- Around line 62-67: The TriggerPatch function currently calls
stateMachine.FireAndActivate(ctx, patch.Trigger(), patch.TriggerParams()) and
then returns nil, nil which conflicts with its declared return type
(*usagebased.Charge, error); update it either to return the resulting charge
like AdvanceCharge does (refetch or obtain the charge from the state machine
after FireAndActivate and return that along with nil error) or change
TriggerPatch's signature to return only error and update callers/interfaces
accordingly; locate TriggerPatch and the stateMachine.FireAndActivate usage and
choose the appropriate fix (return the charge object instead of nil or simplify
the signature to error).

In `@openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go`:
- Around line 893-979: Add a new test case in creditsonly_test.go that exercises
the refund-correction branch of CreditsOnlyStateMachine.DeleteCharge: create or
seed a usage-based charge that already has a Realization with CreditsAllocated
(non-zero), then trigger the deletion path (same pattern used here: Cancel
subscription + Service.SynchronizeSubscription or directly call DeleteCharge
flow), fetch the resulting charge(s) via s.Charges.GetByID and
AsUsageBasedCharge, and assert that a correction realization was emitted with
adjusted Totals (Refund/Correction reflected in Totals.Total and
Totals.CreditsTotal) and that CreditsAllocated entries were adjusted/removed as
expected; reference the helpers expectCreditsOnlyUsageBasedCharges,
Charges.GetByID, AsUsageBasedCharge, and the
CreditsAllocated/CreditRefundPolicyCorrect symbols to locate where to add/setup
assertions. Ensure the test verifies both the emitted correction realization(s)
values and the final deleted/updated charge statuses.
🪄 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: ac814d13-e669-4d82-820e-a61056a434d5

📥 Commits

Reviewing files that changed from the base of the PR and between 4ba29f4 and 43bfebe.

⛔ Files ignored due to path filters (2)
  • openmeter/ent/db/chargeusagebased/chargeusagebased.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
📒 Files selected for processing (10)
  • openmeter/billing/charges/service/helpers.go
  • openmeter/billing/charges/usagebased/adapter.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/service/statemachine.go
  • openmeter/billing/charges/usagebased/service/triggers.go
  • openmeter/billing/charges/usagebased/statemachine.go
  • openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go
💤 Files with no reviewable changes (1)
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go

@turip
turip merged commit a4a2fa1 into main Apr 1, 2026
23 checks passed
@turip
turip deleted the feat/usage-based-patching branch April 1, 2026 15:57
@coderabbitai coderabbitai Bot mentioned this pull request Apr 23, 2026

This branch was previously deployed

1 inactive deployment
dev — c279cdaa Deployed Apr 1, 2026 by turip via Migration Checks #13108
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