Skip to content

chore: refactor state machines - #4133

Merged
turip merged 2 commits into
mainfrom
feat/refactor-statemachine
Apr 13, 2026
Merged

turip merged 2 commits into
mainfrom
feat/refactor-statemachine

Conversation

@turip

@turip turip commented Apr 13, 2026 •

Copy link
Copy Markdown
Member

Overview

Refactor the existing usage based and flatfee services to have the same structure of state-machines.

Logical steps are split into subpackages so that the state-machine is not swamped with all the low level details.

Notes for reviewer

Summary by CodeRabbit

  • Refactor
    • Reorganized credit realization, rating, and run mechanics into modular services and a shared state-machine base for flat-fee and usage-based billing.
  • New Features
    • Improved credit allocation/reconciliation flows for usage-based and flat-fee charges; clearer credit application reporting.
    • Expanded settlement-mode support in ledger handlers to include credit-then-invoice.
  • Bug Fixes
    • More consistent invoice/line totals and credit application after lifecycle transitions.
  • Tests
    • Extended tests to cover credit-then-invoice and allocation scenarios.
  • Documentation
    • Added guidance on realization helper subpackages and naming/usage conventions.

@coderabbitai

coderabbitai Bot commented Apr 13, 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: d475d667-6ae8-4195-a6aa-999418d4b6b6

📥 Commits

Reviewing files that changed from the base of the PR and between e907953 and 6b88c6a.

📒 Files selected for processing (6)
  • openmeter/billing/charges/models/creditrealization/realizations.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/ledger/chargeadapter/usagebased.go
  • openmeter/ledger/chargeadapter/usagebased_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/service/invoicable_test.go
👮 Files not reviewed due to content moderation or server errors (4)
  • openmeter/billing/charges/models/creditrealization/realizations.go
  • openmeter/ledger/chargeadapter/usagebased.go
  • openmeter/ledger/chargeadapter/usagebased_test.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go

📝 Walkthrough

Walkthrough

Refactors credit realization and run mechanics into dedicated services (flat-fee realizations and usage-based run services), extracts rating into a rating service, and adapts state machines to delegate orchestration to these services instead of inlining realization/lineage logic.

Changes

Cohort / File(s) Summary
New flat-fee realizations service
openmeter/billing/charges/flatfee/service/realizations/service.go
Adds flatfeerealizations.Service to create allocations and persist realization lineage/corrections (delegates to adapter and lineage service; wraps errors).
Flat-fee state machine & wiring
openmeter/billing/charges/flatfee/service/statemachine.go, openmeter/billing/charges/flatfee/service/creditsonly.go, openmeter/billing/charges/flatfee/service/lineage.go, openmeter/billing/charges/flatfee/service/invoice.go, openmeter/billing/charges/flatfee/service/service.go, openmeter/billing/charges/flatfee/service/triggers.go
Introduces a stateMachine wrapper and StateMachine interface usage; CreditsOnlyStateMachine now embeds *stateMachine; removed inline create/correct helpers and replaced calls with realizations service; updated factory wiring and refetch/persist flow.
New usage-based run services
openmeter/billing/charges/usagebased/service/run/service.go, openmeter/billing/charges/usagebased/service/run/create.go, openmeter/billing/charges/usagebased/service/run/credits.go, openmeter/billing/charges/usagebased/service/run/correct.go
Adds usagebasedrun.Service for creating rated runs, allocating credits, reconciling credits, and persisting lineage/corrections; introduces credit allocation modes and validation.
Usage-based state machine & service refactor
openmeter/billing/charges/usagebased/service/statemachine.go, openmeter/billing/charges/usagebased/service/creditsonly.go, openmeter/billing/charges/usagebased/service/creditheninvoice.go, openmeter/billing/charges/usagebased/service/triggers.go, openmeter/billing/charges/usagebased/service/service.go, openmeter/billing/charges/usagebased/service/mutations.go, openmeter/billing/charges/usagebased/service/lineage.go, openmeter/billing/charges/usagebased/service/lineengine.go, openmeter/billing/charges/usagebased/service/currenttotals.go
Renames/converts concrete state machine to unexported stateMachine + exported StateMachine interface; service now composes rater and runs services; removed inline run/lineage helpers and delegate to runs.Service; updated call sites to use new interfaces and methods.
Rating extraction
openmeter/billing/charges/usagebased/service/rating/service.go, openmeter/billing/charges/usagebased/service/rating/quantitysnapshot.go
Extracts rating logic into exported rating.Service with GetRatingForUsage, adds config validation and exported input/result types.
Model helpers
openmeter/billing/charges/models/creditrealization/realizations.go
Adds Realizations.AsCreditsApplied() to derive billing credit applications from allocations+corrections.
Ledger adapter & tests
openmeter/ledger/chargeadapter/usagebased.go, openmeter/ledger/chargeadapter/usagebased_test.go
Expands allowed settlement modes for certain handler calls and adds tests for CreditThenInvoice behavior; adjusts test helpers to support variable settlement modes.
Docs & tests
.agents/skills/charges/SKILL.md, openmeter/billing/charges/service/invoicable_test.go
Docs: guidance on realization helper subpackages and responsibilities. Tests: updated usage-based accrual test to simulate available credit clamping and assert totals.

Sequence Diagram(s)

