Skip to content

feat: consolidate usage-based realization states - #4660

Merged
turip merged 3 commits into
mainfrom
feat/usagebased-realization-state
Jul 8, 2026
Merged

turip merged 3 commits into
mainfrom
feat/usagebased-realization-state

Conversation

@turip

@turip turip commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

Summary

Consolidates usage-based realization lifecycle states so the state machine no longer needs separate partial/final status branches. The realization run type now determines whether the completed run is final or non-final, allowing the lifecycle to dynamically route back to active for partial runs or into payment-settlement handling for final runs.

Details

  • Replaces partial/final invoice-created triggers with a single invoice-created trigger.
  • Uses unified active.realization.* statuses across credit-then-invoice and credits-only usage-based flows.
  • Normalizes legacy partial/final persisted statuses at state-machine load time, keeping old values accepted until a follow-up SQL migration rewrites stored rows.
  • Derives final vs non-final behavior from the realized service period and run history instead of encoding it in the status name.

Validation

Not run locally per request; CI will run the test suite.

Summary by CodeRabbit

  • New Features
    • Unified invoice-backed “realization” flow with canonical active.realization.* statuses and legacy-status normalization.
    • Added “latest realization run” selection for advancing state consistently.
  • Bug Fixes
    • Corrected invoice-creation events used to start realization flows and updated related payload/advance error handling.
    • Improved settlement detection for final invoiced runs and corrected extend handling for realization runs.
    • Prevented duplicate final realization runs when one is already active.
  • Tests
    • Updated lifecycle assertions across charge and worker flows to use the new realization-based status names.

Greptile Summary

This PR consolidates the usage-based realization lifecycle into a single state branch. The main changes are:

  • Unified invoice-created triggers for partial and final realization runs.
  • Canonical active.realization.* statuses with legacy status normalization.
  • Period-based routing after realization completion.
  • Updated usage-based and flat-fee lifecycle tests for the new status names.

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/creditheninvoice.go Reworks the credit-then-invoice lifecycle around unified realization states and adds finality-based completion routing.
openmeter/billing/charges/usagebased/statemachine.go Adds canonical realization statuses and maps legacy partial/final statuses to the new branch.
openmeter/billing/charges/usagebased/service/lineengine.go Fires the unified invoice-created trigger and passes the full invoice line period into run creation.
openmeter/billing/charges/usagebased/realizationrun.go Adds a helper for selecting the realization run furthest through the service period.
openmeter/billing/charges/usagebased/service/payments.go Aligns final invoiced run detection with period-based finality.

Reviews (3): Last reviewed commit: "fix: preserve partial run on usage-based..." | Re-trigger Greptile

Context used (3)

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

@turip
turip requested a review from a team as a code owner July 8, 2026 07:08
@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR consolidates invoice-created trigger handling, renames usage-based realization states to a canonical ActiveRealization* set, normalizes legacy statuses on load, and refactors realization-run selection and completion logic. Related flat-fee, usage-based, payment, and test paths are updated to match.

Changes

Trigger and Realization Status Unification

Layer / File(s) Summary
Trigger constant consolidation
openmeter/billing/charges/meta/triggers.go
Replaces TriggerPartialInvoiceCreated and TriggerFinalInvoiceCreated with TriggerInvoiceCreated.
Flat-fee state machine wiring
openmeter/billing/charges/flatfee/service/creditheninvoice.go, openmeter/billing/charges/flatfee/service/lineengine.go, openmeter/billing/charges/service/invoicable_test.go
Flat-fee invoice-created transitions and the standard invoice-created path now use TriggerInvoiceCreated, with the related test expectation updated.
Usage-based status model and normalization
openmeter/billing/charges/usagebased/statemachine.go, openmeter/billing/charges/usagebased/service/statemachine.go, openmeter/billing/charges/usagebased/realizationrun.go
Adds canonical realization statuses, legacy normalization, mutability checks on normalized status, normalized state-machine initialization, and latest-run selection.
Credits-only realization renaming
openmeter/billing/charges/usagebased/service/creditsonly.go, openmeter/billing/charges/usagebased/service/creditsonly_test.go
Renames credits-only realization states to ActiveRealization*, adds a duplicate-run guard, and updates normalization and helper test coverage.
Credit-then-invoice realization flow
openmeter/billing/charges/usagebased/service/creditheninvoice.go, openmeter/billing/charges/usagebased/service/creditheninvoice_test.go
Unifies the realization flow, updates completion routing, refactors invoice-created input and run typing, and adjusts extend/reconciliation tests.
Line engine and payments run selection
openmeter/billing/charges/usagebased/service/lineengine.go, openmeter/billing/charges/usagebased/service/payments.go
Uses the new run-type helper and fixed invoice-created trigger in line handling, and switches settled-run detection to a service-period-based final-run check.
Status assertion updates
openmeter/billing/charges/service/usagebased_test.go, openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go, test/credits/*
Updates lifecycle assertions across service, worker, and credits tests to the new realization status names.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

Suggested labels: release-note/misc, area/billing

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 accurately summarizes the main change: consolidating usage-based realization states.
✨ 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-realization-state

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 added release-note/misc Miscellaneous changes area/billing labels Jul 8, 2026
Comment thread openmeter/ent/db/migrate/schema.go Resolved

@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/usagebased/service/creditheninvoice.go (1)

664-673: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Tiny clarity nit: isFinalRunInPeriod only ever reads servicePeriod.To.

The From bound is discarded, yet two callers (resolveStateAfterRealizationCompleted and payments.areAllInvoicedRunsSettled) build a ClosedPeriod just to hand over a throwaway From. Taking the end time directly makes the intent obvious and drops the ceremony at the call sites. Totally optional, just a readability tidy-up.

♻️ One possible shape
-func isFinalRunInPeriod(charge usagebased.Charge, servicePeriod timeutil.ClosedPeriod) bool {
-	return meta.NormalizeTimestamp(servicePeriod.To).Equal(meta.NormalizeTimestamp(charge.Intent.GetEffectiveServicePeriod().To))
+func isFinalRunEnd(charge usagebased.Charge, servicePeriodTo time.Time) bool {
+	return meta.NormalizeTimestamp(servicePeriodTo).Equal(meta.NormalizeTimestamp(charge.Intent.GetEffectiveServicePeriod().To))
 }

(and getInvoiceRealizationRunType would pass servicePeriod.To.)

🤖 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/creditheninvoice.go` around
lines 664 - 673, `isFinalRunInPeriod` only uses the period end, so simplify the
API by changing it (and `getInvoiceRealizationRunType`) to accept the end
timestamp directly instead of a full `timeutil.ClosedPeriod`. Update the callers
in `resolveStateAfterRealizationCompleted` and
`payments.areAllInvoicedRunsSettled` to pass `servicePeriod.To` rather than
constructing a throwaway period, and keep the comparison against
`charge.Intent.GetEffectiveServicePeriod().To` via `meta.NormalizeTimestamp`.
🤖 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.

Nitpick comments:
In `@openmeter/billing/charges/usagebased/service/creditheninvoice.go`:
- Around line 664-673: `isFinalRunInPeriod` only uses the period end, so
simplify the API by changing it (and `getInvoiceRealizationRunType`) to accept
the end timestamp directly instead of a full `timeutil.ClosedPeriod`. Update the
callers in `resolveStateAfterRealizationCompleted` and
`payments.areAllInvoicedRunsSettled` to pass `servicePeriod.To` rather than
constructing a throwaway period, and keep the comparison against
`charge.Intent.GetEffectiveServicePeriod().To` via `meta.NormalizeTimestamp`.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c6b9531f-6f07-476a-b6c0-b1c25ab8d5bb

📥 Commits

Reviewing files that changed from the base of the PR and between cb9dc6a and ca548eb.

⛔ 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 (18)
  • 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/service/usagebased_test.go
  • openmeter/billing/charges/usagebased/realizationrun.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice_test.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/service/creditsonly_test.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/usagebased/service/payments.go
  • openmeter/billing/charges/usagebased/service/statemachine.go
  • openmeter/billing/charges/usagebased/statemachine.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • test/credits/credit_then_invoice_test.go
  • test/credits/sanity_lifecycle_test.go
  • test/credits/sanity_test.go

@turip
turip merged commit 822c369 into main Jul 8, 2026
26 checks passed
@turip
turip deleted the feat/usagebased-realization-state branch July 8, 2026 08:54
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