Skip to content

feat: usage based charges lifecycle - #3955

Merged
turip merged 4 commits into
mainfrom
feat/usage-based-charges-lifecycle
Mar 24, 2026
Merged

turip merged 4 commits into
mainfrom
feat/usage-based-charges-lifecycle

Conversation

@turip

@turip turip commented Mar 17, 2026 •

Copy link
Copy Markdown
Member

Overview

Implements the full lifecycle state machine for credit-only usage-based charges, from creation through final realization and settlement.

What's in this PR

State machine (usagebased/service/)

A statelessx-backed state machine drives usage-based charge advancement through seven states:

created → active → active.final_realization.started
→ active.final_realization.waiting_for_collection
→ active.final_realization.processing
→ active.final_realization.completed → final

AdvanceUntilStateStable loops the machine until no further transitions are possible in a single call, so a charge that is ready to skip multiple states (e.g. created during an already-elapsed service period) lands in the
correct final state in one advance.

Realization runs (usagebased/realizationrun.go, usagebased/adapter/realizationrun.go)

A new RealizationRun entity tracks the metered quantity snapshot and credit totals for each collection window. Key invariants:

  • CollectionEnd is persisted on the run when it is created and must be read back from that record — never recomputed
  • CurrentRealizationRunID on the charge points to the active run; finalization clears it
  • SetOrClearCurrentRealizationRunID in the adapter handles both branches safely

Collection period semantics

  • InternalCollectionPeriod = 1 minute provides a stored_at grace window
  • StartFinalRealizationRun computes storedAtOffset = now - InternalCollectionPeriod and persists CollectionEnd = servicePeriod.To + profile.Collection.Interval
  • Events with stored_at >= storedAtOffset are excluded and may become eligible on a later advance

AdvanceCharges facade (charges/service/advance.go)

Customer-scoped orchestration: lists non-final usage-based charges, resolves the merged billing profile and feature meters once per customer, then calls usagebased.Service.AdvanceCharge per charge. CreditThenInvoice
settlement mode is explicitly rejected with a not-implemented error.

Auto-advance on create (charges/service/create.go)

After the create transaction commits, autoAdvanceCreatedCharges collects the unique customer IDs of any newly created credit-only usage-based charges and calls AdvanceCharges for each. This means a charge created inside an
active service period is returned from Create already in active status. The auto-advance runs outside the create transaction so that the persisted creation record survives even if the advance fails — a background worker
can retry.

Limitations

Credit Then invoice is not implemented yet

Summary by CodeRabbit

  • New Features

    • Advance usage-based charges per customer (credit-only flow supported)
    • Post-create auto-advancement for credit-only usage-based charges
    • List charges by customer and fetch usage-based charges with realizations
    • Persist realization runs and manage credit allocations with collection-period timing
  • Documentation

    • New user-invocable documentation describing charge lifecycles, state transitions, and testing guidance
  • Tests

    • Added comprehensive tests covering advance, lifecycle, and creation behaviors
  • Database

    • Added collection-end column for realization runs (migration included)

@coderabbitai

coderabbitai Bot commented Mar 17, 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: 0f4e286b-630f-425e-a38f-65e2a0d39f0f

📥 Commits

Reviewing files that changed from the base of the PR and between 593832e and 04aaba5.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (4)
  • openmeter/billing/charges/usagebased/handler.go
  • test/credits/mockledger.go
  • test/credits/sanity_test.go
  • tools/migrate/migrations/20260324140705_charges-run-collection-period.up.sql
✅ Files skipped from review due to trivial changes (1)
  • tools/migrate/migrations/20260324140705_charges-run-collection-period.up.sql
🚧 Files skipped from review as they are similar to previous changes (1)
  • openmeter/billing/charges/usagebased/handler.go

📝 Walkthrough

Walkthrough

Adds credit-only usage-based charge orchestration: realization runs, credit allocations, state machine advancement, post-create auto-advance, adapters/services for Get/Advance flows, feature-meter/rating integration, DB migration for collection window, and test scaffolding updates.

Changes

Cohort / File(s) Summary
Documentation
.agents/skills/charges/SKILL.md
New user-invocable skill documenting charges control flow, state-machine semantics, lifecycle rules, tests, and adapter gotchas.
Charge Service API & Flow
openmeter/billing/charges/service.go, openmeter/billing/charges/service/advance.go, openmeter/billing/charges/service/create.go, openmeter/billing/charges/service/helpers.go
Added AdvanceCharges API and implementation; post-create auto-advance for credit-only usage-based charges; feature-meter resolution and usage-based charge classification.
Usage-Based Service API & State Machine
openmeter/billing/charges/usagebased/service.go, .../service/service.go, .../service/triggers.go, .../service/statemachine.go, .../service/creditsonly.go, .../service/get.go, .../service/mutations.go, .../service/quantitysnapshot.go, .../service/rating.go, .../service/stdinvoice.go, .../service/statemachine.go
Exposed GetByID and AdvanceCharge; introduced StateMachine wrapper and CreditsOnlyStateMachine with lifecycle transitions; snapshot-based quantity, rating integration, realization-run creation/finalization, and invoice lifecycle stubs; added required dependencies (locker, feature, rating, streaming, overrides).
Usage-Based Adapter & Mappers
openmeter/billing/charges/usagebased/adapter.go, .../adapter/charge.go, .../adapter/mapper.go, .../adapter/realizationrun.go, .../adapter/creditallocation.go
Refactored adapter into sub-adapters (Charge, RealizationRun, CreditAllocation); added GetByID, UpdateStatus, UpdateCharge returning ChargeBase; new mappers for ChargeBase and realization-run base; implemented create/update for realization runs and bulk credit allocations.
Domain Types & Validation
openmeter/billing/charges/models/creditrealization/models.go, .../usagebased/charge.go, .../usagebased/realizationrun.go, .../usagebased/handler.go, .../usagebased/rating.go, .../usagebased/const.go, .../usagebased/errors.go, .../usagebased/statemachine.go
Introduced ChargeBase/Charge split with AdvanceAfter; realization-run domain, validation, IDs; handler AllocateCreditsInput and UnimplementedHandler; RateableIntent for rating; InternalCollectionPeriod constant; new validation errors and triggers/types for state machine.
Billing Integration & Locking
openmeter/billing/charges/service/invoice.go, openmeter/billing/charges/lock.go, openmeter/billing/service/stdinvoicestate.go
Routed usage-based invoice lifecycle hooks; added charge lock key helper; replaced local state-machine combinators with statelessx helpers.
Test Changes & Mocks
openmeter/billing/charges/service/base_test.go, .../advance_test.go, .../creditpurchase_test.go, .../invoicable_test.go, .../handlers_test.go, test/credits/mockledger.go, test/credits/sanity_test.go, test/billing/suite.go
Expanded test suites/init wiring for usage-based service and dependencies; renamed teardown hooks; added AdvanceCharges tests and lifecycle-focused tests; handler test callbacks and UnimplementedHandler embedding in mock ledger; profile edit callbacks aggregation.
State-machine Utilities
pkg/statelessx/actions.go, pkg/statelessx/conditions.go
Added composable ActionFn AllOf and BoolFn/Not helpers used by state-machine configurations.
DB Schema & Migrations
openmeter/ent/schema/chargesusagebased.go, tools/migrate/migrations/..._charges-run-collection-period.up.sql, ...down.sql
Added immutable collection_end column to charge_usage_based_runs and corresponding up/down migrations.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ChargesSvc as ChargeService
    participant MetaA as MetaAdapter
    participant UsageSvc as UsageBasedService
    participant FeatureSvc as FeatureService
    participant RatingSvc as RatingService
    participant Handler
    participant Adapter

    Client->>ChargesSvc: AdvanceCharges(customer)
    ChargesSvc->>ChargesSvc: validate input
    ChargesSvc->>MetaA: ListByCustomer(customer)
    MetaA-->>ChargesSvc: metas (filter usage-based)
    ChargesSvc->>UsageSvc: GetByMetas(metas, expand realizations)
    UsageSvc->>Adapter: GetByMetas
    Adapter-->>UsageSvc: usage-based charges
    ChargesSvc->>FeatureSvc: ResolveFeatureMeters(keys)
    FeatureSvc-->>ChargesSvc: feature meters
    ChargesSvc->>UsageSvc: AdvanceCharge(chargeID, override, meter)
    UsageSvc->>Adapter: GetByID(chargeID, expands)
    Adapter-->>UsageSvc: charge with realizations
    UsageSvc->>UsageSvc: build CreditsOnlyStateMachine
    UsageSvc->>RatingSvc: GenerateDetailedLines(snapshot quantity)
    RatingSvc-->>UsageSvc: totals/lines
    UsageSvc->>Handler: OnCollectionStarted / OnCollectionFinalized
    Handler-->>UsageSvc: credit allocations
    UsageSvc->>Adapter: CreateRealizationRun + CreateRunCreditAllocations
    Adapter-->>UsageSvc: persisted run + allocations
    UsageSvc->>Adapter: UpdateCharge(status/state)
    Adapter-->>UsageSvc: updated charge
    UsageSvc-->>ChargesSvc: advanced charge (or nil)
    ChargesSvc-->>Client: advanced charges list
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~55 minutes

Possibly related PRs

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.39% 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 'feat: usage based charges lifecycle' directly reflects the PR's primary objective—implementing the full lifecycle state machine for credit-only usage-based charges.

