Skip to content

feat: improve substate storage for usagebased items - #3979

Merged
turip merged 4 commits into
mainfrom
feat/improve-substate-storage
Mar 20, 2026
Merged

turip merged 4 commits into
mainfrom
feat/improve-substate-storage

Conversation

@turip

@turip turip commented Mar 20, 2026 •

Copy link
Copy Markdown
Member

Overview

This patch improves the usagebased schema by:

  • Allowing for substates needed by state machine
  • Add totals values for runs, so that we can calculate differences
  • Add advance_after field for credit_only entities in the main charge object (will be used for triggering when invoicing is not involved)
  • Add sort_hint for credit realizations so that we know the ledger priority order

Notes for reviewer

Summary by CodeRabbit

Release Notes

  • New Features

    • Charges can now be configured to advance after a specified timestamp
    • Usage-based charges now have enhanced status tracking with detailed realization substates
    • Added ability to track the current realization run for charge management
  • Chores

    • Database schema updated to support new charge capabilities

@turip
turip requested a review from a team as a code owner March 20, 2026 08:26
@coderabbitai

coderabbitai Bot commented Mar 20, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR introduces charge state tracking and ordering enhancements by adding an optional AdvanceAfter timestamp to all charges, a new status type for usage-based charges with substates, tracking of the current realization run, and sort hints for credit realizations, along with corresponding database schema migrations.

Changes

Cohort / File(s) Summary
Meta Charge Model
openmeter/billing/charges/meta/charge.go, openmeter/billing/charges/meta/adapter.go
Added AdvanceAfter *time.Time field to Charge and IntentCreate structs to allow optional timestamp-based advancement hints.
Meta Charge Adapters
openmeter/billing/charges/meta/adapter/create.go, openmeter/billing/charges/meta/adapter/mapper.go, openmeter/billing/charges/meta/adapter/update.go
Updated adapter layer to persist and retrieve AdvanceAfter field through creation, mapping, and status update flows.
Usage-Based Charge State Machine
openmeter/billing/charges/usagebased/statemachine.go
New module introducing Status type with top-level states (created, active, final) and active substates (active.final_realization.*), with conversion, validation, and value enumeration methods.
Usage-Based Charge Model & Adapters
openmeter/billing/charges/usagebased/charge.go, openmeter/billing/charges/usagebased/adapter/charge.go, openmeter/billing/charges/usagebased/adapter/mapper.go
Changed Status from meta type to local type, added CurrentRealizationRunID to charge state with validation, and updated adapters to properly source/persist status and current realization run from database.
Credit Realization Ordering
openmeter/billing/charges/models/creditrealization/mixin.go, openmeter/billing/charges/models/creditrealization/models.go, openmeter/billing/charges/flatfee/adapter/credits.go
Added SortHint int field to credit realizations with full persistence pipeline, and updated credit allocation creation to pass sort hints from callers.
Database Schema
openmeter/ent/schema/charges.go, openmeter/ent/schema/chargesusagebased.go, tools/migrate/migrations/20260320084936_charges-state-details.*
Added nullable advance_after timestamp to charges, added status enum and current_realization_run_id fields to usage-based charges, added sort_hint to credit allocations and aggregate totals to realization runs, with corresponding up/down migrations.

Sequence Diagram

sequenceDiagram
    participant Client
    participant API
    participant Adapter as UsageBased Adapter
    participant StateMachine as State Machine
    participant DB as Database

    Client->>API: UpdateCharge(charge with new status)
    API->>Adapter: UpdateCharge(charge)
    Adapter->>StateMachine: charge.Status.ToMetaChargeStatus()
    StateMachine->>StateMachine: Validate status format
    StateMachine->>StateMachine: Extract meta status from substate
    StateMachine-->>Adapter: meta.ChargeStatus
    Adapter->>DB: UpdateStatus(meta status, advanceAfter)
    DB->>DB: Set status, CurrentRealizationRunID, AdvanceAfter
    DB-->>Adapter: Success
    Adapter->>DB: MapUsageBasedChargeFromDB
    DB-->>Adapter: entity with status, currentRealizationRunID
    Adapter-->>API: usagebased.Charge with local Status
    API-->>Client: Response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested labels

release-note/feature

Suggested reviewers

  • tothandras
  • chrisgacsal
  • GAlexIHU
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.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 accurately reflects the core changes: adding substate storage and related fields (status, current_realization_run_id, advance_after, sort_hint) to support the usage-based state machine.

✏️ 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/improve-substate-storage
📝 Coding Plan
  • Generate coding plan for human review comments

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 added release-note/misc Miscellaneous changes area/billing labels Mar 20, 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.

Actionable comments posted: 4

Caution

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