mermaid
sequenceDiagram
participant SM as StateMachine
participant Runs as usagebasedrun.Service / flatfeerealizations.Service
participant Handler as ChargeHandler
participant Adapter as BillingAdapter
participant Lineage as LineageService

SM->>Runs: Request Allocate / Create / Correct (charge, amounts, asOf)
Runs->>Handler: OnCreditsOnlyUsageAccrued / Correction callbacks
Handler-->>Runs: Allocation creation inputs
Runs->>Adapter: Create Credit Realizations / Create Run Realizations
Adapter-->>Runs: Realizations
Runs->>Lineage: CreateInitialLineages / PersistCorrectionLineageSegments
Lineage-->>Runs: Confirmation
Runs-->>SM: Return Realizations / Allocated totals

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

area/billing

Suggested reviewers

  • tothandras
  • GAlexIHU
🚥 Pre-merge checks | ✅ 2 | ❌ 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 (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'chore: refactor state machines' accurately summarizes the primary change: a significant restructuring of state machine implementations across flat-fee and usage-based services into a shared structure with extracted subpackages.

✏️ 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/refactor-statemachine

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/refactor-statemachine branch from 37ec4c5 to e6948ab Compare April 13, 2026 13:30
@turip turip added the release-note/misc Miscellaneous changes label Apr 13, 2026
@turip
turip force-pushed the feat/refactor-statemachine branch from e6948ab to e907953 Compare April 13, 2026 13:36
@turip
turip marked this pull request as ready for review April 13, 2026 13:38
@turip
turip requested a review from a team as a code owner April 13, 2026 13:38

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

🧹 Nitpick comments (1)
openmeter/billing/charges/flatfee/service/statemachine.go (1)

145-155: Consistent state machine base with usage-based pattern.

The structure mirrors the usage-based state machine nicely, which helps maintainability.

One small difference: refetchCharge here doesn't pass any expands, while the usage-based version at statemachine.go:139-142 passes meta.Expands{meta.ExpandRealizations}. If flat-fee realizations are needed after refetch (e.g., in DeleteCharge), you might want to add similar expand options. But if the current callers don't need them, this is fine as-is.

🔧 Optional: Add expands if realizations are needed after refetch
 func (s *stateMachine) refetchCharge(ctx context.Context) error {
 	charge, err := s.Adapter.GetByID(ctx, flatfee.GetByIDInput{
 		ChargeID: s.Charge.GetChargeID(),
+		Expands:  meta.Expands{meta.ExpandRealizations},
 	})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/flatfee/service/statemachine.go` around lines 145 -
155, The refetchCharge method currently calls s.Adapter.GetByID without any
expand options; if downstream handlers like DeleteCharge need flat-fee
realizations, update refetchCharge to pass meta.Expands{meta.ExpandRealizations}
into GetByID (i.e., adjust the GetByID invocation inside
stateMachine.refetchCharge to include the expands param) so s.Charge returned
contains realizations after refetch; otherwise leave as-is if realizations are
truly unnecessary.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@openmeter/billing/charges/flatfee/service/statemachine.go`:
- Around line 145-155: The refetchCharge method currently calls
s.Adapter.GetByID without any expand options; if downstream handlers like
DeleteCharge need flat-fee realizations, update refetchCharge to pass
meta.Expands{meta.ExpandRealizations} into GetByID (i.e., adjust the GetByID
invocation inside stateMachine.refetchCharge to include the expands param) so
s.Charge returned contains realizations after refetch; otherwise leave as-is if
realizations are truly unnecessary.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9cdb65bd-1d6f-49a3-8b93-26a82f903743

📥 Commits

Reviewing files that changed from the base of the PR and between 5d09e07 and e907953.

📒 Files selected for processing (24)
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/charges/flatfee/service/creditsonly.go
  • openmeter/billing/charges/flatfee/service/invoice.go
  • openmeter/billing/charges/flatfee/service/lineage.go
  • openmeter/billing/charges/flatfee/service/realizations/service.go
  • openmeter/billing/charges/flatfee/service/service.go
  • openmeter/billing/charges/flatfee/service/statemachine.go
  • openmeter/billing/charges/flatfee/service/triggers.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/service/currenttotals.go
  • openmeter/billing/charges/usagebased/service/lineage.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/usagebased/service/mutations.go
  • openmeter/billing/charges/usagebased/service/rating/quantitysnapshot.go
  • openmeter/billing/charges/usagebased/service/rating/service.go
  • openmeter/billing/charges/usagebased/service/run/correct.go
  • openmeter/billing/charges/usagebased/service/run/create.go
  • openmeter/billing/charges/usagebased/service/run/credits.go
  • openmeter/billing/charges/usagebased/service/run/service.go
  • openmeter/billing/charges/usagebased/service/service.go
  • openmeter/billing/charges/usagebased/service/statemachine.go
  • openmeter/billing/charges/usagebased/service/triggers.go
💤 Files with no reviewable changes (3)
  • openmeter/billing/charges/flatfee/service/lineage.go
  • openmeter/billing/charges/usagebased/service/mutations.go
  • openmeter/billing/charges/usagebased/service/lineage.go

@turip
turip requested review from GAlexIHU and tothandras April 13, 2026 13:56
@turip
turip enabled auto-merge (squash) April 13, 2026 15:14

This branch was previously deployed

1 inactive deployment
dev — 6b88c6a1 Deployed Apr 13, 2026 by turip via Migration Checks #13426
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/misc Miscellaneous changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants