Skip to content

feat(billing): scaffold usage based charge lifecycle mapping - #4297

Merged
turip merged 3 commits into
mainfrom
split/rating-scaffolding
May 6, 2026
Merged

turip merged 3 commits into
mainfrom
split/rating-scaffolding

Conversation

@turip

@turip turip commented May 6, 2026 •

Copy link
Copy Markdown
Member

Overview

This PR adds the usage-based charge scaffolding needed to make charge-owned realization runs map cleanly into billing standard invoice lines, while keeping rating behavior on the existing billing rating path.

Note: this PR uses the stock billingrating, the final delta engine is available here: #4298

Changed Behavior

  • Usage-based charge runs now persist enough metadata to reconstruct billing-facing invoice lines from charge realization state:

    • run detailed-line pricer reference IDs (will be required for late events`)
    • correction metadata (corrects_run_id) (will be needed for pro-rating)
    • run-level no_fiat_transaction_required (so that we don't start payment/invoice accrued ledger flow when not needed)
    • selected rating engine metadata, defaulted to delta
  • Usage-based standard invoice lines are now populated from realization runs instead of being recalculated through the generic billing line calculator (but the current implementation uses billing's rating in passthru).

    • Raw cumulative run quantities are mapped into billing line-period and pre-line-period quantities.
    • Usage discounts are communicated through the same standard billing usage-discount structure.
    • Run credits are projected onto the resulting billing line and detailed lines.
  • Charge line engines no longer have to implement billing recalculation.

    • billing.LineCalculator is split out from billing.LineEngine.
    • Invoice calculation skips engines that do not implement LineCalculator, expecting lifecycle hooks to return fully calculated lines.
  • Zero-fiat usage-based runs are handled explicitly.

    • credit_only runs always mark NoFiatTransactionRequired.
    • credit_then_invoice runs derive it from zero totals.
    • Invoice usage booking and payment authorization/settlement skip fiat ledger booking when the run is explicitly marked no-fiat.
  • Billing rating now supports disabling the credits mutator for charge-owned rating passes.

    • Charge rating totals remain gross before charge credit allocation.
    • Credits are applied later by the charge lifecycle.

Migration

Adds a new coalesced migration for:

  • charge_usage_based.rating_engine
  • charge_usage_based_runs.no_fiat_transaction_required
  • charge_flat_fee_detailed_line.pricer_reference_id
  • charge_usage_based_run_detailed_line.pricer_reference_id
  • charge_usage_based_run_detailed_line.corrects_run_id

The migration backfills:

  • existing usage-based charges to rating_engine = 'delta'
  • detailed-line pricer_reference_id from child_unique_reference_id
  • existing credit_only usage-based runs to no_fiat_transaction_required = true

Summary by CodeRabbit

  • New Features

    • Support for multiple rating engines for usage-based billing
    • Refined usage-based quantity semantics and progressive billing mapping
    • Detailed-line enhancements: pricer reference IDs, correction linkage, and a no‑fiat/zero‑total invoice path
  • Documentation

    • Expanded lifecycle, invoice-line mapping, discounts, and detailed-line expansion guidance
    • Cross-documentation guideline for rating algorithm changes
  • Bug Fixes

    • Typo fixed in billing README ("substracting" → "subtracting")

@turip
turip requested a review from a team as a code owner May 6, 2026 10:10
@coderabbitai

coderabbitai Bot commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 96610924-d039-4e81-a77e-5a20fc9d8444

📥 Commits

Reviewing files that changed from the base of the PR and between 4dbbe0e and fa80b79.

⛔ Files ignored due to path filters (28)
  • openmeter/ent/db/chargeflatfeedetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline/chargeflatfeedetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased/chargeusagebased.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline/chargeusagebasedrundetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns/chargeusagebasedruns.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/client.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.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 (62)
  • .agents/skills/billing/SKILL.md
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/README.md
  • openmeter/billing/charges/creditpurchase/lineengine/engine.go
  • openmeter/billing/charges/flatfee/adapter/detailedline.go
  • openmeter/billing/charges/flatfee/adapter/detailedline_test.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/detailedline.go
  • openmeter/billing/charges/usagebased/adapter/detailedline_test.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/detailedline.go
  • openmeter/billing/charges/usagebased/detailedline_uniqueref.go
  • openmeter/billing/charges/usagebased/rating.go
  • openmeter/billing/charges/usagebased/ratingengine.go
  • openmeter/billing/charges/usagebased/realizationrun.go
  • openmeter/billing/charges/usagebased/realizationrun_test.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/service/create.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/usagebased/service/linemapper.go
  • openmeter/billing/charges/usagebased/service/linemapper_test.go
  • openmeter/billing/charges/usagebased/service/payments.go
  • openmeter/billing/charges/usagebased/service/rating/detailedline.go
  • openmeter/billing/charges/usagebased/service/rating/service.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/charges/usagebased/service/rating/totals.go
  • openmeter/billing/charges/usagebased/service/run/create.go
  • openmeter/billing/charges/usagebased/service/run/invoice.go
  • openmeter/billing/charges/usagebased/service/run/payment.go
  • openmeter/billing/charges/usagebased/service/run/payment_test.go
  • openmeter/billing/charges/usagebased/service_test.go
  • openmeter/billing/derived.gen.go
  • openmeter/billing/invoicedetailedline.go
  • openmeter/billing/lineengine.go
  • openmeter/billing/lineengine/engine.go
  • openmeter/billing/models/stddetailedline/derived.gen.go
  • openmeter/billing/models/stddetailedline/model.go
  • openmeter/billing/models/totals/model.go
  • openmeter/billing/models/totals/model_test.go
  • openmeter/billing/rating/service.go
  • openmeter/billing/rating/service/billableperiod.go
  • openmeter/billing/rating/service/mutator/credits.go
  • openmeter/billing/rating/service/mutator/credits_test.go
  • openmeter/billing/rating/service/mutator/discountusage.go
  • openmeter/billing/rating/service/mutator/discountusage_test.go
  • openmeter/billing/rating/service/options_test.go
  • openmeter/billing/rating/service/pricer.go
  • openmeter/billing/rating/service/testutil/ubptest.go
  • openmeter/billing/service/invoicecalc/details.go
  • openmeter/billing/service/invoicecalc/details_test.go
  • openmeter/billing/testutils/lineengine.go
  • openmeter/ent/schema/chargesflatfee.go
  • openmeter/ent/schema/chargesusagebased.go
  • openmeter/ledger/chargeadapter/usagebased_test.go
  • tools/migrate/migrations/20260506102300_add_usage_based_detailed_line_corrects_run_id.down.sql
  • tools/migrate/migrations/20260506102300_add_usage_based_detailed_line_corrects_run_id.up.sql

📝 Walkthrough

Walkthrough

Adds usage-based billing semantics (BillingMeteredQuantity, RatingEngine, NoFiatTransactionRequired), extends DetailedLine with PricerReferenceID/CorrectsRunID, moves detailed-line construction into rating, extracts ApplyUsageDiscount, separates CalculateLines into a new LineCalculator interface, and updates adapters, schema, and tests accordingly.

Changes

Usage-Based Billing Enhancements

Layer / File(s) Summary
Data Shape & Models
openmeter/billing/charges/usagebased/charge.go, openmeter/billing/charges/usagebased/realizationrun.go, openmeter/billing/charges/usagebased/ratingengine.go, openmeter/billing/charges/usagebased/detailedline.go, openmeter/ent/schema/chargesusagebased.go
Added RatingEngine enum; added NoFiatTransactionRequired to runs and inputs; introduced BillingMeteredQuantity; DetailedLine now a struct with PricerReferenceID and CorrectsRunID. DB schema updated.
Quantity Mapping & Calculation
openmeter/billing/charges/usagebased/realizationrun.go, openmeter/billing/charges/usagebased/realizationrun_test.go
Added RealizationRuns.MapToBillingMeteredQuantity to compute per-line quantities from prior runs; tests cover normal and negative-quantity error cases.
Detailed-Line Construction & Utilities
openmeter/billing/charges/usagebased/detailedline.go, openmeter/billing/charges/usagebased/detailedline_uniqueref.go, openmeter/billing/charges/usagebased/service/rating/detailedline.go
Introduced NewDetailedLinesFromBilling, per-line Clone/Validate, and utilities to strip/rehydrate service-period suffixes; rating now delegates to constructor instead of inline mapping.
Line Population, Credits & Discounts
openmeter/billing/charges/usagebased/service/linemapper.go, openmeter/billing/charges/usagebased/service/linemapper_test.go, openmeter/billing/rating/service/mutator/discountusage.go
New populateUsageBasedStandardLineFromRun, detailed-line projection, credit-distribution helpers; extracted ApplyUsageDiscount API and tests; validates projected totals against run totals.
Run Lifecycle & No-Fiat Handling
openmeter/billing/charges/usagebased/service/run/*.go, openmeter/billing/charges/usagebased/service/creditheninvoice.go
Create/update flows now propagate NoFiatTransactionRequired; invoice accrual, payment auth/settle, and booking paths branch/short-circuit on the flag; validations enforce fiat/no-fiat consistency.
Adapters & Persistence
openmeter/billing/charges/usagebased/adapter/*, openmeter/billing/charges/flatfee/adapter/*, openmeter/ent/schema/*, tools/migrate/migrations/*
Adapters persist/restore RatingEngine, PricerReferenceID, CorrectsRunID, and NoFiatTransactionRequired; migration SQL updates DB data and columns; tests updated for DB-backed assertions.
Tests & Docs
.agents/skills/*, openmeter/billing/charges/usagebased/*_test.go, openmeter/billing/*_test.go
Documentation updated (Usage-Based Quantities); many unit/integration tests added/adjusted for mapping, detailed-line upserts, rating-engine validation, line population, credits, discounts, and no-fiat behavior.

Line Engine Interface Refactor

Layer / File(s) Summary
Interface Abstraction
openmeter/billing/lineengine.go, openmeter/billing/lineengine/engine.go
Removed CalculateLines from LineEngine; introduced LineCalculator interface exposing CalculateLines; compile-time assertions updated.
Implementations & Lifecycle
openmeter/billing/charges/usagebased/service/lineengine.go, openmeter/billing/charges/flatfee/service/lineengine.go, openmeter/billing/charges/creditpurchase/lineengine/engine.go
Usage-based engine inlines line calculation into lifecycle hooks and no longer relies on a public CalculateLines call; other engines updated compile-time assertions to optionally implement LineCalculator.
Invocation & Compatibility
openmeter/billing/service/invoicecalc/details.go, openmeter/billing/service/invoicecalc/details_test.go, openmeter/billing/testutils/lineengine.go
Invoice recalculation now checks for LineCalculator and skips engines that don't implement it; added NoopLineEngine test utility and a test ensuring recalculation is skipped without error.

Rating Options, Mutators & Validation

Layer / File(s) Summary
GenerateDetailedLines Options
openmeter/billing/rating/service.go, openmeter/billing/rating/service/pricer.go, openmeter/billing/charges/usagebased/service/rating/totals.go
Added DisableCreditsMutator option and WithCreditsMutatorDisabled() helper; pricer conditionally includes Credits mutator; usage-based flows default to disabling credits mutator where appropriate.
Credits & Discount Mutators
openmeter/billing/rating/service/mutator/credits.go, .../credits_test.go, .../discountusage.go, .../discountusage_test.go
Credits mutator now skips non-positive detailed-line totals and applies rounding via currency calculator; discount logic extracted into reusable ApplyUsageDiscount API with tests.
Validation Options
openmeter/billing/models/stddetailedline/model.go, openmeter/billing/rating/service/options_test.go
Base.Validate now accepts ValidateOption (e.g., IgnoreQuantityChecks) to support transformations that temporarily relax quantity checks; tests cover options behavior.

Supporting Models & Utilities

Layer / File(s) Summary
Totals Utilities
openmeter/billing/models/totals/model.go, openmeter/billing/models/totals/model_test.go
Added Sub, Neg, IsZero, and Equal methods to Totals and unit tests for equality.
Invoice Helpers
openmeter/billing/invoicedetailedline.go
Added DetailedLines.SumTotals() helper used during projection/validation.
Generated Code Updates
openmeter/billing/derived.gen.go, openmeter/billing/models/stddetailedline/derived.gen.go
Adjusted derived equality helpers to use Totals.Equal and to compare credits-applied elements; updated imports.

Sequence Diagram

sequenceDiagram
    participant Client
    participant RatingSvc as Rating Service
    participant Mapper as Line Mapper
    participant Mutator as Discount/Mutator
    participant Ledger as Ledger/Adapter

    Client->>RatingSvc: Create/Rate usage run
    RatingSvc->>RatingSvc: GetPreferredRatingEngineFor(intent)
    RatingSvc->>Mapper: MapToBillingMeteredQuantity(currentRun, priorRuns)
    Mapper->>Mapper: Compute pre-line & line-period quantities
    Mapper-->>RatingSvc: BillingMeteredQuantity
    RatingSvc->>Mutator: ApplyUsageDiscount(usage, discounts)
    Mutator-->>RatingSvc: Discounted usage & StandardLineDiscounts
    RatingSvc->>Mapper: ProjectDetailedLines and apply credits
    Mapper->>Ledger: CreateAccruedOrInvoicedUsage (branch on NoFiatTransactionRequired)
    Ledger-->>RatingSvc: Accrual/Invoice result
    RatingSvc-->>Client: StandardLine (populated, totals validated)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • tothandras
  • GAlexIHU
✨ 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 split/rating-scaffolding

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

Caution

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

⚠️ Outside diff range comments (1)
.agents/skills/charges/SKILL.md (1)

34-45: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

The skill still describes the old detailed-line shape.

This new guidance is helpful, but a few lines below the doc still says to prefer type DetailedLine = stddetailedline.Base in charge packages. Since this PR turns usagebased.DetailedLine into a real struct, the skill now points contributors in two different directions.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.agents/skills/charges/SKILL.md around lines 34 - 45, The skill
documentation is inconsistent about the detailed-line shape: it still advises
using "type DetailedLine = stddetailedline.Base" while this PR made
usagebased.DetailedLine a concrete struct; update the SKILL.md text to remove or
reword that conflicting sentence and make the guidance explicit — state that
charge packages should prefer reusing stddetailedline.Base (referenced as
stddetailedline.Base) for invoice-agnostic base lines or, if a package needs
charge-owned fields, define a concrete type (e.g., usagebased.DetailedLine) that
composes/embeds stddetailedline.Base; keep examples and references to
flatfee.Realizations and usagebased.RealizationRun to show
ownership-by-containment.
🧹 Nitpick comments (14)
openmeter/billing/charges/usagebased/service/rating/totals.go (1)

60-62: ⚡ Quick win

Please annotate why credits are force-disabled here.

At Line 60, this is a meaningful behavior choice; a short inline comment would make the totals semantics explicit and prevent accidental reverts later.

💡 Suggested clarity patch
-	opts := []billingrating.GenerateDetailedLinesOption{
+	// Intentionally exclude credits mutator for usage-total evaluation in this path.
+	opts := []billingrating.GenerateDetailedLinesOption{
 		billingrating.WithCreditsMutatorDisabled(),
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/service/rating/totals.go` around lines
60 - 62, Add a short inline comment next to the opts initialization explaining
why credits are being force-disabled
(billingrating.WithCreditsMutatorDisabled()) for the totals computation: state
the intended semantics (e.g., totals should represent gross usage before
credits, credits are applied later in a separate step, or credits are not
applicable for this rating pass) and mention any related behavior callers must
preserve (such as downstream functions that expect gross totals). Place the
comment directly above or on the same line as the opts variable so future
editors understand the rationale and don't accidentally re-enable credits.
openmeter/billing/models/totals/model.go (1)

86-101: 💤 Low value

Heads up: Sub can produce values that Validate() would reject.

Validate() rejects negative fields, but Sub will happily produce them (e.g. subtracting a larger Total). That's almost certainly the intended semantics — Neg exists for the same reason — but it does mean callers who pipe a Sub result back through Validate() will get errors. Worth a one-line doc comment on Sub/Neg clarifying that the result may carry negative components and isn't guaranteed to satisfy Validate().

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/models/totals/model.go` around lines 86 - 101, Add a
one-line doc comment to Totals.Sub (and the related Totals.Neg if present)
explaining that these operations may produce negative field values and therefore
their results are not guaranteed to satisfy Totals.Validate(), so callers should
validate or clamp results as needed; reference the Totals.Sub and Totals.Neg
method names and the Validate function in the comment so it's clear which
methods produce potentially negative components.
openmeter/billing/charges/usagebased/service/rating/service.go (1)

48-54: 💤 Low value

Heads-up: this is effectively a constant for now.

GetPreferredRatingEngineFor ignores intent and always returns RatingEngineDelta. That matches the PR's "scaffolding" framing, and the _ parameter name signals the intent clearly, so no action needed — just flagging so reviewers/future readers don't expect dispatch logic here yet. A // TODO mentioning that engine selection per intent will land later might help the next person who walks through.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/service/rating/service.go` around lines
48 - 54, GetPreferredRatingEngineFor currently ignores the intent and always
returns usagebased.RatingEngineDelta; update the implementation (or its
immediate comment) in the service.GetPreferredRatingEngineFor function to
include a clear TODO noting that engine selection per usagebased.Intent will be
implemented later (e.g., "// TODO: select rating engine based on intent;
currently returns default RatingEngineDelta"), so reviewers/future readers know
this is intentional scaffolding.
openmeter/billing/models/totals/model_test.go (1)

51-70: ⚡ Quick win

Solid starter test — consider expanding per-field coverage.

The current test only mutates Total, so a regression where (say) CreditsTotal is missing from Equal's field list would slip through. A quick table-driven sweep flipping each field one at a time would lock the contract down for cheap.

♻️ Sketch
 	require.True(t, in.Equal(in))
 
-	other := in
-	other.Total = alpacadecimal.NewFromInt(9)
-	require.False(t, in.Equal(other))
+	mutators := map[string]func(*Totals){
+		"Amount":              func(x *Totals) { x.Amount = alpacadecimal.NewFromInt(99) },
+		"ChargesTotal":        func(x *Totals) { x.ChargesTotal = alpacadecimal.NewFromInt(99) },
+		"DiscountsTotal":      func(x *Totals) { x.DiscountsTotal = alpacadecimal.NewFromInt(99) },
+		"TaxesInclusiveTotal": func(x *Totals) { x.TaxesInclusiveTotal = alpacadecimal.NewFromInt(99) },
+		"TaxesExclusiveTotal": func(x *Totals) { x.TaxesExclusiveTotal = alpacadecimal.NewFromInt(99) },
+		"TaxesTotal":          func(x *Totals) { x.TaxesTotal = alpacadecimal.NewFromInt(99) },
+		"CreditsTotal":        func(x *Totals) { x.CreditsTotal = alpacadecimal.NewFromInt(99) },
+		"Total":               func(x *Totals) { x.Total = alpacadecimal.NewFromInt(99) },
+	}
+	for name, mutate := range mutators {
+		t.Run(name, func(t *testing.T) {
+			other := in
+			mutate(&other)
+			require.False(t, in.Equal(other), "expected inequality when %s differs", name)
+		})
+	}

Also, while you're here, it might be worth adding minimal tests for the sibling helpers (Sub, Neg, IsZero) so the full new arithmetic surface is covered.

As per coding guidelines: "Make sure the tests are comprehensive and cover the changes."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/models/totals/model_test.go` around lines 51 - 70, Expand
TestTotalsEqual into a table-driven test that iterates over each Totals field
(Amount, ChargesTotal, DiscountsTotal, TaxesInclusiveTotal, TaxesExclusiveTotal,
TaxesTotal, CreditsTotal, Total) and for each case makes a copy of the base
Totals, mutates only that field, and asserts in.Equal(other) is false while
keeping the original equality check for identical structs; additionally add
small tests for the helper methods Totals.Sub, Totals.Neg and Totals.IsZero that
verify simple arithmetic (e.g., a.Sub(b) produces expected per-field results,
Neg flips signs, and IsZero returns true for a zero-valued Totals and false
otherwise) to ensure the new arithmetic surface is covered.
openmeter/billing/charges/usagebased/detailedline_uniqueref.go (3)

43-64: ⚡ Quick win

Suffix marker @[ is doing a lot of work — worth a constant.

Both stripServicePeriodFromUniqueReferenceID and formatServicePeriodInUniqueReferenceID hard-code the @[ ... ] shape independently. If anyone tweaks the format on one side they'll silently desync the other. Pulling the marker (or at least @[) into a package-level const, plus a tiny round-trip test (format → strip returns the base), would make this self-defending.

♻️ Sketch
+const servicePeriodSuffixOpen = "@["
+
 func stripServicePeriodFromUniqueReferenceID(id string) (string, error) {
-	idx := strings.Index(id, "@[")
+	idx := strings.Index(id, servicePeriodSuffixOpen)
 	if idx < 0 {
 		return id, nil
 	}
 	...
 }

 func formatServicePeriodInUniqueReferenceID(id string, servicePeriod timeutil.ClosedPeriod) string {
 	return fmt.Sprintf(
-		"%s@[%s..%s]",
+		"%s%s%s..%s]",
 		id,
+		servicePeriodSuffixOpen,
 		servicePeriod.From.UTC().Format(time.RFC3339),
 		servicePeriod.To.UTC().Format(time.RFC3339),
 	)
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/detailedline_uniqueref.go` around lines
43 - 64, Both functions hard-code the same service-period suffix syntax leading
to possible desync; introduce a package-level constant like servicePeriodMarker
= "@[" (or a full suffix pattern const) and use that constant in
stripServicePeriodFromUniqueReferenceID and
formatServicePeriodInUniqueReferenceID so the marker is defined in one place,
then add a small round-trip unit test asserting
formatServicePeriodInUniqueReferenceID(base, sp) when passed through
stripServicePeriodFromUniqueReferenceID returns the original base; update
references to strings.Index(id, "@[") and the fmt.Sprintf call to use the new
constant(s).

29-41: 💤 Low value

Small naming nit on WithServicePeriodFromUniqueReferenceID.

The name reads like it pulls the service period from the ID, but it actually re-encodes the line's ServicePeriod into the ID (stripping any prior suffix first). Something like WithServicePeriodInUniqueReferenceID or EncodeServicePeriodIntoUniqueReferenceID would describe the direction more naturally. Totally optional — feel free to ignore if the current name is intentional.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/detailedline_uniqueref.go` around lines
29 - 41, The function name WithServicePeriodFromUniqueReferenceID is misleading
because it writes/encodes the line's ServicePeriod into ChildUniqueReferenceID
rather than extracting it; rename the function to a clearer name like
WithServicePeriodInUniqueReferenceID or
EncodeServicePeriodIntoUniqueReferenceID, update its declaration and all
internal callers/tests/exports to use the new identifier (including references
to DetailedLines.WithServicePeriodFromUniqueReferenceID and any imports), and
run tests to ensure no remaining references to the old name remain.

57-64: 💤 Low value

RFC3339 formatting is fine for IDs here — the system guarantees 1-second precision system-wide.

The RFC3339 format does technically drop sub-second precision. However, the entire billing system is designed around MinimumWindowSizeDuration = time.Second, and service periods are consistently truncated to 1-second precision via NormalizeTimestamp() and NormalizeClosedPeriod() at all entry points. Your assumption that "billing periods are aligned to whole seconds" is correct by design, so there's no collision risk.

If you want to be extra defensive, you could add a brief comment in the function clarifying that service periods are expected to be pre-normalized, but it's not necessary — the system design handles this.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/detailedline_uniqueref.go` around lines
57 - 64, The RFC3339 timestamp formatting in
formatServicePeriodInUniqueReferenceID may seem to drop sub-second precision, so
add a brief comment above the function clarifying that service periods are
always pre-normalized to 1-second precision (via
NormalizeTimestamp/NormalizeClosedPeriod and MinimumWindowSizeDuration =
time.Second), so using RFC3339 is safe; leave the implementation as-is but
document the normalization guarantee referencing
formatServicePeriodInUniqueReferenceID and the normalization helpers.
openmeter/billing/charges/usagebased/service/create.go (1)

40-40: ⚡ Quick win

Please add a create-path test assertion for RatingEngine forwarding.

This is a key behavior seam now; a small test that verifies Create passes the selected engine into CreateChargesInput.Intents would guard against regressions in the next stacked PRs.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/service/create.go` at line 40, Add a
unit/integration assertion in the Create path test that verifies the selected
rating engine is forwarded into the created intents: after calling Create (the
service method) assert that the returned/constructed CreateChargesInput.Intents
contains entries whose RatingEngine equals the value returned by
s.rater.GetPreferredRatingEngineFor(intent) (or the mocked return value). Locate
the test that exercises Create (or add a focused test named like
TestCreate_ForwardsRatingEngine) and mock s.rater.GetPreferredRatingEngineFor to
a known value, call Create, then assert
CreateChargesInput.Intents[*].RatingEngine matches that known value.
openmeter/billing/charges/usagebased/adapter/detailedline.go (1)

228-239: ⚡ Quick win

Mirror the write-side fallback when hydrating PricerReferenceID.

buildDetailedLineCreate stores lo.CoalesceOrEmpty(line.PricerReferenceID, line.ChildUniqueReferenceID), but the read path takes dbLine.PricerReferenceID as-is. Reusing the same fallback here would make older or partially backfilled rows behave the same way as fresh writes, which feels important for the lifecycle-mapping path this PR is setting up.

Suggested tweak
 	line := usagebased.DetailedLine{
 		Base: stddetailedline.FromDB(
 			dbLine,
 			stddetailedline.BackfillTaxConfig(
 				lo.EmptyableToPtr(dbLine.TaxConfig),
 				dbLine.TaxBehavior,
 				taxCodeIDFromEnt(dbLine.Edges.TaxCode),
 			),
 		),
-		PricerReferenceID: dbLine.PricerReferenceID,
+		PricerReferenceID: lo.CoalesceOrEmpty(dbLine.PricerReferenceID, dbLine.ChildUniqueReferenceID),
 		CorrectsRunID:     dbLine.CorrectsRunID,
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/adapter/detailedline.go` around lines
228 - 239, In mapDetailedLineFromDB replace the direct use of
dbLine.PricerReferenceID with the same write-side fallback used in
buildDetailedLineCreate: when hydrating the Pric erReferenceID field use
lo.CoalesceOrEmpty(dbLine.PricerReferenceID, dbLine.ChildUniqueReferenceID) (or
equivalent) so older/partially-backfilled rows fall back to
ChildUniqueReferenceID the same way writes do; update the Pric erReferenceID
assignment inside mapDetailedLineFromDB to use that coalescing logic.
openmeter/billing/charges/usagebased/service/run/invoice.go (1)

43-49: ⚡ Quick win

Please add a focused test for the no-fiat branch.

This now has two new invariants plus a persistence path that writes AccruedUsage without a ledger transaction. A small unit test covering NoFiatTransactionRequired=true and the two mismatch errors would make this split a lot safer to evolve in the next stacked PRs.

As per coding guidelines, **/*_test.go: Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests.

Also applies to: 64-80

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/service/run/invoice.go` around lines 43
- 49, Add a unit test file (invoice_no_fiat_test.go) that exercises the invoice
path when i.Run.NoFiatTransactionRequired is true: create a Run and Line with a
non-zero Totals.Total to assert the error "requires no fiat transaction but line
total is non-zero", then a case where NoFiatTransactionRequired=false and
Totals.Total is zero to assert the other mismatch error, and finally a
successful NoFiatTransactionRequired=true case that goes through the persistence
logic to write AccruedUsage without creating a ledger transaction (assert
AccruedUsage was persisted and no ledger entries created). Target the code paths
around the checks referencing i.Run.NoFiatTransactionRequired,
i.Line.Totals.Total, and the AccruedUsage persistence to ensure the new
invariants and persistence branch are covered.
openmeter/billing/rating/service/mutator/discountusage.go (1)

65-99: 💤 Low value

Tiny readability nit on the removeRateCardUsageDiscounts calls.

You end up calling removeRateCardUsageDiscounts(out.StandardLineDiscounts) in all three branches. Since out.StandardLineDiscounts always starts as in.StandardLineDiscounts.Clone(), you could prune once up front and simplify each branch. Totally optional — current code is correct and arguably more explicit per-branch.

♻️ Optional simplification
 	out := ApplyUsageDiscountResult{
 		Usage:                 in.Usage,
-		StandardLineDiscounts: in.StandardLineDiscounts.Clone(),
+		StandardLineDiscounts: removeRateCardUsageDiscounts(in.StandardLineDiscounts.Clone()),
 	}
 
 	usageDiscount := in.RateCardDiscounts.Usage
 	if usageDiscount == nil {
-		out.StandardLineDiscounts = removeRateCardUsageDiscounts(out.StandardLineDiscounts)
 		return out, nil
 	}
@@
 	discountAppliedToCurrentLine := applyDiscount(previouslyAppliedDiscount.discountRemaining, in.Usage.Quantity)
 	if discountAppliedToCurrentLine.discountApplied.IsZero() {
-		out.StandardLineDiscounts = removeRateCardUsageDiscounts(out.StandardLineDiscounts)
 		return out, nil
 	}
 
-	out.StandardLineDiscounts = removeRateCardUsageDiscounts(out.StandardLineDiscounts)
 	out.Usage.Quantity = in.Usage.Quantity.Sub(discountAppliedToCurrentLine.discountApplied)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/rating/service/mutator/discountusage.go` around lines 65 -
99, The code repeatedly calls
removeRateCardUsageDiscounts(out.StandardLineDiscounts) in multiple branches;
simplify by pruning once after initializing out.StandardLineDiscounts (which
comes from in.StandardLineDiscounts.Clone()) — call out.StandardLineDiscounts =
removeRateCardUsageDiscounts(out.StandardLineDiscounts) immediately after that
initialization, then remove the three per-branch calls and keep the existing
logic that sets out.Usage and merges the new billing.UsageLineDiscountManaged;
adjust any early-return branches (e.g., when usageDiscount == nil or
discountAppliedToCurrentLine.discountApplied.IsZero()) to rely on the pre-pruned
out.StandardLineDiscounts instead of re-invoking removeRateCardUsageDiscounts.
openmeter/ent/schema/chargesusagebased.go (2)

190-190: 💤 Low value

Same nit for no_fiat_transaction_required.

No Default(false) here either — the up migration adds the column with DEFAULT false and then drops the default, so going forward every ChargeUsageBasedRuns.Create must SetNoFiatTransactionRequired(...) explicitly. The relevant context snippet confirms CreateRealizationRunInput now propagates this, so we're likely fine, but a Default(false) on the schema would be a cheap safety belt.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/ent/schema/chargesusagebased.go` at line 190, The schema field
declaration field.Bool("no_fiat_transaction_required") lacks a Default(false)
safety — add Default(false) to that field in the ChargesUsageBased schema so new
ChargeUsageBasedRuns created without explicitly calling
SetNoFiatTransactionRequired(...) default to false; update the schema field
definition for "no_fiat_transaction_required" (the field.Bool(...) entry) to
include Default(false) to match the migration's intent and prevent future
creation bugs (this complements existing CreateRealizationRunInput propagation
and ChargeUsageBasedRuns.Create callers).

62-63: 💤 Low value

Schema-level default check: rating_engine doesn't have one, but that's already handled.

Good news—the buildCreateUsageBasedCharge function in the adapter does set SetRatingEngine(intent.RatingEngine) when creating new charges. Existing rows are backfilled to 'delta' by the migration, so you're all set there. That said, if you'd like a future-proofing safety net (in case someone adds another create path and forgets to set it), consider adding Default(string(usagebased.RatingEngineDelta)) to the schema—it's not required but could save a debugging headache down the line.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/ent/schema/chargesusagebased.go` around lines 62 - 63, Add a
schema-level default for the rating_engine enum by updating the field definition
that currently reads
field.Enum("rating_engine").GoType(usagebased.RatingEngine("")). Specifically,
append Default(string(usagebased.RatingEngineDelta)) to the field definition so
the schema uses the delta value when a create path forgets to set RatingEngine;
keep the existing GoType(usagebased.RatingEngine("")) and only add the
Default(...) call.
tools/migrate/migrations/20260430092817_add_usage_based_detailed_line_corrects_run_id.up.sql (1)

1-14: 💤 Low value

Lock-duration heads up on SET NOT NULL.

Each of the ALTER TABLE ... ALTER COLUMN ... SET NOT NULL statements (lines 6, 10, 14) takes an AccessExclusiveLock and scans the full table to validate. That's totally fine for small/medium tables, but charge_usage_based_run_detailed_line and charge_flat_fee_detailed_line can grow large — worth a quick check on production sizes before rolling out, and considering the ADD CONSTRAINT ... CHECK (col IS NOT NULL) NOT VALID → VALIDATE CONSTRAINT → SET NOT NULL dance if they're already big.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@tools/migrate/migrations/20260430092817_add_usage_based_detailed_line_corrects_run_id.up.sql`
around lines 1 - 14, SET NOT NULL on large tables will acquire
AccessExclusiveLock and scan the full table; for the columns "rating_engine",
"pricer_reference_id" (on charge_flat_fee_detailed_line and
charge_usage_based_run_detailed_line) replace the immediate ALTER COLUMN ... SET
NOT NULL with the safe three-step pattern: ADD the new column and backfill as
you already do, then ADD CONSTRAINT "<constraint_name>" CHECK (<column> IS NOT
NULL) NOT VALID (use exact names like cub_run_corrected_detailed_lines for the
FK and create similar unique constraint names for the checks), run VALIDATE
CONSTRAINT to perform the scan without long exclusive locks, and only after
validation run ALTER TABLE ... ALTER COLUMN ... SET NOT NULL; also verify
production table sizes for charge_usage_based_run_detailed_line and
charge_flat_fee_detailed_line before deploying.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@openmeter/billing/charges/usagebased/charge.go`:
- Around line 247-249: The State validation now requires a non-empty
RatingEngine (checked via State.RatingEngine.Validate()), so update the test
helper that constructs State{} (the fixture in the usagebased test helper) to
supply a valid RatingEngine value; replace bare State{} with something like
State{RatingEngine: "delta"} or use the project constant (e.g., RatingEngine:
ratingengine.Delta) so the call to State.RatingEngine.Validate() no longer fails
in the test.

In `@openmeter/billing/charges/usagebased/detailedline.go`:
- Around line 22-23: The JSON tag for the struct field CorrectsRunID should use
the same "...ID" casing as the rest of the model; change the tag from
`json:"correctsRunId,omitempty"` to `json:"correctsRunID,omitempty"` so
serialization matches other fields like PricerReferenceID and keeps wire shape
consistent.

In `@openmeter/billing/charges/usagebased/realizationrun.go`:
- Around line 274-315: MapToBillingMeteredQuantity's selection of latestPriorRun
only uses ServicePeriodTo.After which leaves ties unresolved and can pick the
wrong prior run; change the selection logic in
RealizationRuns.MapToBillingMeteredQuantity so when
r[idx].ServicePeriodTo.Equal(latestPriorRun.ServicePeriodTo) you apply a
deterministic tie-breaker (e.g. prefer the run with a non-empty CorrectsRunID
that corrects the other, or if unavailable prefer the later CreatedAt) and
update latestPriorRun accordingly; also include the chosen prior run's ID in the
negative-quantity error message (augment the fmt.Errorf call) so the error
prints the relevant run identifier for easier triage.

In `@openmeter/billing/charges/usagebased/service/lineengine.go`:
- Around line 161-168: The change in lineengine.go inlined run→line mapping and
removed delegation to the existing billing pipeline, causing usage-based
invoices to bypass CalculateLines; restore delegation by keeping this engine's
CalculateLines(...) implementation and have the lifecycle/state-transition code
(functions: stateMachine.GetCharge(), charge.GetCurrentRealizationRun(), and
populateUsageBasedStandardLineFromRun) only drive state changes — then call the
existing billing LineCalculator.CalculateLines(...) (or the original
CalculateLines implementation) to perform the actual line rating; also apply the
same fix for the other block referenced (around the code that mirrors lines
212-224) so both paths continue to invoke CalculateLines rather than replacing
its logic inline.

In `@openmeter/billing/charges/usagebased/service/linemapper.go`:
- Around line 67-68: projectUsageBasedDetailedLines currently drops the
PricerReferenceID before calling DetailedLinesWithIDReuse which prevents reuse
when pricer identity is unchanged but ChildUniqueReferenceID changes; update
projectUsageBasedDetailedLines to preserve/thread the PricerReferenceID into
each projected detailed line (so DetailedLinesWithIDReuse can match on
PricerReferenceID in addition to ChildUniqueReferenceID), ensure
stdLine.DetailedLines = stdLine.DetailedLinesWithIDReuse(projectedDetailedLines)
receives lines that include PricerReferenceID, and add a regression test that
simulates a rerate where PricerReferenceID is constant but
ChildUniqueReferenceID changes to assert IDs are reused rather than churned
(also apply same fix to the other projection block around the 88-105 region).

In `@openmeter/billing/README.md`:
- Line 119: The sentence "When subtracting the two we get the delta for the
period (this gets the delta for all supported meter types except of Min and
Avg)." has awkward grammar; update that parenthetical to read "(this gets the
delta for all supported meter types except Min and Avg)" by removing "of" so it
reads clearly in openmeter/billing/README.md where that sentence appears.

In
`@tools/migrate/migrations/20260430092817_add_usage_based_detailed_line_corrects_run_id.up.sql`:
- Around line 16-18: The backfill only marks no_fiat_transaction_required true
for parent charges with settlement_mode='credit_only' but misses existing runs
whose total is zero; update the migration SQL in charge_usage_based_runs to also
set no_fiat_transaction_required = true when the run's total is zero (use the
actual totals column produced by your totals mixin, e.g. r."total" or the JSON
path that represents Totals.Total), keeping the existing settlement_mode
condition (use OR), and then still drop the DEFAULT as shown; verify against
service/run/create.go and service/run/invoice.go semantics so the DB value
matches the runtime rule.

---

Outside diff comments:
In @.agents/skills/charges/SKILL.md:
- Around line 34-45: The skill documentation is inconsistent about the
detailed-line shape: it still advises using "type DetailedLine =
stddetailedline.Base" while this PR made usagebased.DetailedLine a concrete
struct; update the SKILL.md text to remove or reword that conflicting sentence
and make the guidance explicit — state that charge packages should prefer
reusing stddetailedline.Base (referenced as stddetailedline.Base) for
invoice-agnostic base lines or, if a package needs charge-owned fields, define a
concrete type (e.g., usagebased.DetailedLine) that composes/embeds
stddetailedline.Base; keep examples and references to flatfee.Realizations and
usagebased.RealizationRun to show ownership-by-containment.

---

Nitpick comments:
In `@openmeter/billing/charges/usagebased/adapter/detailedline.go`:
- Around line 228-239: In mapDetailedLineFromDB replace the direct use of
dbLine.PricerReferenceID with the same write-side fallback used in
buildDetailedLineCreate: when hydrating the Pric erReferenceID field use
lo.CoalesceOrEmpty(dbLine.PricerReferenceID, dbLine.ChildUniqueReferenceID) (or
equivalent) so older/partially-backfilled rows fall back to
ChildUniqueReferenceID the same way writes do; update the Pric erReferenceID
assignment inside mapDetailedLineFromDB to use that coalescing logic.

In `@openmeter/billing/charges/usagebased/detailedline_uniqueref.go`:
- Around line 43-64: Both functions hard-code the same service-period suffix
syntax leading to possible desync; introduce a package-level constant like
servicePeriodMarker = "@[" (or a full suffix pattern const) and use that
constant in stripServicePeriodFromUniqueReferenceID and
formatServicePeriodInUniqueReferenceID so the marker is defined in one place,
then add a small round-trip unit test asserting
formatServicePeriodInUniqueReferenceID(base, sp) when passed through
stripServicePeriodFromUniqueReferenceID returns the original base; update
references to strings.Index(id, "@[") and the fmt.Sprintf call to use the new
constant(s).
- Around line 29-41: The function name WithServicePeriodFromUniqueReferenceID is
misleading because it writes/encodes the line's ServicePeriod into
ChildUniqueReferenceID rather than extracting it; rename the function to a
clearer name like WithServicePeriodInUniqueReferenceID or
EncodeServicePeriodIntoUniqueReferenceID, update its declaration and all
internal callers/tests/exports to use the new identifier (including references
to DetailedLines.WithServicePeriodFromUniqueReferenceID and any imports), and
run tests to ensure no remaining references to the old name remain.
- Around line 57-64: The RFC3339 timestamp formatting in
formatServicePeriodInUniqueReferenceID may seem to drop sub-second precision, so
add a brief comment above the function clarifying that service periods are
always pre-normalized to 1-second precision (via
NormalizeTimestamp/NormalizeClosedPeriod and MinimumWindowSizeDuration =
time.Second), so using RFC3339 is safe; leave the implementation as-is but
document the normalization guarantee referencing
formatServicePeriodInUniqueReferenceID and the normalization helpers.

In `@openmeter/billing/charges/usagebased/service/create.go`:
- Line 40: Add a unit/integration assertion in the Create path test that
verifies the selected rating engine is forwarded into the created intents: after
calling Create (the service method) assert that the returned/constructed
CreateChargesInput.Intents contains entries whose RatingEngine equals the value
returned by s.rater.GetPreferredRatingEngineFor(intent) (or the mocked return
value). Locate the test that exercises Create (or add a focused test named like
TestCreate_ForwardsRatingEngine) and mock s.rater.GetPreferredRatingEngineFor to
a known value, call Create, then assert
CreateChargesInput.Intents[*].RatingEngine matches that known value.

In `@openmeter/billing/charges/usagebased/service/rating/service.go`:
- Around line 48-54: GetPreferredRatingEngineFor currently ignores the intent
and always returns usagebased.RatingEngineDelta; update the implementation (or
its immediate comment) in the service.GetPreferredRatingEngineFor function to
include a clear TODO noting that engine selection per usagebased.Intent will be
implemented later (e.g., "// TODO: select rating engine based on intent;
currently returns default RatingEngineDelta"), so reviewers/future readers know
this is intentional scaffolding.

In `@openmeter/billing/charges/usagebased/service/rating/totals.go`:
- Around line 60-62: Add a short inline comment next to the opts initialization
explaining why credits are being force-disabled
(billingrating.WithCreditsMutatorDisabled()) for the totals computation: state
the intended semantics (e.g., totals should represent gross usage before
credits, credits are applied later in a separate step, or credits are not
applicable for this rating pass) and mention any related behavior callers must
preserve (such as downstream functions that expect gross totals). Place the
comment directly above or on the same line as the opts variable so future
editors understand the rationale and don't accidentally re-enable credits.

In `@openmeter/billing/charges/usagebased/service/run/invoice.go`:
- Around line 43-49: Add a unit test file (invoice_no_fiat_test.go) that
exercises the invoice path when i.Run.NoFiatTransactionRequired is true: create
a Run and Line with a non-zero Totals.Total to assert the error "requires no
fiat transaction but line total is non-zero", then a case where
NoFiatTransactionRequired=false and Totals.Total is zero to assert the other
mismatch error, and finally a successful NoFiatTransactionRequired=true case
that goes through the persistence logic to write AccruedUsage without creating a
ledger transaction (assert AccruedUsage was persisted and no ledger entries
created). Target the code paths around the checks referencing
i.Run.NoFiatTransactionRequired, i.Line.Totals.Total, and the AccruedUsage
persistence to ensure the new invariants and persistence branch are covered.

In `@openmeter/billing/models/totals/model_test.go`:
- Around line 51-70: Expand TestTotalsEqual into a table-driven test that
iterates over each Totals field (Amount, ChargesTotal, DiscountsTotal,
TaxesInclusiveTotal, TaxesExclusiveTotal, TaxesTotal, CreditsTotal, Total) and
for each case makes a copy of the base Totals, mutates only that field, and
asserts in.Equal(other) is false while keeping the original equality check for
identical structs; additionally add small tests for the helper methods
Totals.Sub, Totals.Neg and Totals.IsZero that verify simple arithmetic (e.g.,
a.Sub(b) produces expected per-field results, Neg flips signs, and IsZero
returns true for a zero-valued Totals and false otherwise) to ensure the new
arithmetic surface is covered.

In `@openmeter/billing/models/totals/model.go`:
- Around line 86-101: Add a one-line doc comment to Totals.Sub (and the related
Totals.Neg if present) explaining that these operations may produce negative
field values and therefore their results are not guaranteed to satisfy
Totals.Validate(), so callers should validate or clamp results as needed;
reference the Totals.Sub and Totals.Neg method names and the Validate function
in the comment so it's clear which methods produce potentially negative
components.

In `@openmeter/billing/rating/service/mutator/discountusage.go`:
- Around line 65-99: The code repeatedly calls
removeRateCardUsageDiscounts(out.StandardLineDiscounts) in multiple branches;
simplify by pruning once after initializing out.StandardLineDiscounts (which
comes from in.StandardLineDiscounts.Clone()) — call out.StandardLineDiscounts =
removeRateCardUsageDiscounts(out.StandardLineDiscounts) immediately after that
initialization, then remove the three per-branch calls and keep the existing
logic that sets out.Usage and merges the new billing.UsageLineDiscountManaged;
adjust any early-return branches (e.g., when usageDiscount == nil or
discountAppliedToCurrentLine.discountApplied.IsZero()) to rely on the pre-pruned
out.StandardLineDiscounts instead of re-invoking removeRateCardUsageDiscounts.

In `@openmeter/ent/schema/chargesusagebased.go`:
- Line 190: The schema field declaration
field.Bool("no_fiat_transaction_required") lacks a Default(false) safety — add
Default(false) to that field in the ChargesUsageBased schema so new
ChargeUsageBasedRuns created without explicitly calling
SetNoFiatTransactionRequired(...) default to false; update the schema field
definition for "no_fiat_transaction_required" (the field.Bool(...) entry) to
include Default(false) to match the migration's intent and prevent future
creation bugs (this complements existing CreateRealizationRunInput propagation
and ChargeUsageBasedRuns.Create callers).
- Around line 62-63: Add a schema-level default for the rating_engine enum by
updating the field definition that currently reads
field.Enum("rating_engine").GoType(usagebased.RatingEngine("")). Specifically,
append Default(string(usagebased.RatingEngineDelta)) to the field definition so
the schema uses the delta value when a create path forgets to set RatingEngine;
keep the existing GoType(usagebased.RatingEngine("")) and only add the
Default(...) call.

In
`@tools/migrate/migrations/20260430092817_add_usage_based_detailed_line_corrects_run_id.up.sql`:
- Around line 1-14: SET NOT NULL on large tables will acquire
AccessExclusiveLock and scan the full table; for the columns "rating_engine",
"pricer_reference_id" (on charge_flat_fee_detailed_line and
charge_usage_based_run_detailed_line) replace the immediate ALTER COLUMN ... SET
NOT NULL with the safe three-step pattern: ADD the new column and backfill as
you already do, then ADD CONSTRAINT "<constraint_name>" CHECK (<column> IS NOT
NULL) NOT VALID (use exact names like cub_run_corrected_detailed_lines for the
FK and create similar unique constraint names for the checks), run VALIDATE
CONSTRAINT to perform the scan without long exclusive locks, and only after
validation run ALTER TABLE ... ALTER COLUMN ... SET NOT NULL; also verify
production table sizes for charge_usage_based_run_detailed_line and
charge_flat_fee_detailed_line before deploying.
🪄 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: c0980d9d-1e96-4225-a7db-93e02b6ebb53

📥 Commits

Reviewing files that changed from the base of the PR and between 80d86ac and d43c0a7.

⛔ Files ignored due to path filters (28)
  • openmeter/ent/db/chargeflatfeedetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline/chargeflatfeedetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased/chargeusagebased.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline/chargeusagebasedrundetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns/chargeusagebasedruns.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/client.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.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 (58)
  • .agents/skills/billing/SKILL.md
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/README.md
  • openmeter/billing/charges/creditpurchase/lineengine/engine.go
  • openmeter/billing/charges/flatfee/adapter/detailedline.go
  • openmeter/billing/charges/flatfee/adapter/detailedline_test.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/detailedline.go
  • openmeter/billing/charges/usagebased/adapter/detailedline_test.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/detailedline.go
  • openmeter/billing/charges/usagebased/detailedline_uniqueref.go
  • openmeter/billing/charges/usagebased/rating.go
  • openmeter/billing/charges/usagebased/ratingengine.go
  • openmeter/billing/charges/usagebased/realizationrun.go
  • openmeter/billing/charges/usagebased/realizationrun_test.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/service/create.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/usagebased/service/linemapper.go
  • openmeter/billing/charges/usagebased/service/linemapper_test.go
  • openmeter/billing/charges/usagebased/service/payments.go
  • openmeter/billing/charges/usagebased/service/rating/detailedline.go
  • openmeter/billing/charges/usagebased/service/rating/service.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/charges/usagebased/service/rating/totals.go
  • openmeter/billing/charges/usagebased/service/run/create.go
  • openmeter/billing/charges/usagebased/service/run/invoice.go
  • openmeter/billing/charges/usagebased/service/run/payment.go
  • openmeter/billing/charges/usagebased/service/run/payment_test.go
  • openmeter/billing/charges/usagebased/service_test.go
  • openmeter/billing/invoicedetailedline.go
  • openmeter/billing/lineengine.go
  • openmeter/billing/lineengine/engine.go
  • openmeter/billing/models/stddetailedline/model.go
  • openmeter/billing/models/totals/model.go
  • openmeter/billing/models/totals/model_test.go
  • openmeter/billing/rating/service.go
  • openmeter/billing/rating/service/billableperiod.go
  • openmeter/billing/rating/service/mutator/credits.go
  • openmeter/billing/rating/service/mutator/credits_test.go
  • openmeter/billing/rating/service/mutator/discountusage.go
  • openmeter/billing/rating/service/mutator/discountusage_test.go
  • openmeter/billing/rating/service/options_test.go
  • openmeter/billing/rating/service/pricer.go
  • openmeter/billing/rating/service/testutil/ubptest.go
  • openmeter/billing/service/invoicecalc/details.go
  • openmeter/billing/service/invoicecalc/details_test.go
  • openmeter/billing/testutils/lineengine.go
  • openmeter/ent/schema/chargesflatfee.go
  • openmeter/ent/schema/chargesusagebased.go
  • tools/migrate/migrations/20260430092817_add_usage_based_detailed_line_corrects_run_id.down.sql
  • tools/migrate/migrations/20260430092817_add_usage_based_detailed_line_corrects_run_id.up.sql

Comment thread openmeter/billing/README.md Resolved
@turip
turip force-pushed the split/rating-scaffolding branch from d43c0a7 to a3df829 Compare May 6, 2026 11:46

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

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

22-23: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

JSON tag still uses correctsRunId — this was flagged in a previous review.

The past comment noted that all other ID fields serialize as ...ID (pricerReferenceID, childUniqueReferenceID, etc.), making correctsRunId the odd one out on the wire format. Worth fixing before this lands!

🛠️ Suggested fix
-	CorrectsRunID     *string `json:"correctsRunId,omitempty"`
+	CorrectsRunID     *string `json:"correctsRunID,omitempty"`
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/detailedline.go` around lines 22 - 23,
The JSON tag for the struct field CorrectsRunID is inconsistent with the
project's ID casing convention: change the tag on CorrectsRunID from
`correctsRunId` to `correctsRunID` so it matches other fields like
PricerReferenceID and ChildUniqueReferenceID; update the struct field's tag in
detailedline.go for the CorrectsRunID field to `json:"correctsRunID,omitempty"`
to keep wire format consistent.
🧹 Nitpick comments (6)
openmeter/billing/charges/usagebased/detailedline_uniqueref.go (1)

16-65: ⚡ Quick win

Worth adding unit tests for this new string-parsing utility

The sentinel-based parsing (@[) and the strip/reformat round-trip are subtle enough that a few table-driven unit tests would go a long way — especially for edge cases like:

  • id with no suffix (idempotent strip)
  • id that already has a suffix (round-trip via WithServicePeriodFromUniqueReferenceID)
  • id = "@[...]" (error case — empty base)

Also worth a quick comment or invariant check: the format assumes base IDs never contain the literal "@[" substring; it'd be nice to document this precondition so future callers don't accidentally break the sentinel.

As per coding guidelines, **/*_test.go: "Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/detailedline_uniqueref.go` around lines
16 - 65, Add table-driven unit tests for
stripServicePeriodFromUniqueReferenceID,
StripServicePeriodFromUniqueReferenceID, WithServicePeriodFromUniqueReferenceID
and the round-trip with formatServicePeriodInUniqueReferenceID covering: (1) id
with no suffix (should be idempotent), (2) id that already has a suffix (strip
then reformat yields original base+formatted suffix), (3) id == "@[...]" (expect
error for empty base), and edge cases with UTC formatting; also add a short doc
comment/invariant on stripServicePeriodFromUniqueReferenceID (and/or at the top
of the file) that the implementation assumes base IDs never contain the literal
"@[" so callers must not pass IDs containing that substring.
openmeter/billing/models/totals/model_test.go (1)

51-70: 💤 Low value

Consider covering more fields in TestTotalsEqual

Right now only Total is flipped to test inequality. If Equal ever has a per-field bug (e.g., accidentally skipping CreditsTotal), this test won't catch it. Adding a sub-test or table-driven case per field would give a tighter safety net.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/models/totals/model_test.go` around lines 51 - 70,
TestTotalsEqual currently only flips Totals.Total which won't catch per-field
mismatches; update TestTotalsEqual to be table-driven or add subtests that
iterate over each Totals field (Amount, ChargesTotal, DiscountsTotal,
TaxesInclusiveTotal, TaxesExclusiveTotal, TaxesTotal, CreditsTotal, Total) and
for each case create a copy of the base Totals, change only that field, then
assert that in.Equal(modified) is false and that in.Equal(in) remains true; use
the Totals type and its Equal method and name subtests with the field name to
make failures clear.
openmeter/billing/charges/usagebased/adapter/detailedline_test.go (1)

499-525: 💤 Low value

Builder is tidy; one tiny readability nit.

The lo.CoalesceOrEmpty(input.PricerReferenceID, input.ChildUniqueReferenceID) fallback nicely mirrors the production code's behavior, which keeps the test honest. Minor optional thought: the Totals math recomputes 0.1 * Quantity three times — extracting a local would shave a couple of lines and make intent clearer, but it's purely cosmetic.

♻️ Optional cosmetic tweak
+		amount := alpacadecimal.NewFromFloat(0.1).Mul(alpacadecimal.NewFromInt(input.Quantity))
 		Base: stddetailedline.Base{
 			...
 			Totals: totals.Totals{
-				Amount:       alpacadecimal.NewFromFloat(0.1).Mul(alpacadecimal.NewFromInt(input.Quantity)),
-				ChargesTotal: alpacadecimal.NewFromFloat(0.1).Mul(alpacadecimal.NewFromInt(input.Quantity)),
-				Total:        alpacadecimal.NewFromFloat(0.1).Mul(alpacadecimal.NewFromInt(input.Quantity)),
+				Amount:       amount,
+				ChargesTotal: amount,
+				Total:        amount,
 			},
 		},
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/adapter/detailedline_test.go` around
lines 499 - 525, The test builder newDetailedLine recomputes the per-unit *
quantity expression three times; improve readability by calculating the line
total once into a local variable (e.g., compute total :=
alpacadecimal.NewFromFloat(0.1).Mul(alpacadecimal.NewFromInt(input.Quantity))
after setting PerUnitAmount and Quantity) and reuse that local for
Totals.Amount, Totals.ChargesTotal and Totals.Total to make intent clearer;
update the newDetailedLine function accordingly.
openmeter/billing/service/invoicecalc/details.go (1)

45-50: 💤 Low value

Clean interface-check pattern, small observability note

The continue when an engine doesn't implement LineCalculator is explained well by the comment — no functional issue. That said, if a new engine type is accidentally wired without implementing LineCalculator, recalculation silently gets skipped. A debug-level log here would make that kind of issue much easier to catch:

 		lineCalculator, ok := lineEngine.(billing.LineCalculator)
 		if !ok {
+			// Optional: log.Debug("skipping recalculation for engine without LineCalculator", "engine", lineEngineType)
 			continue
 		}

Totally optional, just a suggestion for future debuggability.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/service/invoicecalc/details.go` around lines 45 - 50, The
loop currently type-asserts lineEngine to billing.LineCalculator using
"lineCalculator, ok := lineEngine.(billing.LineCalculator)" and silently
continues on ok==false; add a debug-level log in the branch where ok is false to
surface when an engine was skipped (include the engine's concrete type or
identifier and context such as invoice ID or engine name if available) before
the "continue" so accidental non-implementing engines are observable during
debugging.
openmeter/billing/charges/usagebased/service/run/create.go (1)

29-31: 💤 Low value

Tiny doc-comment phrasing tweak.

The doc comment doubles up "there's no" and "is expected", which makes it read a little bumpy. A small rewording would make this public field's contract a touch clearer for future readers:

📝 Suggested phrasing
-	// NoFiatTransactionRequired is set if either there's no fiat-based
-	// settlement is expected (credits_only) or if the run totals are zero.
+	// NoFiatTransactionRequired is set when either no fiat-based settlement
+	// is expected (credits_only) or the run totals are zero.
 	NoFiatTransactionRequired bool
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/service/run/create.go` around lines 29 -
31, Update the doc comment for the exported field NoFiatTransactionRequired to
remove the doubled phrasing and make it clearer; e.g., reword to:
"NoFiatTransactionRequired is true when no fiat-based settlement is expected
(for example, credits_only) or when the run totals are zero." Ensure the comment
sits immediately above the NoFiatTransactionRequired field declaration.
openmeter/billing/charges/usagebased/service/rating/service.go (1)

48-54: 💤 Low value

Scaffolding default looks good.

Returning RatingEngineDelta unconditionally is consistent with the PR's "keep production on the existing rating path" intent. Once more engine policies land, this is the obvious place to plug them in.

Tiny optional nit: the method body sits between the Service interface and the service struct declaration — moving it below the struct (next to New) would keep the type-then-methods flow most of this package follows. Totally up to you.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/service/rating/service.go` around lines
48 - 54, The GetPreferredRatingEngineFor method implementation for the Service
interface is placed between the Service interface and the service struct,
breaking the package's type-then-methods ordering; move the method body for
GetPreferredRatingEngineFor(_ usagebased.Intent) usagebased.RatingEngine so it
sits after the service struct declaration (near New) to keep the Service
interface, service struct, then methods flow intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@openmeter/billing/charges/usagebased/service/rating/totals.go`:
- Around line 60-65: Add a short doc comment on GetTotalsForUsage stating that
it intentionally disables credit mutation (via
billingrating.WithCreditsMutatorDisabled) and therefore returns pre-credit
totals for performance reasons, and mention that GetDetailedRatingForUsage
applies credits so results will differ; update the comment immediately above the
GetTotalsForUsage function to make this distinction explicit for future callers
and maintainers.

---

Duplicate comments:
In `@openmeter/billing/charges/usagebased/detailedline.go`:
- Around line 22-23: The JSON tag for the struct field CorrectsRunID is
inconsistent with the project's ID casing convention: change the tag on
CorrectsRunID from `correctsRunId` to `correctsRunID` so it matches other fields
like PricerReferenceID and ChildUniqueReferenceID; update the struct field's tag
in detailedline.go for the CorrectsRunID field to
`json:"correctsRunID,omitempty"` to keep wire format consistent.

---

Nitpick comments:
In `@openmeter/billing/charges/usagebased/adapter/detailedline_test.go`:
- Around line 499-525: The test builder newDetailedLine recomputes the per-unit
* quantity expression three times; improve readability by calculating the line
total once into a local variable (e.g., compute total :=
alpacadecimal.NewFromFloat(0.1).Mul(alpacadecimal.NewFromInt(input.Quantity))
after setting PerUnitAmount and Quantity) and reuse that local for
Totals.Amount, Totals.ChargesTotal and Totals.Total to make intent clearer;
update the newDetailedLine function accordingly.

In `@openmeter/billing/charges/usagebased/detailedline_uniqueref.go`:
- Around line 16-65: Add table-driven unit tests for
stripServicePeriodFromUniqueReferenceID,
StripServicePeriodFromUniqueReferenceID, WithServicePeriodFromUniqueReferenceID
and the round-trip with formatServicePeriodInUniqueReferenceID covering: (1) id
with no suffix (should be idempotent), (2) id that already has a suffix (strip
then reformat yields original base+formatted suffix), (3) id == "@[...]" (expect
error for empty base), and edge cases with UTC formatting; also add a short doc
comment/invariant on stripServicePeriodFromUniqueReferenceID (and/or at the top
of the file) that the implementation assumes base IDs never contain the literal
"@[" so callers must not pass IDs containing that substring.

In `@openmeter/billing/charges/usagebased/service/rating/service.go`:
- Around line 48-54: The GetPreferredRatingEngineFor method implementation for
the Service interface is placed between the Service interface and the service
struct, breaking the package's type-then-methods ordering; move the method body
for GetPreferredRatingEngineFor(_ usagebased.Intent) usagebased.RatingEngine so
it sits after the service struct declaration (near New) to keep the Service
interface, service struct, then methods flow intact.

In `@openmeter/billing/charges/usagebased/service/run/create.go`:
- Around line 29-31: Update the doc comment for the exported field
NoFiatTransactionRequired to remove the doubled phrasing and make it clearer;
e.g., reword to: "NoFiatTransactionRequired is true when no fiat-based
settlement is expected (for example, credits_only) or when the run totals are
zero." Ensure the comment sits immediately above the NoFiatTransactionRequired
field declaration.

In `@openmeter/billing/models/totals/model_test.go`:
- Around line 51-70: TestTotalsEqual currently only flips Totals.Total which
won't catch per-field mismatches; update TestTotalsEqual to be table-driven or
add subtests that iterate over each Totals field (Amount, ChargesTotal,
DiscountsTotal, TaxesInclusiveTotal, TaxesExclusiveTotal, TaxesTotal,
CreditsTotal, Total) and for each case create a copy of the base Totals, change
only that field, then assert that in.Equal(modified) is false and that
in.Equal(in) remains true; use the Totals type and its Equal method and name
subtests with the field name to make failures clear.

In `@openmeter/billing/service/invoicecalc/details.go`:
- Around line 45-50: The loop currently type-asserts lineEngine to
billing.LineCalculator using "lineCalculator, ok :=
lineEngine.(billing.LineCalculator)" and silently continues on ok==false; add a
debug-level log in the branch where ok is false to surface when an engine was
skipped (include the engine's concrete type or identifier and context such as
invoice ID or engine name if available) before the "continue" so accidental
non-implementing engines are observable during debugging.
🪄 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: a396b7fb-ee63-4309-bc81-36d0c42cbd5c

📥 Commits

Reviewing files that changed from the base of the PR and between d43c0a7 and a3df829.

⛔ Files ignored due to path filters (27)
  • openmeter/ent/db/chargeflatfeedetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline/chargeflatfeedetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased/chargeusagebased.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebased_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline/chargeusagebasedrundetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns/chargeusagebasedruns.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/client.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
📒 Files selected for processing (56)
  • .agents/skills/billing/SKILL.md
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/README.md
  • openmeter/billing/charges/creditpurchase/lineengine/engine.go
  • openmeter/billing/charges/flatfee/adapter/detailedline.go
  • openmeter/billing/charges/flatfee/adapter/detailedline_test.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/detailedline.go
  • openmeter/billing/charges/usagebased/adapter/detailedline_test.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/detailedline.go
  • openmeter/billing/charges/usagebased/detailedline_uniqueref.go
  • openmeter/billing/charges/usagebased/rating.go
  • openmeter/billing/charges/usagebased/ratingengine.go
  • openmeter/billing/charges/usagebased/realizationrun.go
  • openmeter/billing/charges/usagebased/realizationrun_test.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/service/create.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/usagebased/service/linemapper.go
  • openmeter/billing/charges/usagebased/service/linemapper_test.go
  • openmeter/billing/charges/usagebased/service/payments.go
  • openmeter/billing/charges/usagebased/service/rating/detailedline.go
  • openmeter/billing/charges/usagebased/service/rating/service.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/charges/usagebased/service/rating/totals.go
  • openmeter/billing/charges/usagebased/service/run/create.go
  • openmeter/billing/charges/usagebased/service/run/invoice.go
  • openmeter/billing/charges/usagebased/service/run/payment.go
  • openmeter/billing/charges/usagebased/service/run/payment_test.go
  • openmeter/billing/charges/usagebased/service_test.go
  • openmeter/billing/invoicedetailedline.go
  • openmeter/billing/lineengine.go
  • openmeter/billing/lineengine/engine.go
  • openmeter/billing/models/stddetailedline/model.go
  • openmeter/billing/models/totals/model.go
  • openmeter/billing/models/totals/model_test.go
  • openmeter/billing/rating/service.go
  • openmeter/billing/rating/service/billableperiod.go
  • openmeter/billing/rating/service/mutator/credits.go
  • openmeter/billing/rating/service/mutator/credits_test.go
  • openmeter/billing/rating/service/mutator/discountusage.go
  • openmeter/billing/rating/service/mutator/discountusage_test.go
  • openmeter/billing/rating/service/options_test.go
  • openmeter/billing/rating/service/pricer.go
  • openmeter/billing/rating/service/testutil/ubptest.go
  • openmeter/billing/service/invoicecalc/details.go
  • openmeter/billing/service/invoicecalc/details_test.go
  • openmeter/billing/testutils/lineengine.go
  • openmeter/ent/schema/chargesflatfee.go
  • openmeter/ent/schema/chargesusagebased.go
✅ Files skipped from review due to trivial changes (2)
  • .agents/skills/billing/SKILL.md
  • openmeter/billing/README.md
🚧 Files skipped from review as they are similar to previous changes (4)
  • openmeter/billing/models/totals/model.go
  • openmeter/billing/charges/usagebased/adapter/realizationrun.go
  • openmeter/billing/rating/service/mutator/discountusage_test.go
  • openmeter/billing/charges/usagebased/service/run/payment_test.go

@turip turip added release-note/feature Release note: Exciting New Features area/billing labels May 6, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
openmeter/ledger/chargeadapter/usagebased_test.go (1)

489-530: 🏗️ Heavy lift

Consider adding tests for the NoFiatTransactionRequired path

The PR explicitly introduces skipping fiat ledger booking and payment authorization/settlement when a run is marked NoFiatTransactionRequired (both for credit_only and credit_then_invoice). None of the existing test cases in this file exercise that code path, so a bug there wouldn't be caught here.

It'd be great to see at least a couple of cases like:

  • credit_only run with zero fiat — verify that OnPaymentAuthorized / OnPaymentSettled return empty refs without writing any ledger transactions.
  • credit_then_invoice run where totals zero out — same expectation.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/ledger/chargeadapter/usagebased_test.go` around lines 489 - 530,
Add tests exercising the NoFiatTransactionRequired path by extending
usageBasedHandlerTestEnv.newCharge / test setup to create runs with
Intent.SettlementMode values (credit_only and credit_then_invoice) and mark the
run metadata NoFiatTransactionRequired; then call the handler methods
OnPaymentAuthorized and OnPaymentSettled (or the public entry points used in
existing tests) with a charge from newCharge and assert they return empty refs
and that no ledger writes occurred (inspect ledger adapter/mocks used in these
tests). Target the same test file (usagebased_test.go) and mirror existing test
structure for other settlement scenarios so coverage includes both credit_only
zero-fiat and credit_then_invoice totals-zero cases using the same assertions
against ledger/mocks and authorization/settlement results.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.agents/skills/charges/SKILL.md:
- Around line 34-39: The SKILL.md references three README files that don't
exist; create placeholder README.md files at
openmeter/billing/charges/usagebased/service/rating/delta/README.md,
openmeter/billing/charges/usagebased/service/rating/periodpreserving/README.md,
and openmeter/billing/charges/usagebased/service/rating/subtract/README.md (or
alternatively update the SKILL.md references to point to existing docs). Each
README should at minimum state the calculation contract name, a short
description of the algorithm, expected input/output shapes, and a "TODO" note
linking to the detailed spec so agents won't hit dead ends when following
SKILL.md.

---

Nitpick comments:
In `@openmeter/ledger/chargeadapter/usagebased_test.go`:
- Around line 489-530: Add tests exercising the NoFiatTransactionRequired path
by extending usageBasedHandlerTestEnv.newCharge / test setup to create runs with
Intent.SettlementMode values (credit_only and credit_then_invoice) and mark the
run metadata NoFiatTransactionRequired; then call the handler methods
OnPaymentAuthorized and OnPaymentSettled (or the public entry points used in
existing tests) with a charge from newCharge and assert they return empty refs
and that no ledger writes occurred (inspect ledger adapter/mocks used in these
tests). Target the same test file (usagebased_test.go) and mirror existing test
structure for other settlement scenarios so coverage includes both credit_only
zero-fiat and credit_then_invoice totals-zero cases using the same assertions
against ledger/mocks and authorization/settlement results.
🪄 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: ec62e06e-e0b0-4c2d-8242-61b98c0fc68d

📥 Commits

Reviewing files that changed from the base of the PR and between a3df829 and 1aae8cf.

📒 Files selected for processing (7)
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/README.md
  • openmeter/billing/charges/usagebased/detailedline.go
  • openmeter/billing/charges/usagebased/service/rating/totals.go
  • openmeter/billing/derived.gen.go
  • openmeter/billing/models/stddetailedline/derived.gen.go
  • openmeter/ledger/chargeadapter/usagebased_test.go

Comment thread .agents/skills/charges/SKILL.md Resolved
@turip
turip force-pushed the split/rating-scaffolding branch from 4dbbe0e to fa80b79 Compare May 6, 2026 14:41
@turip
turip enabled auto-merge (squash) May 6, 2026 14:43
@turip
turip merged commit cbd4e2a into main May 6, 2026
26 of 27 checks passed
@turip
turip deleted the split/rating-scaffolding branch May 6, 2026 14:47

This branch was previously deployed

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

Labels

area/billing release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants