Repository navigation
feat: improve substate storage for usagebased items - #3979
Conversation
📝 WalkthroughWalkthroughThis PR introduces charge state tracking and ordering enhancements by adding an optional Changes
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
📝 Coding Plan
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. Comment |
There was a problem hiding this comment.
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 | 🟠 MajorValidate
CurrentRealizationRunIDagainstRealizationRuns.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 onadvance_afterif 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 oncharges. A small partial index on non-nulladvance_afterwould 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 theSetNillableCurrentRealizationRunIDno-op trap.Ent's
SetNillable*methods only set when the value is non-nil — passingnilwon't actually clear the database field. If your state machine transitions to "no current run" (represented asnil), you'll need to branch toClearCurrentRealizationRunID()explicitly, otherwise stale run IDs will linger in the database.Verified behavior
The generated
SetNillableCurrentRealizationRunIDinchargeusagebased_update.godoes exactly this:if v != nil { _u.SetCurrentRealizationRunID(*v) }So
nilvalues are silently ignored. Whether this matters depends on whether your state machine actually represents "no current run" asnil— 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
⛔ Files ignored due to path filters (23)
go.sumis excluded by!**/*.sum,!**/*.sumopenmeter/ent/db/charge.gois excluded by!**/ent/db/**openmeter/ent/db/charge/charge.gois excluded by!**/ent/db/**openmeter/ent/db/charge/where.gois excluded by!**/ent/db/**openmeter/ent/db/charge_create.gois excluded by!**/ent/db/**openmeter/ent/db/charge_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased/chargeusagebased.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns/chargeusagebasedruns.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns_update.gois excluded by!**/ent/db/**openmeter/ent/db/client.gois excluded by!**/ent/db/**openmeter/ent/db/entmixinaccessor.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**openmeter/ent/db/mutation.gois excluded by!**/ent/db/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (13)
openmeter/billing/charges/meta/adapter.goopenmeter/billing/charges/meta/adapter/create.goopenmeter/billing/charges/meta/adapter/mapper.goopenmeter/billing/charges/meta/adapter/update.goopenmeter/billing/charges/meta/charge.goopenmeter/billing/charges/usagebased/adapter/charge.goopenmeter/billing/charges/usagebased/adapter/mapper.goopenmeter/billing/charges/usagebased/charge.goopenmeter/billing/charges/usagebased/statemachine.goopenmeter/ent/schema/charges.goopenmeter/ent/schema/chargesusagebased.gotools/migrate/migrations/20260320081817_charges-state-details.down.sqltools/migrate/migrations/20260320081817_charges-state-details.up.sql
There was a problem hiding this comment.
🧹 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.SplitNalways 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 explicitOnDelete(SetNull)annotation to match the migration.The migration SQL specifies
ON DELETE SET NULLfor 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
⛔ Files ignored due to path filters (2)
openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (6)
openmeter/billing/charges/meta/adapter/update.goopenmeter/billing/charges/usagebased/charge.goopenmeter/billing/charges/usagebased/statemachine.goopenmeter/ent/schema/chargesusagebased.gotools/migrate/migrations/20260320084936_charges-state-details.down.sqltools/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
Overview
This patch improves the usagebased schema by:
Notes for reviewer
Summary by CodeRabbit
Release Notes
New Features
Chores