✏️ 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-charges-lifecycle

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 changed the base branch from main to feat/usage-based-charges March 17, 2026 07:37
@turip
turip force-pushed the feat/usage-based-charges branch from 91086aa to 14bf466 Compare March 17, 2026 16:43
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from 3edee44 to ce93c06 Compare March 18, 2026 05:59
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from ce93c06 to b7578f0 Compare March 18, 2026 08:47
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from b7578f0 to b5ca17e Compare March 18, 2026 09:00
Base automatically changed from feat/usage-based-charges to main March 18, 2026 16:10
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from b5ca17e to ab9b345 Compare March 19, 2026 06:20
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from ab9b345 to 53b86a4 Compare March 19, 2026 09:46
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from 53b86a4 to 73e1d91 Compare March 19, 2026 11:37
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from 73e1d91 to be402c2 Compare March 19, 2026 17:02
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from be402c2 to f9ed2d5 Compare March 19, 2026 17:06
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from f9ed2d5 to 8c4d723 Compare March 19, 2026 17:12
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from 8c4d723 to 6e2cd0d Compare March 20, 2026 08:07
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from 6e2cd0d to 0a8fa53 Compare March 20, 2026 14:05
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from 0a8fa53 to a5cf573 Compare March 22, 2026 07:20
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from a5cf573 to 413f856 Compare March 22, 2026 11:09
@turip turip added release-note/misc Miscellaneous changes area/billing labels Mar 22, 2026
@turip turip changed the title Feat/usage based charges lifecycle feat: usage based charges lifecycle Mar 22, 2026
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from c9a4b8d to 06965ce Compare March 22, 2026 18:14
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from 06965ce to 248e508 Compare March 22, 2026 18:14
@turip
turip marked this pull request as ready for review March 22, 2026 18:14
@turip
turip requested a review from a team as a code owner March 22, 2026 18:14
@turip
turip requested review from GAlexIHU and tothandras March 22, 2026 18:14

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

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/service/invoice.go (1)

68-86: ⚠️ Potential issue | 🔴 Critical

Missing switch cases for usage-based and credit-purchase charges.

The handleChargeEvent function only handles ChargeTypeFlatFee. Since you've wired up usageBased and creditPurchase processors in processorByType, any charge of those types will hit the default case and error with "unsupported charge type".

You'll need to add cases for meta.ChargeTypeUsageBased and meta.ChargeTypeCreditPurchase to actually invoke those processors.