⚠️ Outside diff range comments (1)
openmeter/billing/charges/usagebased/charge.go (1)

110-117: ⚠️ Potential issue | 🟠 Major

Validate CurrentRealizationRunID against RealizationRuns.

Right now this new pointer can reference a run that is not actually present in the aggregate and Validate() still returns nil. That leaves you with a dangling “current run” that only fails later when the state machine tries to use it.

💡 Suggested fix
 func (s State) Validate() error {
-	return s.RealizationRuns.Validate()
+	var errs []error
+
+	if err := s.RealizationRuns.Validate(); err != nil {
+		errs = append(errs, err)
+	}
+
+	if s.CurrentRealizationRunID != nil && !slices.ContainsFunc(s.RealizationRuns, func(run RealizationRun) bool {
+		return run.ID == *s.CurrentRealizationRunID
+	}) {
+		errs = append(errs, fmt.Errorf("current realization run id must reference one of the realization runs"))
+	}
+
+	return errors.Join(errs...)
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/charge.go` around lines 110 - 117, The
State.Validate method must also ensure CurrentRealizationRunID (pointer)
actually refers to an existing entry in RealizationRuns: after calling
s.RealizationRuns.Validate(), if s.CurrentRealizationRunID != nil iterate the
RealizationRuns collection (or use its lookup method) to confirm an entry with
that ID exists and return a descriptive error if not found so you don't allow a
dangling current run; update State.Validate() accordingly to perform this
existence check.
🧹 Nitpick comments (2)
openmeter/ent/schema/charges.go (1)

82-84: Consider a partial index on advance_after if a worker will poll it.

If ready-to-advance charges are going to be selected by advance_after <= now(), this new column becomes a filter key and the lookup will otherwise turn into a full scan on charges. A small partial index on non-null advance_after would keep that path cheap.

As per coding guidelines, performance should be a priority in critical code paths, including database operations.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/ent/schema/charges.go` around lines 82 - 84, Add a partial index to
speed up queries filtering on the advance_after column: create a DB migration
that runs something like "CREATE INDEX CONCURRENTLY idx_charges_advance_after ON
charges (advance_after) WHERE advance_after IS NOT NULL" (and drop it on
rollback), so lookups like advance_after <= now() don’t trigger full-table
scans; target the "advance_after" field introduced in the Ent schema
(field.Time("advance_after")) and ensure the migration runs without locking
(CONCURRENTLY) in production.
openmeter/billing/charges/usagebased/adapter/charge.go (1)

38-43: Watch out for the SetNillableCurrentRealizationRunID no-op trap.

Ent's SetNillable* methods only set when the value is non-nil — passing nil won't actually clear the database field. If your state machine transitions to "no current run" (represented as nil), you'll need to branch to ClearCurrentRealizationRunID() explicitly, otherwise stale run IDs will linger in the database.

Verified behavior

The generated SetNillableCurrentRealizationRunID in chargeusagebased_update.go does exactly this:

if v != nil {
  _u.SetCurrentRealizationRunID(*v)
}

So nil values are silently ignored. Whether this matters depends on whether your state machine actually represents "no current run" as nil — if so, add the conditional clear.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/adapter/charge.go` around lines 38 - 43,
The UpdateOneID call using SetNillableCurrentRealizationRunID will ignore nil
and therefore won't clear an existing DB value; update the transaction logic
around tx.db.ChargeUsageBased.UpdateOneID(charge.ID) to branch on
charge.State.CurrentRealizationRunID: if non-nil keep using
SetNillableCurrentRealizationRunID (or SetCurrentRealizationRunID), but if nil
call ClearCurrentRealizationRunID() on the Update builder before Save(ctx) so
stale run IDs are removed.
🤖 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/meta/adapter.go`:
- Around line 21-25: UpdateStatusInput currently allows AdvanceAfter to be set
for any charge; restrict this so only credit_purchase charges accept an
advanceAfter update. Add a guard/validation where UpdateStatusInput is
constructed or validated (reference UpdateStatusInput, AdvanceAfter, ChargeID,
ChargeStatus) to reject or ignore AdvanceAfter unless the associated charge type
=== "credit_purchase", and move any code that writes charges.advance_after into
the credit-purchase lifecycle path (the credit-purchase create/update handler)
instead of the shared invoice/charge update flow (e.g., avoid setting
AdvanceAfter in handleStandardInvoiceUpdate / handleChargeEvent); also ensure
creation-time validation enforces that only credit_purchase charges are created
with advance_after.