🐛 Proposed fix to add missing switch cases
 	for _, lineWithCharge := range linesWithCharges {
 		switch lineWithCharge.Charge.Type() {
 		case meta.ChargeTypeFlatFee:
 			flatFee, err := lineWithCharge.Charge.AsFlatFeeCharge()
 			if err != nil {
 				return err
 			}

 			if processorByType.flatFee == nil {
 				return fmt.Errorf("flat fee payment post processor is not supported")
 			}

 			err = processorByType.flatFee(ctx, flatFee, lineWithCharge.StandardLineWithInvoiceHeader)
 			if err != nil {
 				return err
 			}
+		case meta.ChargeTypeUsageBased:
+			usageBased, err := lineWithCharge.Charge.AsUsageBasedCharge()
+			if err != nil {
+				return err
+			}
+
+			if processorByType.usageBased == nil {
+				return fmt.Errorf("usage based payment post processor is not supported")
+			}
+
+			err = processorByType.usageBased(ctx, usageBased, lineWithCharge.StandardLineWithInvoiceHeader)
+			if err != nil {
+				return err
+			}
+		case meta.ChargeTypeCreditPurchase:
+			creditPurchase, err := lineWithCharge.Charge.AsCreditPurchaseCharge()
+			if err != nil {
+				return err
+			}
+
+			if processorByType.creditPurchase == nil {
+				return fmt.Errorf("credit purchase payment post processor is not supported")
+			}
+
+			err = processorByType.creditPurchase(ctx, creditPurchase, lineWithCharge.StandardLineWithInvoiceHeader)
+			if err != nil {
+				return err
+			}
 		default:
 			return fmt.Errorf("unsupported charge type: %s", lineWithCharge.Charge.Type())
 		}
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/service/invoice.go` around lines 68 - 86, The
switch in handleChargeEvent currently only handles meta.ChargeTypeFlatFee and
returns an error for other types; add cases for meta.ChargeTypeUsageBased and
meta.ChargeTypeCreditPurchase that mirror the flat-fee flow: call the
appropriate type conversion methods (e.g., AsUsageBasedCharge and
AsCreditPurchaseCharge) on lineWithCharge.Charge, check errors, verify the
corresponding processor exists on processorByType (processorByType.usageBased
and processorByType.creditPurchase), then invoke the processor with ctx, the
typed charge, and lineWithCharge.StandardLineWithInvoiceHeader, returning any
error from the processor; keep the same error patterns/messages used for
flat-fee when a processor is missing or conversion fails.
🧹 Nitpick comments (7)
pkg/statelessx/actions.go (1)

13-24: Skip nil actions in this shared combinator.

Now that AllOf is reusable, a single optional callback left nil will panic the whole activation path. Treating nil entries as no-ops makes this helper a lot safer for future callers.

♻️ Suggested tweak
 func AllOf(fn ...ActionFn) ActionFn {
 	return func(ctx context.Context) error {
 		var outErr error
 
 		for _, f := range fn {
+			if f == nil {
+				continue
+			}
 			if err := f(ctx); err != nil {
 				outErr = errors.Join(outErr, err)
 			}
 		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/statelessx/actions.go` around lines 13 - 24, AllOf currently panics if
any entry in the variadic fn slice is nil; update the combinator (function AllOf
and its use of ActionFn) to treat nil actions as no-ops by skipping nil entries
in the for loop (i.e., if f == nil continue) so callers can pass optional
callbacks safely, while preserving the existing error-joining logic
(errors.Join) and return behavior.
openmeter/billing/charges/usagebased/service/quantitysnapshot.go (1)

68-75: Minor: Consider precision implications of NewFromFloat.

alpacadecimal.NewFromFloat(row.Value) converts a float64 to Decimal. For meter values that are large or have many decimal places, this conversion may introduce subtle precision artifacts since float64 can't represent all decimal values exactly.

If meter.MeterQueryRow.Value is always expected to be a "nice" number (e.g., counts), this is fine. But if high precision is needed, you might want to verify the source data or consider whether the meter API could return a string/decimal representation.

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

In `@openmeter/billing/charges/usagebased/service/quantitysnapshot.go` around
lines 68 - 75, summarizeMeterQueryRow currently builds the sum by calling
alpacadecimal.NewFromFloat(row.Value), which can introduce precision artifacts;
update summarizeMeterQueryRow to construct decimals from a string or exact
representation instead (e.g., use alpacadecimal.NewFromString on a string field
or formatted value) for meter.MeterQueryRow.Value, and handle/propagate any
conversion errors; if you cannot change the source type immediately, add a
conversion branch that prefers NewFromString when a string representation is
available and falls back to NewFromFloat only as a last resort, ensuring the
logic lives in summarizeMeterQueryRow and references meter.MeterQueryRow.Value
and alpacadecimal.NewFromString/NewFromFloat.
openmeter/billing/charges/usagebased/handler.go (1)

14-41: Looks good overall!

The AllocateCreditsInput struct and its validation are well-structured. The errors.Join pattern is idiomatic Go for aggregating multiple validation errors.

One small nit: Line 29's error message says "as of is required" but the field is actually named AllocateAt. Might be worth aligning the error message with the field name for clearer debugging.

 	if i.AllocateAt.IsZero() {
-		errs = append(errs, fmt.Errorf("as of is required"))
+		errs = append(errs, fmt.Errorf("allocate at is required"))
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/handler.go` around lines 14 - 41, Update
the validation error message in AllocateCreditsInput.Validate: replace the
message "as of is required" with one that references the actual field name
(e.g., "allocateAt is required" or "AllocateAt is required") so the error
clearly points to AllocateCreditsInput.AllocateAt when the timestamp is missing;
adjust the string in the Validate method where i.AllocateAt.IsZero() is checked.
.agents/skills/charges/SKILL.md (2)

285-286: Minor grammar fix.

The compound adjective "merged-profile-based" should use hyphens when modifying "collection-period resolution":

-- preserve merged-profile based collection-period resolution
+- preserve merged-profile-based collection-period resolution
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.agents/skills/charges/SKILL.md around lines 285 - 286, The phrase
"merged-profile based collection-period resolution" in the SKILL.md doc is
missing hyphens; update the compound adjective to "merged-profile-based
collection-period resolution" to correctly hyphenate the modifier, preserving
the existing bullet that also mentions `AdvanceCharge(...)` and the "nil means
noop" contract without changing meaning.

70-73: Minor wording nit.

The static analysis flagged "only supports CreditOnly" as repetitive. Since CreditOnly is an enum value, it's unavoidable, but you could rephrase slightly if it bothers you:

-- `usagebased.Service.AdvanceCharge(...)` only supports `CreditOnly`
+- `usagebased.Service.AdvanceCharge(...)` supports only the `CreditOnly` settlement mode

Totally optional - the meaning is clear either way.

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

In @.agents/skills/charges/SKILL.md around lines 70 - 73, Rephrase the
repetitive wording in the documentation: update the sentence that reads
"usagebased.Service.AdvanceCharge(...) only supports `CreditOnly`" to a less
repetitive form such as "usagebased.Service.AdvanceCharge(...) supports the
CreditOnly mode" (or "only supports the CreditOnly mode") in SKILL.md so the
meaning stays identical but avoids the awkward repetition of "only supports
`CreditOnly`".
openmeter/billing/charges/usagebased/service/triggers.go (1)

38-46: Switch pattern note.

The empty case productcatalog.CreditOnlySettlementMode: followed by code after the switch block is valid Go, but it might be slightly clearer to add a brief comment:

switch charge.Intent.SettlementMode {
case productcatalog.CreditOnlySettlementMode:
	// Handled below via credits-only state machine
case productcatalog.CreditThenInvoiceSettlementMode:
	return nil, models.NewGenericNotImplementedError(...)
default:
	return nil, fmt.Errorf(...)
}

This is purely a readability suggestion - the current code is correct.

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

In `@openmeter/billing/charges/usagebased/service/triggers.go` around lines 38 -
46, Add a brief clarifying comment inside the empty case for
productcatalog.CreditOnlySettlementMode in the switch on
charge.Intent.SettlementMode (in triggers.go) to indicate why it’s intentionally
empty and that the credits-only path is handled later (e.g., "Handled below via
credits-only state machine"); this preserves the current behavior while
improving readability for future maintainers.
openmeter/billing/charges/service/invoicable_test.go (1)

407-575: Worth pinning down the persisted CollectionEnd invariant here.

This flow keeps the billing profile fixed from #3.1 through #4.2, so it still passes if finalization accidentally recomputes the collection window from the latest profile instead of the value stored on the run. Changing the collection interval after the first realization starts would make that regression visible.

As per coding guidelines, **/*_test.go: Make sure the tests are comprehensive and cover the changes.

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

In `@openmeter/billing/charges/service/invoicable_test.go` around lines 407 - 575,
The test doesn't assert that the persisted CollectionEnd on the realization run
remains unchanged across advances/finalization (allowing a regression where
finalization recomputes it from a new billing profile); capture the initial
run.CollectionEnd (e.g. after obtaining currentRun in "#3.1") into a variable
like initialCollectionEnd and then assert equality against
usageBasedFromDB.Realizations[...] .CollectionEnd (or finalRun.CollectionEnd) in
subsequent subtests "#3.2", "#4.1" and "#4.2" to ensure the stored CollectionEnd
is invariant; update the assertions around currentRun.CollectionEnd and
finalRun.CollectionEnd to compare to initialCollectionEnd (using the same
UTC/time equality checks used elsewhere) so the test fails if finalization
recomputes the window.
🤖 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/service/advance_test.go`:
- Around line 34-36: TearDownTest in AdvanceChargesTestSuite must clear any test
clock overrides set by clock.SetTime (seen at lines 55 and 177); update
AdvanceChargesTestSuite.TearDownTest to reset the clock (e.g., call
clock.Reset(), or if that API is unavailable restore to real time with
clock.SetTime(time.Now())) before delegating to s.BaseSuite.TearDownTest() so
clock state cannot leak between tests.

In `@openmeter/billing/charges/usagebased/adapter/charge.go`:
- Around line 164-179: The loop assumes entities from query.All(ctx) line up
with input.Charges by index, causing mismatched ChargeBase; instead build a map
from input.Charges keyed by their ID (the same ID field used on DB entity), then
iterate entities and look up the corresponding meta using entity.ID (do not use
idx/input.Charges[idx]); call MapChargeBaseFromDB(entity, foundMeta) and
MapRealizationRunsFromDB(entity) as before, and return an error if a matching
meta is missing so KeyBy and subsequent steps get correctly paired data (refer
to MapChargeBaseFromDB, MapRealizationRunsFromDB, input.Charges, entities, and
KeyBy).

In `@openmeter/billing/charges/usagebased/realizationrun.go`:
- Around line 82-97: UpdateRealizationRunInput.Validate currently omits
validating the Totals field, allowing malformed totals to be persisted; modify
UpdateRealizationRunInput.Validate to call the same validation used elsewhere
for totals (e.g., invoke Totals.Validate or the equivalent Totals validation
helper) and append any returned error to errs (with context like "totals: %w")
before returning errors.Join(errs...), ensuring Totals are checked on updates
just like on create and in the persisted model.

In `@openmeter/billing/charges/usagebased/service/statemachine.go`:
- Around line 82-105: The external-storage callback passed into
stateless.NewStateMachineWithExternalStorage persists the new state before
activation side-effects run, causing failed activations (e.g.,
StartFinalRealizationRun invoked from OnActive) to be skipped on retry; update
the state machine flow so persistence only occurs after a successful ActivateCtx
(or call ActivateCtx on the persisted state before computing the next
transition). Concretely, modify the storage callback / surrounding
AdvanceUntilStateStable loop to either (A) defer calling
out.Adapter.UpdateStatus (usagebased.UpdateStatusInput / out.Charge.ChargeBase
assignment) until after ActivateCtx and any OnActive handlers complete
successfully, or (B) immediately invoke ActivateCtx for the currently persisted
state before checking CanFireCtx/FireCtx so idempotent activation retries run;
ensure newStatus.Validate() still runs and error handling remains intact.

In `@openmeter/ent/schema/chargesusagebased.go`:
- Around line 129-131: Make the collection_end field immutable so it cannot be
changed after creation: in the Ent schema where
field.Time("collection_end").Optional().Nillable() is declared (schema
ChargesUsageBased / the field named "collection_end"), add the Immutable()
modifier to the field declaration (e.g.,
field.Time("collection_end")....Immutable()) and re-run Ent codegen/migrations
so updates are rejected at the ORM layer.

---

Outside diff comments:
In `@openmeter/billing/charges/service/invoice.go`:
- Around line 68-86: The switch in handleChargeEvent currently only handles
meta.ChargeTypeFlatFee and returns an error for other types; add cases for
meta.ChargeTypeUsageBased and meta.ChargeTypeCreditPurchase that mirror the
flat-fee flow: call the appropriate type conversion methods (e.g.,
AsUsageBasedCharge and AsCreditPurchaseCharge) on lineWithCharge.Charge, check
errors, verify the corresponding processor exists on processorByType
(processorByType.usageBased and processorByType.creditPurchase), then invoke the
processor with ctx, the typed charge, and
lineWithCharge.StandardLineWithInvoiceHeader, returning any error from the
processor; keep the same error patterns/messages used for flat-fee when a
processor is missing or conversion fails.

---

Nitpick comments:
In @.agents/skills/charges/SKILL.md:
- Around line 285-286: The phrase "merged-profile based collection-period
resolution" in the SKILL.md doc is missing hyphens; update the compound
adjective to "merged-profile-based collection-period resolution" to correctly
hyphenate the modifier, preserving the existing bullet that also mentions
`AdvanceCharge(...)` and the "nil means noop" contract without changing meaning.
- Around line 70-73: Rephrase the repetitive wording in the documentation:
update the sentence that reads "usagebased.Service.AdvanceCharge(...) only
supports `CreditOnly`" to a less repetitive form such as
"usagebased.Service.AdvanceCharge(...) supports the CreditOnly mode" (or "only
supports the CreditOnly mode") in SKILL.md so the meaning stays identical but
avoids the awkward repetition of "only supports `CreditOnly`".

In `@openmeter/billing/charges/service/invoicable_test.go`:
- Around line 407-575: The test doesn't assert that the persisted CollectionEnd
on the realization run remains unchanged across advances/finalization (allowing
a regression where finalization recomputes it from a new billing profile);
capture the initial run.CollectionEnd (e.g. after obtaining currentRun in
"#3.1") into a variable like initialCollectionEnd and then assert equality
against usageBasedFromDB.Realizations[...] .CollectionEnd (or
finalRun.CollectionEnd) in subsequent subtests "#3.2", "#4.1" and "#4.2" to
ensure the stored CollectionEnd is invariant; update the assertions around
currentRun.CollectionEnd and finalRun.CollectionEnd to compare to
initialCollectionEnd (using the same UTC/time equality checks used elsewhere) so
the test fails if finalization recomputes the window.

In `@openmeter/billing/charges/usagebased/handler.go`:
- Around line 14-41: Update the validation error message in
AllocateCreditsInput.Validate: replace the message "as of is required" with one
that references the actual field name (e.g., "allocateAt is required" or
"AllocateAt is required") so the error clearly points to
AllocateCreditsInput.AllocateAt when the timestamp is missing; adjust the string
in the Validate method where i.AllocateAt.IsZero() is checked.

In `@openmeter/billing/charges/usagebased/service/quantitysnapshot.go`:
- Around line 68-75: summarizeMeterQueryRow currently builds the sum by calling
alpacadecimal.NewFromFloat(row.Value), which can introduce precision artifacts;
update summarizeMeterQueryRow to construct decimals from a string or exact
representation instead (e.g., use alpacadecimal.NewFromString on a string field
or formatted value) for meter.MeterQueryRow.Value, and handle/propagate any
conversion errors; if you cannot change the source type immediately, add a
conversion branch that prefers NewFromString when a string representation is
available and falls back to NewFromFloat only as a last resort, ensuring the
logic lives in summarizeMeterQueryRow and references meter.MeterQueryRow.Value
and alpacadecimal.NewFromString/NewFromFloat.

In `@openmeter/billing/charges/usagebased/service/triggers.go`:
- Around line 38-46: Add a brief clarifying comment inside the empty case for
productcatalog.CreditOnlySettlementMode in the switch on
charge.Intent.SettlementMode (in triggers.go) to indicate why it’s intentionally
empty and that the credits-only path is handled later (e.g., "Handled below via
credits-only state machine"); this preserves the current behavior while
improving readability for future maintainers.

In `@pkg/statelessx/actions.go`:
- Around line 13-24: AllOf currently panics if any entry in the variadic fn
slice is nil; update the combinator (function AllOf and its use of ActionFn) to
treat nil actions as no-ops by skipping nil entries in the for loop (i.e., if f
== nil continue) so callers can pass optional callbacks safely, while preserving
the existing error-joining logic (errors.Join) and return behavior.
🪄 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: ffb1f89a-51b5-441a-b96f-26537e5737b5

📥 Commits

Reviewing files that changed from the base of the PR and between 440a51f and 248e508.

⛔ Files ignored due to path filters (9)
  • 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/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 (48)
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/charges/lock/service.go
  • openmeter/billing/charges/meta/adapter.go
  • openmeter/billing/charges/meta/adapter/get.go
  • openmeter/billing/charges/models/creditrealization/models.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/service/advance.go
  • openmeter/billing/charges/service/advance_test.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/creditpurchase_test.go
  • openmeter/billing/charges/service/handlers_test.go
  • openmeter/billing/charges/service/helpers.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/service/invoice.go
  • openmeter/billing/charges/service/service.go
  • openmeter/billing/charges/usagebased/adapter.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/creditallocation.go
  • openmeter/billing/charges/usagebased/adapter/mapper.go
  • openmeter/billing/charges/usagebased/adapter/realizationrun.go
  • openmeter/billing/charges/usagebased/charge.go
  • openmeter/billing/charges/usagebased/const.go
  • openmeter/billing/charges/usagebased/errors.go
  • openmeter/billing/charges/usagebased/handler.go
  • openmeter/billing/charges/usagebased/rating.go
  • openmeter/billing/charges/usagebased/realizationrun.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/service/get.go
  • openmeter/billing/charges/usagebased/service/mutations.go
  • openmeter/billing/charges/usagebased/service/quantitysnapshot.go
  • openmeter/billing/charges/usagebased/service/rating.go
  • openmeter/billing/charges/usagebased/service/service.go
  • openmeter/billing/charges/usagebased/service/statemachine.go
  • openmeter/billing/charges/usagebased/service/stdinvoice.go
  • openmeter/billing/charges/usagebased/service/triggers.go
  • openmeter/billing/charges/usagebased/statemachine.go
  • openmeter/billing/service/stdinvoicestate.go
  • openmeter/ent/schema/chargesusagebased.go
  • openmeter/entitlement/metered/lateevents_test.go
  • openmeter/streaming/testutils/streaming.go
  • openmeter/streaming/testutils/streaming_test.go
  • pkg/statelessx/actions.go
  • pkg/statelessx/conditions.go
  • test/billing/suite.go
  • tools/migrate/migrations/20260322083731_add_usage_based_run_collection_end.down.sql
  • tools/migrate/migrations/20260322083731_add_usage_based_run_collection_end.up.sql

@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from 248e508 to 1549f0b Compare March 23, 2026 09:07

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

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/service/invoice.go (1)

68-86: ⚠️ Potential issue | 🔴 Critical

Missing switch case for usage-based charges — invoice events will fail!

The processorByType struct was extended with usageBased processor (line 31), and it's properly wired in handleStandardInvoiceUpdate. However, the handleChargeEvent switch only handles ChargeTypeFlatFee — there's no case for ChargeTypeUsageBased.

Any usage-based charge will fall through to the default case (line 85) and return "unsupported charge type: usage_based".

🐛 Add the missing switch case for usage-based charges
 		case meta.ChargeTypeFlatFee:
 			flatFee, err := lineWithCharge.Charge.AsFlatFeeCharge()
 			if err != nil {
 				return err
 			}

 			if processorByType.flatFee == nil {
 				return fmt.Errorf("flat fee payment post processor is not supported")
 			}

 			err = processorByType.flatFee(ctx, flatFee, lineWithCharge.StandardLineWithInvoiceHeader)
 			if err != nil {
 				return err
 			}
+		case meta.ChargeTypeUsageBased:
+			usageBased, err := lineWithCharge.Charge.AsUsageBasedCharge()
+			if err != nil {
+				return err
+			}
+
+			if processorByType.usageBased == nil {
+				return fmt.Errorf("usage based payment post processor is not supported")
+			}
+
+			err = processorByType.usageBased(ctx, usageBased, lineWithCharge.StandardLineWithInvoiceHeader)
+			if err != nil {
+				return err
+			}
 		default:
 			return fmt.Errorf("unsupported charge type: %s", lineWithCharge.Charge.Type())
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/service/invoice.go` around lines 68 - 86, The
switch in handleChargeEvent iterates linesWithCharges but only handles
meta.ChargeTypeFlatFee, causing UsageBased charges to hit the default error; add
a new case for meta.ChargeTypeUsageBased that calls
lineWithCharge.Charge.AsUsageBasedCharge(), checks processorByType.usageBased is
non-nil (return a descriptive error if nil), then invoke
processorByType.usageBased(ctx, usageBased,
lineWithCharge.StandardLineWithInvoiceHeader) and propagate any error
returned—mirroring the flat-fee branch's error handling and flow.
🧹 Nitpick comments (5)
openmeter/billing/charges/usagebased/adapter/creditallocation.go (1)

36-39: Consider adding context to the error for easier debugging.

The bulk create error doesn't include context about what was being created. This is pretty minor, but wrapping with context can help when troubleshooting.

💡 Optional: wrap error with context
 		dbEntities, err := tx.db.ChargeUsageBasedRunCreditAllocations.CreateBulk(creates...).Save(ctx)
 		if err != nil {
-			return nil, err
+			return nil, fmt.Errorf("creating credit allocations for run [id=%s]: %w", runID.ID, err)
 		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/adapter/creditallocation.go` around
lines 36 - 39, The error returned from
tx.db.ChargeUsageBasedRunCreditAllocations.CreateBulk(...).Save(ctx) lacks
context; update the error handling in that block (around CreateBulk/Save and
variable dbEntities) to wrap or annotate the original err with a descriptive
message—e.g., "creating ChargeUsageBasedRunCreditAllocations bulk"—using
fmt.Errorf("%s: %w", ...) or your project's error-wrapping utility before
returning.
.agents/skills/charges/SKILL.md (1)

286-286: Minor grammar fix.

Per the static analysis hint, "merged-profile based" should use a hyphen to form the compound adjective.

📝 Suggested fix
-- preserve merged-profile based collection-period resolution
+- preserve merged-profile-based collection-period resolution
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.agents/skills/charges/SKILL.md at line 286, Update the compound adjective
in the phrase "preserve merged-profile based collection-period resolution" to
use a hyphen: change the text "preserve merged-profile based collection-period
resolution" to "preserve merged-profile-based collection-period resolution" in
SKILL.md so the compound modifier "merged-profile-based" is grammatically
correct.
openmeter/billing/charges/usagebased/service/triggers.go (1)

38-46: Consider restructuring the switch for readability.

The empty case productcatalog.CreditOnlySettlementMode: followed by other cases that return errors is valid Go but reads a bit awkwardly. A small refactor could make the intent clearer.

♻️ Optional: Explicit early-exit pattern
-		switch charge.Intent.SettlementMode {
-		case productcatalog.CreditOnlySettlementMode:
-		case productcatalog.CreditThenInvoiceSettlementMode:
+		if charge.Intent.SettlementMode == productcatalog.CreditThenInvoiceSettlementMode {
 			return nil, models.NewGenericNotImplementedError(
 				fmt.Errorf("advancing usage based charge with settlement mode %s is not supported [charge_id=%s]", charge.Intent.SettlementMode, charge.ID),
 			)
-		default:
+		}
+
+		if charge.Intent.SettlementMode != productcatalog.CreditOnlySettlementMode {
 			return nil, fmt.Errorf("unsupported settlement mode %s [charge_id=%s]", charge.Intent.SettlementMode, charge.ID)
 		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/service/triggers.go` around lines 38 -
46, The switch over charge.Intent.SettlementMode is awkward due to an empty
case; update it to explicitly handle the supported CreditOnly path and return
nil there, and make the CreditThenInvoice case explicitly return
models.NewGenericNotImplementedError (using fmt.Errorf with the same message) so
intent is clear; keep the default branch returning fmt.Errorf for other
unsupported modes. Target the switch that references
charge.Intent.SettlementMode and the constants
productcatalog.CreditOnlySettlementMode and
productcatalog.CreditThenInvoiceSettlementMode and the error constructor
models.NewGenericNotImplementedError.
openmeter/billing/charges/service/create.go (1)

165-181: Consider adding observability for advancement failures.

When AdvanceCharges fails for a customer, the error is returned immediately, stopping advancement for remaining customers. This is fine for correctness, but you might want to log or emit metrics here so operators can see which customer/charge caused issues during the auto-advance step.

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

In `@openmeter/billing/charges/service/create.go` around lines 165 - 181, When
AdvanceCharges(ctx, charges.AdvanceChargesInput{Customer: custID}) returns an
error, augment the current behavior by emitting observability before returning:
call the service logger (e.g., s.logger or s.Log) and/or increment a metric
(e.g., s.metrics.Inc or s.recordError) with the customer identifier and the
error details, then return the original fmt.Errorf(...) as before; locate the
AdvanceCharges call and the surrounding loop over customerIDs and add the
logging/metric emit right inside the if err != nil block so operators can see
which custID caused the failure.
openmeter/billing/charges/usagebased/adapter/charge.go (1)

236-243: Consider using tx.GetByMetas for consistency.

Inside the TransactingRepo callback, you have access to tx *adapter but call a.GetByMetas (the outer adapter). While this works since entutils.TransactingRepo reuses the transaction from context, using tx.GetByMetas would be more explicit and consistent with patterns elsewhere in this file (e.g., tx.metaAdapter at line 225).

♻️ Optional fix
-		charges, err := a.GetByMetas(ctx, usagebased.GetByMetasInput{
+		charges, err := tx.GetByMetas(ctx, usagebased.GetByMetasInput{
			Namespace: input.ChargeID.Namespace,
			Charges:   meta.Charges{metas[0]},
			Expands:   input.Expands,
		})
🤖 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 236 -
243, Inside the TransactingRepo callback you call a.GetByMetas (outer adapter)
but should use the transaction-bound adapter to be explicit; change the call to
tx.GetByMetas so the query uses the same transaction instance (mirrors usage of
tx.metaAdapter and follows the file's pattern). Locate the block where charges,
err := a.GetByMetas(ctx, usagebased.GetByMetasInput{...}) is invoked and replace
the receiver a with tx, leaving the input and error handling unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@openmeter/billing/charges/service/invoice.go`:
- Around line 68-86: The switch in handleChargeEvent iterates linesWithCharges
but only handles meta.ChargeTypeFlatFee, causing UsageBased charges to hit the
default error; add a new case for meta.ChargeTypeUsageBased that calls
lineWithCharge.Charge.AsUsageBasedCharge(), checks processorByType.usageBased is
non-nil (return a descriptive error if nil), then invoke
processorByType.usageBased(ctx, usageBased,
lineWithCharge.StandardLineWithInvoiceHeader) and propagate any error
returned—mirroring the flat-fee branch's error handling and flow.

---

Nitpick comments:
In @.agents/skills/charges/SKILL.md:
- Line 286: Update the compound adjective in the phrase "preserve merged-profile
based collection-period resolution" to use a hyphen: change the text "preserve
merged-profile based collection-period resolution" to "preserve
merged-profile-based collection-period resolution" in SKILL.md so the compound
modifier "merged-profile-based" is grammatically correct.

In `@openmeter/billing/charges/service/create.go`:
- Around line 165-181: When AdvanceCharges(ctx,
charges.AdvanceChargesInput{Customer: custID}) returns an error, augment the
current behavior by emitting observability before returning: call the service
logger (e.g., s.logger or s.Log) and/or increment a metric (e.g., s.metrics.Inc
or s.recordError) with the customer identifier and the error details, then
return the original fmt.Errorf(...) as before; locate the AdvanceCharges call
and the surrounding loop over customerIDs and add the logging/metric emit right
inside the if err != nil block so operators can see which custID caused the
failure.

In `@openmeter/billing/charges/usagebased/adapter/charge.go`:
- Around line 236-243: Inside the TransactingRepo callback you call a.GetByMetas
(outer adapter) but should use the transaction-bound adapter to be explicit;
change the call to tx.GetByMetas so the query uses the same transaction instance
(mirrors usage of tx.metaAdapter and follows the file's pattern). Locate the
block where charges, err := a.GetByMetas(ctx, usagebased.GetByMetasInput{...})
is invoked and replace the receiver a with tx, leaving the input and error
handling unchanged.

In `@openmeter/billing/charges/usagebased/adapter/creditallocation.go`:
- Around line 36-39: The error returned from
tx.db.ChargeUsageBasedRunCreditAllocations.CreateBulk(...).Save(ctx) lacks
context; update the error handling in that block (around CreateBulk/Save and
variable dbEntities) to wrap or annotate the original err with a descriptive
message—e.g., "creating ChargeUsageBasedRunCreditAllocations bulk"—using
fmt.Errorf("%s: %w", ...) or your project's error-wrapping utility before
returning.

In `@openmeter/billing/charges/usagebased/service/triggers.go`:
- Around line 38-46: The switch over charge.Intent.SettlementMode is awkward due
to an empty case; update it to explicitly handle the supported CreditOnly path
and return nil there, and make the CreditThenInvoice case explicitly return
models.NewGenericNotImplementedError (using fmt.Errorf with the same message) so
intent is clear; keep the default branch returning fmt.Errorf for other
unsupported modes. Target the switch that references
charge.Intent.SettlementMode and the constants
productcatalog.CreditOnlySettlementMode and
productcatalog.CreditThenInvoiceSettlementMode and the error constructor
models.NewGenericNotImplementedError.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: fecfaa69-a022-4282-b6ba-d7fddc5b6076

📥 Commits

Reviewing files that changed from the base of the PR and between 248e508 and 1549f0b.

⛔ Files ignored due to path filters (8)
  • go.sum is excluded by !**/*.sum, !**/*.sum
  • 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/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (45)
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/charges/lock.go
  • openmeter/billing/charges/meta/adapter.go
  • openmeter/billing/charges/meta/adapter/get.go
  • openmeter/billing/charges/models/creditrealization/models.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/service/advance.go
  • openmeter/billing/charges/service/advance_test.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/creditpurchase_test.go
  • openmeter/billing/charges/service/handlers_test.go
  • openmeter/billing/charges/service/helpers.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/service/invoice.go
  • openmeter/billing/charges/service/service.go
  • openmeter/billing/charges/usagebased/adapter.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/creditallocation.go
  • openmeter/billing/charges/usagebased/adapter/mapper.go
  • openmeter/billing/charges/usagebased/adapter/realizationrun.go
  • openmeter/billing/charges/usagebased/charge.go
  • openmeter/billing/charges/usagebased/const.go
  • openmeter/billing/charges/usagebased/errors.go
  • openmeter/billing/charges/usagebased/handler.go
  • openmeter/billing/charges/usagebased/rating.go
  • openmeter/billing/charges/usagebased/realizationrun.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/service/get.go
  • openmeter/billing/charges/usagebased/service/mutations.go
  • openmeter/billing/charges/usagebased/service/quantitysnapshot.go
  • openmeter/billing/charges/usagebased/service/rating.go
  • openmeter/billing/charges/usagebased/service/service.go
  • openmeter/billing/charges/usagebased/service/statemachine.go
  • openmeter/billing/charges/usagebased/service/stdinvoice.go
  • openmeter/billing/charges/usagebased/service/triggers.go
  • openmeter/billing/charges/usagebased/statemachine.go
  • openmeter/billing/service/stdinvoicestate.go
  • openmeter/ent/schema/chargesusagebased.go
  • pkg/statelessx/actions.go
  • pkg/statelessx/conditions.go
  • test/billing/suite.go
  • tools/migrate/migrations/20260323090205_charges-run-collection-period.down.sql
  • tools/migrate/migrations/20260323090205_charges-run-collection-period.up.sql
✅ Files skipped from review due to trivial changes (11)
  • openmeter/billing/charges/usagebased/const.go
  • tools/migrate/migrations/20260323090205_charges-run-collection-period.down.sql
  • openmeter/billing/charges/service/service.go
  • tools/migrate/migrations/20260323090205_charges-run-collection-period.up.sql
  • openmeter/billing/charges/models/creditrealization/models.go
  • openmeter/ent/schema/chargesusagebased.go
  • pkg/statelessx/conditions.go
  • openmeter/billing/charges/usagebased/service/rating.go
  • openmeter/billing/charges/usagebased/errors.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/statemachine.go
🚧 Files skipped from review as they are similar to previous changes (14)
  • openmeter/billing/charges/service/helpers.go
  • test/billing/suite.go
  • openmeter/billing/charges/meta/adapter/get.go
  • pkg/statelessx/actions.go
  • openmeter/billing/charges/usagebased/service/stdinvoice.go
  • openmeter/billing/charges/service/advance.go
  • openmeter/billing/charges/usagebased/adapter/realizationrun.go
  • openmeter/billing/charges/usagebased/service/quantitysnapshot.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/handler.go
  • openmeter/billing/charges/usagebased/service/service.go
  • openmeter/billing/charges/usagebased/realizationrun.go
  • openmeter/billing/service/stdinvoicestate.go
  • openmeter/billing/charges/usagebased/adapter/mapper.go

@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from 1549f0b to 593832e Compare March 24, 2026 14:25
@turip
turip force-pushed the feat/usage-based-charges-lifecycle branch from 593832e to 04aaba5 Compare March 24, 2026 14:29

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

♻️ Duplicate comments (1)
openmeter/billing/charges/usagebased/service/statemachine.go (1)

181-220: ⚠️ Potential issue | 🔴 Critical

Activate the current state before checking TriggerNext.

AdvanceUntilStateStable only runs OnActive for states it just transitioned into. Charges that already start in created, active, or waiting_for_collection never refresh AdvanceAfter, so a future-dated charge can sit in created without a wake-up timestamp. It also skips retrying started / processing entry work after a partial advance. Please activate + persist the current state once before the loop, then evaluate the next trigger.

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

In `@openmeter/billing/charges/usagebased/service/statemachine.go` around lines
181 - 220, AdvanceUntilStateStable must Activate the current state before
entering the loop so entry work (OnActive/AdvanceAfter) runs for charges that
start already in created/active/waiting_for_collection and to retry
started/processing entry work; call s.FireAndActivate(ctx, /* no trigger */) or
directly call s.StateMachine.ActivateCtx(ctx) (use the existing FireAndActivate
helper only when firing a trigger) and persist the resulting s.Charge via
s.Adapter.UpdateCharge(ctx, s.Charge.ChargeBase) once before the for-loop, then
proceed to the existing CanFireCtx(ctx, usagebased.TriggerNext) loop and use
FireAndActivate for subsequent TriggerNext transitions as currently implemented.
🧹 Nitpick comments (4)
openmeter/billing/charges/usagebased/charge.go (1)

69-77: Consider validating Realizations in Charge.Validate().

Charge adds a Realizations RealizationRuns field, but Validate() only delegates to ChargeBase. Since RealizationRuns has its own Validate() method, you might want to call it here for completeness. Though if realizations are always validated at the adapter boundary, this could be intentional.

🛡️ Optional defensive validation
 func (c Charge) Validate() error {
 	var errs []error

 	if err := c.ChargeBase.Validate(); err != nil {
 		errs = append(errs, fmt.Errorf("charge base: %w", err))
 	}

+	if err := c.Realizations.Validate(); err != nil {
+		errs = append(errs, fmt.Errorf("realizations: %w", err))
+	}
+
 	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 69 - 77, The
Charge.Validate method currently only validates ChargeBase; add defensive
validation for the Realizations field by calling Realizations.Validate() (on the
RealizationRuns type) and append any returned error to the errs slice (e.g.,
wrap with fmt.Errorf("realizations: %w", err)); ensure you handle a nil/empty
Realizations safely and continue to use errors.Join(errs...) as the aggregate
return.
test/credits/sanity_test.go (1)

141-143: Minor: Consider aligning with testify/suite naming convention.

The testify/suite package documents TearDownTest (CamelCase "Down") as the teardown hook. This file uses TeardownTest. While both may work depending on how the base suite is configured, aligning with the canonical name improves consistency with the base test changes mentioned in the PR.

🔧 Optional rename
-func (s *CreditsTestSuite) TeardownTest() {
+func (s *CreditsTestSuite) TearDownTest() {
 	s.Ledger.Reset()
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/credits/sanity_test.go` around lines 141 - 143, Rename the teardown
method on type CreditsTestSuite from TeardownTest to the testify/suite canonical
TearDownTest to match the base suite hook; update the method declaration
(receiver remains s *CreditsTestSuite) and any callers or references to use
TearDownTest so the suite teardown runs consistently with testify/suite
expectations.
openmeter/billing/charges/service/advance_test.go (1)

38-215: Would add the “advance until stable” happy path here.

A case where clock.SetTime() is already past the service period end and AdvanceCharges drives a credit-only charge all the way to final in one call would cover the main new behavior in this PR. Right now the suite mostly exercises noop/unsupported branches, so the multi-hop lifecycle loop can still regress pretty quietly.

As per coding guidelines, **/*_test.go: Make sure the tests are comprehensive and cover the changes.

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

In `@openmeter/billing/charges/service/advance_test.go` around lines 38 - 215, Add
a new “advance until stable” test to AdvanceChargesTestSuite that creates a
credit-only usage-based charge (use SetupApiRequestsTotalFeature to get
featureKey and s.createMockChargeIntent with
productcatalog.CreditOnlySettlementMode), set clock to a time after the
servicePeriod.To (use clock.SetTime), call s.Charges.AdvanceCharges(ctx,
charges.AdvanceChargesInput{Customer: cust.GetID()}), and assert no error and
that the returned/DB-fetched usage-based charge (use
createdCharges[].AsUsageBasedCharge() and
s.mustGetChargeByID(...).AsUsageBasedCharge()) reached the final state (compare
meta.ChargeStatus(usageBased.Status) == meta.ChargeStatusFinal and/or
State.AdvanceAfter nil as appropriate); this covers the multi-hop lifecycle
driving credit-only charges to final in one call.
openmeter/billing/charges/usagebased/service/statemachine.go (1)

162-165: Bubble up AddTo failures here.

GetCollectionPeriodEnd already returns an error, but the interval math error is dropped. Failing fast is a lot safer than silently continuing with a bad collection boundary.

Possible tweak
 func (s *StateMachine) GetCollectionPeriodEnd(_ context.Context) (time.Time, error) {
 	collectionPeriod := s.CustomerOverride.MergedProfile.WorkflowConfig.Collection.Interval
-	collectionPeriodEnd, _ := collectionPeriod.AddTo(s.Charge.Intent.ServicePeriod.To)
-	return collectionPeriodEnd, nil
+	collectionPeriodEnd, err := collectionPeriod.AddTo(s.Charge.Intent.ServicePeriod.To)
+	if err != nil {
+		return time.Time{}, fmt.Errorf("add collection interval: %w", err)
+	}
+	return collectionPeriodEnd, nil
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/billing/charges/usagebased/service/statemachine.go` around lines
162 - 165, The GetCollectionPeriodEnd method on StateMachine drops the error
returned by collectionPeriod.AddTo; modify GetCollectionPeriodEnd to check the
error from collectionPeriod.AddTo (called on
CustomerOverride.MergedProfile.WorkflowConfig.Collection.Interval with
s.Charge.Intent.ServicePeriod.To), and if non-nil return the zero time and that
error instead of ignoring it so callers receive the failure.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.agents/skills/charges/SKILL.md:
- Around line 149-155: The two AdvanceAfter descriptions are reversed: swap the
targets so that the transition `created -> active` (guarded by
IsInsideServicePeriod()) sets AdvanceAfter to servicePeriod.From (wait until
service start), and the transition `active -> active.final_realization.started`
(guarded by IsAfterServicePeriod()) sets AdvanceAfter to servicePeriod.To (wait
until service end); update those bullet descriptions for `AdvanceAfter`
accordingly so the guards and state names (`created -> active`, `active ->
active.final_realization.started`, IsInsideServicePeriod(),
IsAfterServicePeriod(), and AdvanceAfter) match the lifecycle tests.
- Around line 109-125: The documentation references a stale lock helper name;
update the Usage-Based Advance Flow section to point to the correct symbol by
replacing `charges/lock.NewChargeKey(...)` with
`openmeter/billing/charges/lock.NewLockKeyForCharge(...)` and optionally note it
returns the charge-scoped lock key used with `*lockr.Locker`, so readers are
directed to the current `NewLockKeyForCharge` implementation instead of the
removed `NewChargeKey`.

In `@openmeter/billing/charges/service/advance.go`:
- Around line 47-50: The prefetch call to s.usageBasedService.GetByMetas is
requesting meta.ExpandRealizations (via meta.Expands{meta.ExpandRealizations})
which causes unnecessary DB work on a hot path; remove the realization expansion
from the GetByMetas call (i.e., stop passing meta.ExpandRealizations in the
Expands argument and pass an empty/nil expands value) because AdvanceCharge
reloads the charge with realizations when needed; update the usageBasedCharges
fetch (referencing s.usageBasedService.GetByMetas and usageBasedChargeMetas) to
exclude meta.ExpandRealizations to eliminate the extra expansion cost.
- Around line 22-85: The current code wraps the whole batch in transaction.Run
(transaction.Run) which keeps a single DB transaction open across feature
resolution and multiple AdvanceCharge calls (s.usageBasedService.AdvanceCharge),
causing long-lived transactions and global rollback on any per-charge failure;
change the flow to do all read-only work outside a transaction (call
s.metaAdapter.ListByCustomer, s.billingService.GetCustomerOverride,
s.usageBasedService.GetByMetas, s.resolveFeatureMeters) and then iterate
usageBasedCharges and perform each advance in its own lifecycle/transaction
(call s.usageBasedService.AdvanceCharge per charge, or wrap each AdvanceCharge
call in a short transaction.Run if AdvanceCharge is not transactional),
collecting successful advanced charges into advancedCharges and handling
per-charge errors without aborting the entire batch. Ensure references: remove
the outer transaction.Run, keep usageBasedChargeMetas, customerOverride,
featureMeters resolution, and call AdvanceCharge per charge individually.

In `@openmeter/billing/charges/service/create.go`:
- Around line 141-172: autoAdvanceCreatedCharges currently groups by customer
and calls AdvanceCharges for the whole customer, which can fail if that customer
has non-credit-only usage-based charges; instead restrict auto-advance to only
the freshly created credit-only usage-based charges: in
autoAdvanceCreatedCharges (and where you call s.AdvanceCharges) collect the
specific charge identifiers (or charge objects) for the created credit-only
usage-based charges you discovered and pass those to AdvanceCharges (or add a
new AdvanceChargesInput field to accept charge IDs), or modify the auto-advance
path to skip any charges whose settlement mode is not
productcatalog.CreditOnlySettlementMode; ensure you reference
autoAdvanceCreatedCharges, the created variable, and the AdvanceCharges call so
the change scopes advancement to just the new credit-only charges rather than
the entire customer.

In `@openmeter/billing/charges/service/invoicable_test.go`:
- Around line 407-480: Add an extra AddSimpleEvent in this subtest with
stored_at exactly equal to firstStoredAtOffset to assert the cutoff is
exclusive: call s.MockStreamingConnector.AddSimpleEvent(meterSlug, <new-id>,
<some event time>,
streamingtestutils.WithStoredAt(firstStoredAtOffset.AsTime())) inside the same
test before advancing the charge; keep all subsequent assertions unchanged
(expect only the earlier events to be considered, startedCallbacks length and
AmountToAllocate remain the same) to catch any accidental <= vs < logic errors
in currentRun allocation filtering.

In `@openmeter/billing/charges/service/invoice.go`:
- Around line 34-55: handleChargeEvent currently only dispatches flat-fee
charges so usage-based handlers never run; update handleChargeEvent to switch on
the charge type (use meta.ChargeTypeFlatFee, meta.ChargeTypeUsageBased,
meta.ChargeTypeCreditPurchase) and invoke the corresponding processorByType
field (flatFee, usageBased, creditPurchase) for each case, returning any error
the invoked handler produces and preserving the existing fallback for
unsupported types; refer to the processorByType struct and functions
s.handleChargeEvent, s.flatFeeService.*, s.usageBasedService.*, and the
creditPurchase processor field when making the change.

In `@openmeter/billing/charges/usagebased/adapter/charge.go`:
- Around line 224-248: The callback in entutils.TransactingRepo uses the
transaction-aware adapter variable tx for the first read
(tx.metaAdapter.GetByIDs) but then calls a.GetByMetas(...) which bypasses the
transaction; change that call to tx.GetByMetas(...) so both reads
(metaAdapter.GetByIDs and GetByMetas) execute within the same transaction
boundary and return the single charge as before.

In `@openmeter/billing/charges/usagebased/service/creditsonly.go`:
- Around line 160-191: The credit allocation (allocateCredits) is performed
before the realization run checkpoint is durably advanced
(createNewRealizationRun), allowing duplicate allocations on retry; make the
allocation durable/idempotent by moving the allocation into the same atomic
boundary as the run creation or by using a cross-call idempotency key that is
persisted with the realization run. Concretely: either (A) change
createNewRealizationRun to accept allocation details and perform the credit
adjustments inside the same DB transaction so allocateCredits is not called
separately, or (B) generate and pass a unique idempotency key from the calling
code into allocateCredits and include that key in the created realization run
(createNewRealizationRun) and in the credit allocation records, and modify
allocateCredits to be idempotent when the same key is seen; update both
realization paths (including the block that calls allocateCredits and the block
around lines ~225-258) to use the same approach.

In `@openmeter/billing/charges/usagebased/service/quantitysnapshot.go`:
- Around line 25-38: The Validate method on snapshotQuantityInput currently only
checks Meter but must also validate the Feature and group-by filters used later;
update snapshotQuantityInput.Validate() to call/ reuse the existing validator
for FeatureMeter (if present) or explicitly ensure in.FeatureMeter.Feature is
non-nil and that Feature.Namespace is non-empty, and validate
MeterGroupByFilters (e.g., non-nil/valid structure) so snapshotQuantity (which
reads in.FeatureMeter.Feature.Namespace and MeterGroupByFilters) fails fast with
a clear error instead of proceeding with partial data.

---

Duplicate comments:
In `@openmeter/billing/charges/usagebased/service/statemachine.go`:
- Around line 181-220: AdvanceUntilStateStable must Activate the current state
before entering the loop so entry work (OnActive/AdvanceAfter) runs for charges
that start already in created/active/waiting_for_collection and to retry
started/processing entry work; call s.FireAndActivate(ctx, /* no trigger */) or
directly call s.StateMachine.ActivateCtx(ctx) (use the existing FireAndActivate
helper only when firing a trigger) and persist the resulting s.Charge via
s.Adapter.UpdateCharge(ctx, s.Charge.ChargeBase) once before the for-loop, then
proceed to the existing CanFireCtx(ctx, usagebased.TriggerNext) loop and use
FireAndActivate for subsequent TriggerNext transitions as currently implemented.

---

Nitpick comments:
In `@openmeter/billing/charges/service/advance_test.go`:
- Around line 38-215: Add a new “advance until stable” test to
AdvanceChargesTestSuite that creates a credit-only usage-based charge (use
SetupApiRequestsTotalFeature to get featureKey and s.createMockChargeIntent with
productcatalog.CreditOnlySettlementMode), set clock to a time after the
servicePeriod.To (use clock.SetTime), call s.Charges.AdvanceCharges(ctx,
charges.AdvanceChargesInput{Customer: cust.GetID()}), and assert no error and
that the returned/DB-fetched usage-based charge (use
createdCharges[].AsUsageBasedCharge() and
s.mustGetChargeByID(...).AsUsageBasedCharge()) reached the final state (compare
meta.ChargeStatus(usageBased.Status) == meta.ChargeStatusFinal and/or
State.AdvanceAfter nil as appropriate); this covers the multi-hop lifecycle
driving credit-only charges to final in one call.

In `@openmeter/billing/charges/usagebased/charge.go`:
- Around line 69-77: The Charge.Validate method currently only validates
ChargeBase; add defensive validation for the Realizations field by calling
Realizations.Validate() (on the RealizationRuns type) and append any returned
error to the errs slice (e.g., wrap with fmt.Errorf("realizations: %w", err));
ensure you handle a nil/empty Realizations safely and continue to use
errors.Join(errs...) as the aggregate return.

In `@openmeter/billing/charges/usagebased/service/statemachine.go`:
- Around line 162-165: The GetCollectionPeriodEnd method on StateMachine drops
the error returned by collectionPeriod.AddTo; modify GetCollectionPeriodEnd to
check the error from collectionPeriod.AddTo (called on
CustomerOverride.MergedProfile.WorkflowConfig.Collection.Interval with
s.Charge.Intent.ServicePeriod.To), and if non-nil return the zero time and that
error instead of ignoring it so callers receive the failure.

In `@test/credits/sanity_test.go`:
- Around line 141-143: Rename the teardown method on type CreditsTestSuite from
TeardownTest to the testify/suite canonical TearDownTest to match the base suite
hook; update the method declaration (receiver remains s *CreditsTestSuite) and
any callers or references to use TearDownTest so the suite teardown runs
consistently with testify/suite expectations.
🪄 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: 405468f8-f4bd-4bd9-b832-8f793ac09128

📥 Commits

Reviewing files that changed from the base of the PR and between 1549f0b and 593832e.

⛔ Files ignored due to path filters (7)
  • 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/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (47)
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/charges/lock.go
  • openmeter/billing/charges/meta/adapter.go
  • openmeter/billing/charges/meta/adapter/get.go
  • openmeter/billing/charges/models/creditrealization/models.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/service/advance.go
  • openmeter/billing/charges/service/advance_test.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/creditpurchase_test.go
  • openmeter/billing/charges/service/handlers_test.go
  • openmeter/billing/charges/service/helpers.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/service/invoice.go
  • openmeter/billing/charges/service/service.go
  • openmeter/billing/charges/usagebased/adapter.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/creditallocation.go
  • openmeter/billing/charges/usagebased/adapter/mapper.go
  • openmeter/billing/charges/usagebased/adapter/realizationrun.go
  • openmeter/billing/charges/usagebased/charge.go
  • openmeter/billing/charges/usagebased/const.go
  • openmeter/billing/charges/usagebased/errors.go
  • openmeter/billing/charges/usagebased/handler.go
  • openmeter/billing/charges/usagebased/rating.go
  • openmeter/billing/charges/usagebased/realizationrun.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/service/get.go
  • openmeter/billing/charges/usagebased/service/mutations.go
  • openmeter/billing/charges/usagebased/service/quantitysnapshot.go
  • openmeter/billing/charges/usagebased/service/rating.go
  • openmeter/billing/charges/usagebased/service/service.go
  • openmeter/billing/charges/usagebased/service/statemachine.go
  • openmeter/billing/charges/usagebased/service/stdinvoice.go
  • openmeter/billing/charges/usagebased/service/triggers.go
  • openmeter/billing/charges/usagebased/statemachine.go
  • openmeter/billing/service/stdinvoicestate.go
  • openmeter/ent/schema/chargesusagebased.go
  • pkg/statelessx/actions.go
  • pkg/statelessx/conditions.go
  • test/billing/suite.go
  • test/credits/mockledger.go
  • test/credits/sanity_test.go
  • tools/migrate/migrations/20260324140705_charges-run-collection-period.down.sql
  • tools/migrate/migrations/20260324140705_charges-run-collection-period.up.sql
✅ Files skipped from review due to trivial changes (8)
  • tools/migrate/migrations/20260324140705_charges-run-collection-period.down.sql
  • openmeter/billing/charges/lock.go
  • pkg/statelessx/actions.go
  • openmeter/billing/charges/usagebased/errors.go
  • pkg/statelessx/conditions.go
  • openmeter/billing/charges/usagebased/service/stdinvoice.go
  • tools/migrate/migrations/20260324140705_charges-run-collection-period.up.sql
  • openmeter/billing/charges/usagebased/service/triggers.go
🚧 Files skipped from review as they are similar to previous changes (12)
  • openmeter/billing/charges/usagebased/const.go
  • openmeter/billing/charges/service/service.go
  • test/billing/suite.go
  • openmeter/billing/charges/service/handlers_test.go
  • openmeter/billing/charges/meta/adapter/get.go
  • openmeter/ent/schema/chargesusagebased.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/usagebased/adapter/creditallocation.go
  • openmeter/billing/charges/usagebased/adapter/realizationrun.go
  • openmeter/billing/charges/usagebased/rating.go
  • openmeter/billing/charges/usagebased/adapter.go
  • openmeter/billing/charges/usagebased/adapter/mapper.go

Comment thread .agents/skills/charges/SKILL.md Resolved
Comment thread .agents/skills/charges/SKILL.md Resolved
Comment on lines +224 to +248
return entutils.TransactingRepo(ctx, a, func(ctx context.Context, tx *adapter) (usagebased.Charge, error) {
metas, err := tx.metaAdapter.GetByIDs(ctx, meta.GetByIDsInput{
Namespace: input.ChargeID.Namespace,
ChargeIDs: []string{input.ChargeID.ID},
})
if err != nil {
return usagebased.Charge{}, err
}
if len(metas) != 1 {
return usagebased.Charge{}, fmt.Errorf("expected 1 meta, got %d", len(metas))
}

charges, err := a.GetByMetas(ctx, usagebased.GetByMetasInput{
Namespace: input.ChargeID.Namespace,
Charges: meta.Charges{metas[0]},
Expands: input.Expands,
})
if err != nil {
return usagebased.Charge{}, err
}
if len(charges) != 1 {
return usagebased.Charge{}, fmt.Errorf("expected 1 charge, got %d", len(charges))
}

return charges[0], nil

@coderabbitai coderabbitai Bot Mar 24, 2026 •

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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== TransactingRepo implementation ==="
rg -n -C4 'func .*TransactingRepo' pkg/framework

echo
echo "=== usage-based adapter GetByID/GetByMetas ==="
rg -n -C4 'func \(a \*adapter\) GetBy(ID|Metas)\b' openmeter/billing/charges/usagebased/adapter/charge.go

Repository: openmeterio/openmeter

Length of output: 1871


Use the transaction-aware adapter for the second read inside the callback.

Right now, GetByID opens a transaction and passes a transaction-aware adapter (tx) to the callback, but then calls a.GetByMetas(...) on the original adapter instead. This bypasses the transaction and runs the query outside its scope. Switch to tx.GetByMetas(...) so both reads stay within the same transaction boundary.

Change
-		charges, err := a.GetByMetas(ctx, usagebased.GetByMetasInput{
+		charges, err := tx.GetByMetas(ctx, usagebased.GetByMetasInput{
 			Namespace: input.ChargeID.Namespace,
 			Charges:   meta.Charges{metas[0]},
 			Expands:   input.Expands,
 		})
🤖 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 224 -
248, The callback in entutils.TransactingRepo uses the transaction-aware adapter
variable tx for the first read (tx.metaAdapter.GetByIDs) but then calls
a.GetByMetas(...) which bypasses the transaction; change that call to
tx.GetByMetas(...) so both reads (metaAdapter.GetByIDs and GetByMetas) execute
within the same transaction boundary and return the single charge as before.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be fixed later.

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.

@turip, got it! Would you like me to open a follow-up GitHub issue to track the fix (a.GetByMetas → tx.GetByMetas inside GetByID's TransactingRepo callback)? Happy to do that so it doesn't get lost.


🧠 Learnings used
Learnt from: turip
Repo: openmeterio/openmeter PR: 3943
File: openmeter/billing/charges/service.go:75-98
Timestamp: 2026-03-14T21:06:40.124Z
Learning: In openmeter/billing/charges/service.go (Go, billing charges domain), `GetByIDsInput` intentionally uses `[]string` for `ChargeIDs` (not `[]meta.ChargeID`) because it already has a top-level `Namespace` field. This enforces a single-namespace batch lookup — `meta.ChargeID` is a NamespacedID (namespace + ID), so using it per-element would redundantly duplicate the namespace.

Learnt from: turip
Repo: openmeterio/openmeter PR: 3943
File: openmeter/billing/charges/flatfee/service/payment.go:15-50
Timestamp: 2026-03-14T21:01:48.475Z
Learning: In the OpenMeter billing charges flatfee service (openmeter/billing/charges/flatfee/service/payment.go), the invoicing lifecycle callbacks (e.g., PostPaymentAuthorized, PostPaymentSettled) are protected against concurrent execution by customer-scoped locks applied at the invoicing callback layer. In-memory state checks (e.g., checking charge.State.Payment != nil before authorizing) are therefore safe and do not require additional durable/atomic guards in the adapter layer.

Learnt from: turip
Repo: openmeterio/openmeter PR: 3952
File: openmeter/billing/charges/service/invoicable_test.go:263-346
Timestamp: 2026-03-17T16:54:36.947Z
Learning: In `openmeter/billing/charges/service/invoicable_test.go`, `TestUsageBasedPartialCreditRealizations` is intentionally a scaffolding stub. It only covers create/get and gathering line linkage for now; the invoicing and credit realization assertions will be filled in a future PR once the underlying usage-based charge lifecycle is fully implemented.

Learnt from: GAlexIHU
Repo: openmeterio/openmeter PR: 2945
File: pkg/framework/lockr/locker.go:89-126
Timestamp: 2025-06-05T11:34:14.035Z
Learning: The lockr package's transaction detection using `transaction_timestamp() != statement_timestamp()` correctly handles nested transactions and subtransactions, as proven by the test "Should be able to acquire same lock in sub-transaction" in pkg/framework/lockr/locker_test.go.

Learnt from: turip
Repo: openmeterio/openmeter PR: 3943
File: openmeter/billing/charges/flatfee/service/payment.go:54-89
Timestamp: 2026-03-14T21:01:52.959Z
Learning: In the openmeter/billing/charges/flatfee/service/payment.go file (Go, billing charges domain), the PostPaymentAuthorized and PostPaymentSettled methods are invoked exclusively from invoicing callbacks that are locked on a customer scope. This customer-scoped lock prevents concurrent execution for the same charge, so the in-memory payment status check (e.g., payment.StatusAuthorized) before persisting the settled state is safe and does not create a race/double-settlement window.

Learnt from: CR
Repo: openmeterio/openmeter PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-23T14:11:51.048Z
Learning: Applies to openmeter/**/!(ent)/**.go : Use the layered service/adapter pattern for domain packages under `openmeter/`

Learnt from: turip
Repo: openmeterio/openmeter PR: 3851
File: openmeter/billing/stdinvoiceline.go:399-405
Timestamp: 2026-02-11T09:32:00.452Z
Learning: In `openmeter/billing/stdinvoiceline.go`, `StandardLine.UsageBased` is currently a pointer (`*UsageBasedLine`) but will be refactored to a non-pointer member in the future. This architectural change will eliminate nil-check concerns in methods like `SetPrice`.

Learnt from: chrisgacsal
Repo: openmeterio/openmeter PR: 2699
File: openmeter/productcatalog/planaddon/service/service_test.go:210-211
Timestamp: 2025-04-21T08:32:31.689Z
Learning: In `productcatalog.UsageBasedRateCard`, the `BillingCadence` field is a non-pointer `isodate.Period`, while in `productcatalog.FlatFeeRateCard`, `BillingCadence` is a pointer type (`*isodate.Period`). This means `MonthPeriod` should be used directly for `UsageBasedRateCard` (not `&MonthPeriod`).

Learnt from: turip
Repo: openmeterio/openmeter PR: 3943
File: openmeter/billing/charges/service/invoice.go:19-24
Timestamp: 2026-03-14T21:10:14.241Z
Learning: In `openmeter/billing/charges/service/invoice.go`, the `processorByType.creditPurchase` field in `handleStandardInvoiceUpdate` is intentionally left nil/empty. Credit-purchase charges have their own separate lifecycle path and are not dispatched through the standard invoice lifecycle hooks (`handleStandardInvoiceUpdate` / `handleChargeEvent`).

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

Good work

return nil, fmt.Errorf("new credits only state machine: %w", err)
}

return stateMachine.AdvanceUntilStateStable(ctx)

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.

this is a kinda far-fetched thought (with no expectation of any change-request), just hear me out...

I'm in general happy we're using stateless and the same semantics as in billing beforehand, I think that consistency helps a lot

I was just thinking that even in billing the onActivate or whats-it-called for the transitions does basically all the work (practically from validations to db writes) and i'm just wondering what it would be like if we extracted that part and only kept the state transition rules and validations as part of the statemachine

e.g.

for {
      nextState, canAdvance := sm.NextState(ctx, TriggerNext)
      if !canAdvance { break }

      if err := executeSideEffects(ctx, charge, nextState); err != nil { return err }

      charge.Status = nextState
      persist(ctx, charge)
  }

I think in most cases we only care about what state we enter into don't care which state we came from

I'm just thinking out loud, wdyt? (Feel free to ignore, we're busy and this is philosophizing)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually this makes sense, I had to force myself to write this as this is a linear state-machine. I have picked stateless for billing as it's extremely verbose and strict, as when we are dealing with money (or ledgers) we don't want suprises.

This PR is just about a happy path. Once we get into the territory of daily realizations, progressive billing, deleting/voiding of charges (and credit_then_invoice schemantics) I do see value in being overly verbose in this specific codepath.

The part I don't know yet is if the thing you are suggesting would/might work for simpler cases such as the credit purchase. There we need to map what void/delete means and if it fits into this representation.

But generally speaking, I would love to have something simpler, just I have the bad feeling that neither of the subtypes will have a simple linear lifecycle at the end 😢

Let's see how this goes for the creditpurchase or flat fee as those might be subject to simplification (that's why they have this "bespoke" state machine that is subject to rewrite either to a simpler state machine or stateless).

}

func (s *CreditsOnlyStateMachine) configureStates() {
s.Configure(usagebased.StatusCreated).

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.

I suppose the periodic realization cycle will be an increment (which i'm happy with it's already long enough 😆 )

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that's a can of worms I wouldn't open just yet. I think the priority order is:

  • credit_then_invoice settlement flow (that will be a beast due to needing sync with invoicing state machines)
  • then the periodic revenue recognition as that is basically this code with shorter collection + the invoicing accrued transactions without an invoice line being already allocated


charge.State.CurrentRealizationRunID = lo.ToPtr(run.ID.ID)

updatedCharge, err := s.adapter.UpdateCharge(ctx, charge.ChargeBase)

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.

I think we're double updating here (which is not incorrect just unnecessary), both this and the for loop in AdvanceUntilStateStable saves the charge state, I don't think this one is necessary

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.

But i might be missing something in control flow / error handling

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah this is somewhat of ambiguous, but I prefer to keep two invariants:

  • The AdvaceUntilStable is responsible for persisting the status of the charge. This is essential as over time we have states without activate actions and I wouldn't want to rely on us not forgetting to call the update state there as usually those are for state transitions that block on waits.
  • Here the updateCharge is invoked so that the CurrentRealizationRunID is persisted (that is/will be used for validating that no different revenue recognition runs can run in parallel), which in fact is redundant with the save, but safety first.

So in overal I prefer to save the state after each transitions so that we don't need to review for missing statements but we do sacrifice some performance here unfortunately. :/

return nil, fmt.Errorf("get charge lock key: %w", err)
}

if err := s.locker.LockForTX(ctx, key); err != nil {

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.

I think this lock will be held for the whole scope (not just this per charge transaction scope), I assume we have a customer scoped lock as well so two instances of the outer scope can't run in parallel, but if they can then this could cause deadlocks

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Locking is something we need to think about. I will create a ticket on this.

Initially I wanted to reuse the customer scoped lock for all of this, but once we fully roll out charges we can do invoice or charge based locks depending on scope.

For now this is more like an aspiration, but I might revert to the billing lock until we have some breathing room to actually think about this properly. 😐

@turip
turip merged commit 811410b into main Mar 24, 2026
42 of 43 checks passed
@turip
turip deleted the feat/usage-based-charges-lifecycle branch March 24, 2026 19:34

This branch was previously deployed

1 inactive deployment
dev — 04aaba57 Deployed Mar 24, 2026 by turip via Migration Checks #12797
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