In `@openmeter/billing/charges/meta/adapter/update.go`:
- Around line 19-23: The patch should replace the SetNillableAdvanceAfter call
with the generator-provided SetOrClearAdvanceAfter on the UpdateOne flow so nil
will clear the DB field instead of being a no-op; locate the update chain
beginning with tx.db.Charge.UpdateOneID(...) in update.go (the block that
currently calls SetNillableAdvanceAfter(convert.SafeToUTC(in.AdvanceAfter))) and
swap that call to SetOrClearAdvanceAfter(convert.SafeToUTC(in.AdvanceAfter))
while keeping the surrounding Where(...).SetStatus(...).Save(ctx) logic intact.

In `@openmeter/billing/charges/usagebased/statemachine.go`:
- Around line 46-57: The bug is that ToMetaChargeStatus() currently accepts
dotted statuses like "active.typo" by only validating the prefix; change
ToMetaChargeStatus in statemachine.go to reject any dotted status before
collapsing: if the Status string contains a '.' return an error (e.g. "invalid
status: %s") so only bare statuses are converted, then convert to
meta.ChargeStatus and call metaStatus.Validate() as before; update error paths
to return meta.ChargeStatusCreated on failure.

In `@openmeter/ent/schema/chargesusagebased.go`:
- Around line 83-86: Change the reverse delete behavior for the current_run
edge: in the edge declaration using ChargeUsageBasedRuns.Type and
Field("current_realization_run_id") replace the entsql.OnDelete(entsql.Cascade)
annotation with entsql.OnDelete(entsql.SetNull) (or
entsql.OnDelete(entsql.NoAction) if you want to prevent deletes) so deleting a
run nulls the current_run pointer instead of cascading and removing the parent
charge; after the code change regenerate the Atlas migration so the SQL reflects
the new ON DELETE behavior.

---

Outside diff comments:
In `@openmeter/billing/charges/usagebased/charge.go`:
- Around line 110-117: The State.Validate method must also ensure
CurrentRealizationRunID (pointer) actually refers to an existing entry in
RealizationRuns: after calling s.RealizationRuns.Validate(), if
s.CurrentRealizationRunID != nil iterate the RealizationRuns collection (or use
its lookup method) to confirm an entry with that ID exists and return a
descriptive error if not found so you don't allow a dangling current run; update
State.Validate() accordingly to perform this existence check.

---

Nitpick comments:
In `@openmeter/billing/charges/usagebased/adapter/charge.go`:
- Around line 38-43: The UpdateOneID call using
SetNillableCurrentRealizationRunID will ignore nil and therefore won't clear an
existing DB value; update the transaction logic around
tx.db.ChargeUsageBased.UpdateOneID(charge.ID) to branch on
charge.State.CurrentRealizationRunID: if non-nil keep using
SetNillableCurrentRealizationRunID (or SetCurrentRealizationRunID), but if nil
call ClearCurrentRealizationRunID() on the Update builder before Save(ctx) so
stale run IDs are removed.

In `@openmeter/ent/schema/charges.go`:
- Around line 82-84: Add a partial index to speed up queries filtering on the
advance_after column: create a DB migration that runs something like "CREATE
INDEX CONCURRENTLY idx_charges_advance_after ON charges (advance_after) WHERE
advance_after IS NOT NULL" (and drop it on rollback), so lookups like
advance_after <= now() don’t trigger full-table scans; target the
"advance_after" field introduced in the Ent schema (field.Time("advance_after"))
and ensure the migration runs without locking (CONCURRENTLY) in production.
🪄 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: 20d32bdb-bfd2-41f3-aeac-14d59c972c47

📥 Commits

Reviewing files that changed from the base of the PR and between 4971c89 and 354b650.

⛔ Files ignored due to path filters (23)
  • go.sum is excluded by !**/*.sum, !**/*.sum
  • openmeter/ent/db/charge.go is excluded by !**/ent/db/**
  • openmeter/ent/db/charge/charge.go is excluded by !**/ent/db/**
  • openmeter/ent/db/charge/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/charge_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/charge_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased/chargeusagebased.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns/chargeusagebasedruns.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/client.go is excluded by !**/ent/db/**
  • openmeter/ent/db/entmixinaccessor.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (13)
  • openmeter/billing/charges/meta/adapter.go
  • openmeter/billing/charges/meta/adapter/create.go
  • openmeter/billing/charges/meta/adapter/mapper.go
  • openmeter/billing/charges/meta/adapter/update.go
  • openmeter/billing/charges/meta/charge.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/mapper.go
  • openmeter/billing/charges/usagebased/charge.go
  • openmeter/billing/charges/usagebased/statemachine.go
  • openmeter/ent/schema/charges.go
  • openmeter/ent/schema/chargesusagebased.go
  • tools/migrate/migrations/20260320081817_charges-state-details.down.sql
  • tools/migrate/migrations/20260320081817_charges-state-details.up.sql

@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 (2)
openmeter/billing/charges/usagebased/statemachine.go (1)

46-62: Nice implementation!

Good to see Validate() is called first at line 47 — that addresses the earlier concern about accepting invalid substates like "active.typo".

One small thing: the check at lines 52-54 is unreachable. strings.SplitN always returns at least one element (even for an empty string, it returns [""]). Since you've already validated the status above, this check will never trigger anyway.

Optional cleanup
 func (s Status) ToMetaChargeStatus() (meta.ChargeStatus, error) {
 	if err := s.Validate(); err != nil {
 		return meta.ChargeStatusCreated, err
 	}

 	split := strings.SplitN(string(s), ".", 2)
-	if len(split) == 0 {
-		return meta.ChargeStatusCreated, fmt.Errorf("invalid status: %s", s)
-	}

 	metaStatus := meta.ChargeStatus(split[0])
 	if err := metaStatus.Validate(); err != nil {
 		return meta.ChargeStatusCreated, fmt.Errorf("invalid status: %s", s)
 	}

 	return metaStatus, nil
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/statemachine.go` around lines 46 - 62,
The check that verifies len(split) == 0 in Status.ToMetaChargeStatus is
unreachable because strings.SplitN always returns at least one element and you
already call s.Validate() earlier; remove the unreachable block (lines that
check split length and return an error) and keep the existing logic that takes
split[0], casts to meta.ChargeStatus, validates via metaStatus.Validate(), and
returns metaStatus or the validation error.
openmeter/ent/schema/chargesusagebased.go (1)

83-85: Add explicit OnDelete(SetNull) annotation to match the migration.

The migration SQL specifies ON DELETE SET NULL for this FK, but the edge definition here doesn't include the corresponding Ent annotation. Since the Ent schema is the source of truth for the database schema, it's good practice to make this explicit so future schema regenerations stay consistent.

Suggested fix
 		edge.To("current_run", ChargeUsageBasedRuns.Type).
 			Field("current_realization_run_id").
-			Unique(),
+			Unique().
+			Annotations(entsql.OnDelete(entsql.SetNull)),

As per coding guidelines: "Define Ent entity schemas in openmeter/ent/schema/ as the source of truth for database schema"

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/ent/schema/chargesusagebased.go` around lines 83 - 85, The edge
definition edge.To("current_run",
ChargeUsageBasedRuns.Type).Field("current_realization_run_id").Unique() is
missing the explicit ON DELETE SET NULL annotation; update that edge to include
.Annotations(entsql.OnDelete(entsql.SetNull)) (using entgo.io/ent/dialect/sql as
entsql) so the schema explicitly matches the migration and future ent codegen
preserves ON DELETE SET NULL semantics.
🤖 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/usagebased/statemachine.go`:
- Around line 46-62: The check that verifies len(split) == 0 in
Status.ToMetaChargeStatus is unreachable because strings.SplitN always returns
at least one element and you already call s.Validate() earlier; remove the
unreachable block (lines that check split length and return an error) and keep
the existing logic that takes split[0], casts to meta.ChargeStatus, validates
via metaStatus.Validate(), and returns metaStatus or the validation error.

In `@openmeter/ent/schema/chargesusagebased.go`:
- Around line 83-85: The edge definition edge.To("current_run",
ChargeUsageBasedRuns.Type).Field("current_realization_run_id").Unique() is
missing the explicit ON DELETE SET NULL annotation; update that edge to include
.Annotations(entsql.OnDelete(entsql.SetNull)) (using entgo.io/ent/dialect/sql as
entsql) so the schema explicitly matches the migration and future ent codegen
preserves ON DELETE SET NULL semantics.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 312aeaff-f73c-4fad-b82a-fd518037f95c

📥 Commits

Reviewing files that changed from the base of the PR and between d9fa1e6 and 54cd387.

⛔ Files ignored due to path filters (2)
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (6)
  • openmeter/billing/charges/meta/adapter/update.go
  • openmeter/billing/charges/usagebased/charge.go
  • openmeter/billing/charges/usagebased/statemachine.go
  • openmeter/ent/schema/chargesusagebased.go
  • tools/migrate/migrations/20260320084936_charges-state-details.down.sql
  • tools/migrate/migrations/20260320084936_charges-state-details.up.sql
🚧 Files skipped from review as they are similar to previous changes (2)
  • openmeter/billing/charges/meta/adapter/update.go
  • openmeter/billing/charges/usagebased/charge.go

@turip
turip merged commit 51db29b into main Mar 20, 2026
24 of 25 checks passed
@turip
turip deleted the feat/improve-substate-storage branch March 20, 2026 09:22

This branch was previously deployed

1 inactive deployment
dev — 54cd3877 Deployed Mar 20, 2026 by turip via Migration Checks #12686
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