Repository navigation
feat(billing): scaffold usage based charge lifecycle mapping - #4297
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (28)
📒 Files selected for processing (62)
📝 WalkthroughWalkthroughAdds 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. ChangesUsage-Based Billing Enhancements
Line Engine Interface Refactor
Rating Options, Mutators & Validation
Supporting Models & Utilities
Sequence DiagramsequenceDiagram
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)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
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 winThe 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.Basein charge packages. Since this PR turnsusagebased.DetailedLineinto 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 winPlease 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 valueHeads up:
Subcan produce values thatValidate()would reject.
Validate()rejects negative fields, butSubwill happily produce them (e.g. subtracting a largerTotal). That's almost certainly the intended semantics —Negexists for the same reason — but it does mean callers who pipe aSubresult back throughValidate()will get errors. Worth a one-line doc comment onSub/Negclarifying that the result may carry negative components and isn't guaranteed to satisfyValidate().🤖 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 valueHeads-up: this is effectively a constant for now.
GetPreferredRatingEngineForignoresintentand always returnsRatingEngineDelta. 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// TODOmentioning 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 winSolid starter test — consider expanding per-field coverage.
The current test only mutates
Total, so a regression where (say)CreditsTotalis missing fromEqual'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 winSuffix marker
@[is doing a lot of work — worth a constant.Both
stripServicePeriodFromUniqueReferenceIDandformatServicePeriodInUniqueReferenceIDhard-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 → stripreturns 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 valueSmall naming nit on
WithServicePeriodFromUniqueReferenceID.The name reads like it pulls the service period from the ID, but it actually re-encodes the line's
ServicePeriodinto the ID (stripping any prior suffix first). Something likeWithServicePeriodInUniqueReferenceIDorEncodeServicePeriodIntoUniqueReferenceIDwould 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 valueRFC3339 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 viaNormalizeTimestamp()andNormalizeClosedPeriod()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 winPlease add a create-path test assertion for
RatingEngineforwarding.This is a key behavior seam now; a small test that verifies
Createpasses the selected engine intoCreateChargesInput.Intentswould 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 winMirror the write-side fallback when hydrating
PricerReferenceID.
buildDetailedLineCreatestoreslo.CoalesceOrEmpty(line.PricerReferenceID, line.ChildUniqueReferenceID), but the read path takesdbLine.PricerReferenceIDas-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 winPlease add a focused test for the no-fiat branch.
This now has two new invariants plus a persistence path that writes
AccruedUsagewithout a ledger transaction. A small unit test coveringNoFiatTransactionRequired=trueand 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 valueTiny readability nit on the
removeRateCardUsageDiscountscalls.You end up calling
removeRateCardUsageDiscounts(out.StandardLineDiscounts)in all three branches. Sinceout.StandardLineDiscountsalways starts asin.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 valueSame nit for
no_fiat_transaction_required.No
Default(false)here either — the up migration adds the column withDEFAULT falseand then drops the default, so going forward everyChargeUsageBasedRuns.CreatemustSetNoFiatTransactionRequired(...)explicitly. The relevant context snippet confirmsCreateRealizationRunInputnow propagates this, so we're likely fine, but aDefault(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 valueSchema-level default check:
rating_enginedoesn't have one, but that's already handled.Good news—the
buildCreateUsageBasedChargefunction in the adapter does setSetRatingEngine(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 addingDefault(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 valueLock-duration heads up on
SET NOT NULL.Each of the
ALTER TABLE ... ALTER COLUMN ... SET NOT NULLstatements (lines 6, 10, 14) takes anAccessExclusiveLockand scans the full table to validate. That's totally fine for small/medium tables, butcharge_usage_based_run_detailed_lineandcharge_flat_fee_detailed_linecan grow large — worth a quick check on production sizes before rolling out, and considering theADD CONSTRAINT ... CHECK (col IS NOT NULL) NOT VALID→VALIDATE CONSTRAINT→SET NOT NULLdance 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
⛔ Files ignored due to path filters (28)
openmeter/ent/db/chargeflatfeedetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeedetailedline/chargeflatfeedetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeedetailedline/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeedetailedline_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeedetailedline_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased/chargeusagebased.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline/chargeusagebasedrundetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns/chargeusagebasedruns.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns_update.gois excluded by!**/ent/db/**openmeter/ent/db/client.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**openmeter/ent/db/mutation.gois excluded by!**/ent/db/**openmeter/ent/db/runtime.gois excluded by!**/ent/db/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (58)
.agents/skills/billing/SKILL.md.agents/skills/charges/SKILL.mdopenmeter/billing/README.mdopenmeter/billing/charges/creditpurchase/lineengine/engine.goopenmeter/billing/charges/flatfee/adapter/detailedline.goopenmeter/billing/charges/flatfee/adapter/detailedline_test.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/usagebased/adapter/charge.goopenmeter/billing/charges/usagebased/adapter/detailedline.goopenmeter/billing/charges/usagebased/adapter/detailedline_test.goopenmeter/billing/charges/usagebased/adapter/mapper.goopenmeter/billing/charges/usagebased/adapter/realizationrun.goopenmeter/billing/charges/usagebased/charge.goopenmeter/billing/charges/usagebased/detailedline.goopenmeter/billing/charges/usagebased/detailedline_uniqueref.goopenmeter/billing/charges/usagebased/rating.goopenmeter/billing/charges/usagebased/ratingengine.goopenmeter/billing/charges/usagebased/realizationrun.goopenmeter/billing/charges/usagebased/realizationrun_test.goopenmeter/billing/charges/usagebased/service.goopenmeter/billing/charges/usagebased/service/create.goopenmeter/billing/charges/usagebased/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/creditsonly.goopenmeter/billing/charges/usagebased/service/lineengine.goopenmeter/billing/charges/usagebased/service/linemapper.goopenmeter/billing/charges/usagebased/service/linemapper_test.goopenmeter/billing/charges/usagebased/service/payments.goopenmeter/billing/charges/usagebased/service/rating/detailedline.goopenmeter/billing/charges/usagebased/service/rating/service.goopenmeter/billing/charges/usagebased/service/rating/service_test.goopenmeter/billing/charges/usagebased/service/rating/totals.goopenmeter/billing/charges/usagebased/service/run/create.goopenmeter/billing/charges/usagebased/service/run/invoice.goopenmeter/billing/charges/usagebased/service/run/payment.goopenmeter/billing/charges/usagebased/service/run/payment_test.goopenmeter/billing/charges/usagebased/service_test.goopenmeter/billing/invoicedetailedline.goopenmeter/billing/lineengine.goopenmeter/billing/lineengine/engine.goopenmeter/billing/models/stddetailedline/model.goopenmeter/billing/models/totals/model.goopenmeter/billing/models/totals/model_test.goopenmeter/billing/rating/service.goopenmeter/billing/rating/service/billableperiod.goopenmeter/billing/rating/service/mutator/credits.goopenmeter/billing/rating/service/mutator/credits_test.goopenmeter/billing/rating/service/mutator/discountusage.goopenmeter/billing/rating/service/mutator/discountusage_test.goopenmeter/billing/rating/service/options_test.goopenmeter/billing/rating/service/pricer.goopenmeter/billing/rating/service/testutil/ubptest.goopenmeter/billing/service/invoicecalc/details.goopenmeter/billing/service/invoicecalc/details_test.goopenmeter/billing/testutils/lineengine.goopenmeter/ent/schema/chargesflatfee.goopenmeter/ent/schema/chargesusagebased.gotools/migrate/migrations/20260430092817_add_usage_based_detailed_line_corrects_run_id.down.sqltools/migrate/migrations/20260430092817_add_usage_based_detailed_line_corrects_run_id.up.sql
d43c0a7 to
a3df829
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
openmeter/billing/charges/usagebased/detailedline.go (1)
22-23:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winJSON 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.), makingcorrectsRunIdthe 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 winWorth 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:
idwith no suffix (idempotent strip)idthat already has a suffix (round-trip viaWithServicePeriodFromUniqueReferenceID)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 valueConsider covering more fields in
TestTotalsEqualRight now only
Totalis flipped to test inequality. IfEqualever has a per-field bug (e.g., accidentally skippingCreditsTotal), 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 valueBuilder 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: theTotalsmath recomputes0.1 * Quantitythree 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 valueClean interface-check pattern, small observability note
The
continuewhen an engine doesn't implementLineCalculatoris explained well by the comment — no functional issue. That said, if a new engine type is accidentally wired without implementingLineCalculator, recalculation silently gets skipped. Adebug-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 valueTiny 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 valueScaffolding default looks good.
Returning
RatingEngineDeltaunconditionally 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
Serviceinterface and theservicestruct declaration — moving it below the struct (next toNew) 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
⛔ Files ignored due to path filters (27)
openmeter/ent/db/chargeflatfeedetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeedetailedline/chargeflatfeedetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeedetailedline/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeedetailedline_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfeedetailedline_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased/chargeusagebased.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline/chargeusagebasedrundetailedline.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedrundetailedline_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns/chargeusagebasedruns.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns_update.gois excluded by!**/ent/db/**openmeter/ent/db/client.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**openmeter/ent/db/mutation.gois excluded by!**/ent/db/**openmeter/ent/db/runtime.gois excluded by!**/ent/db/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**
📒 Files selected for processing (56)
.agents/skills/billing/SKILL.md.agents/skills/charges/SKILL.mdopenmeter/billing/README.mdopenmeter/billing/charges/creditpurchase/lineengine/engine.goopenmeter/billing/charges/flatfee/adapter/detailedline.goopenmeter/billing/charges/flatfee/adapter/detailedline_test.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/usagebased/adapter/charge.goopenmeter/billing/charges/usagebased/adapter/detailedline.goopenmeter/billing/charges/usagebased/adapter/detailedline_test.goopenmeter/billing/charges/usagebased/adapter/mapper.goopenmeter/billing/charges/usagebased/adapter/realizationrun.goopenmeter/billing/charges/usagebased/charge.goopenmeter/billing/charges/usagebased/detailedline.goopenmeter/billing/charges/usagebased/detailedline_uniqueref.goopenmeter/billing/charges/usagebased/rating.goopenmeter/billing/charges/usagebased/ratingengine.goopenmeter/billing/charges/usagebased/realizationrun.goopenmeter/billing/charges/usagebased/realizationrun_test.goopenmeter/billing/charges/usagebased/service.goopenmeter/billing/charges/usagebased/service/create.goopenmeter/billing/charges/usagebased/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/creditsonly.goopenmeter/billing/charges/usagebased/service/lineengine.goopenmeter/billing/charges/usagebased/service/linemapper.goopenmeter/billing/charges/usagebased/service/linemapper_test.goopenmeter/billing/charges/usagebased/service/payments.goopenmeter/billing/charges/usagebased/service/rating/detailedline.goopenmeter/billing/charges/usagebased/service/rating/service.goopenmeter/billing/charges/usagebased/service/rating/service_test.goopenmeter/billing/charges/usagebased/service/rating/totals.goopenmeter/billing/charges/usagebased/service/run/create.goopenmeter/billing/charges/usagebased/service/run/invoice.goopenmeter/billing/charges/usagebased/service/run/payment.goopenmeter/billing/charges/usagebased/service/run/payment_test.goopenmeter/billing/charges/usagebased/service_test.goopenmeter/billing/invoicedetailedline.goopenmeter/billing/lineengine.goopenmeter/billing/lineengine/engine.goopenmeter/billing/models/stddetailedline/model.goopenmeter/billing/models/totals/model.goopenmeter/billing/models/totals/model_test.goopenmeter/billing/rating/service.goopenmeter/billing/rating/service/billableperiod.goopenmeter/billing/rating/service/mutator/credits.goopenmeter/billing/rating/service/mutator/credits_test.goopenmeter/billing/rating/service/mutator/discountusage.goopenmeter/billing/rating/service/mutator/discountusage_test.goopenmeter/billing/rating/service/options_test.goopenmeter/billing/rating/service/pricer.goopenmeter/billing/rating/service/testutil/ubptest.goopenmeter/billing/service/invoicecalc/details.goopenmeter/billing/service/invoicecalc/details_test.goopenmeter/billing/testutils/lineengine.goopenmeter/ent/schema/chargesflatfee.goopenmeter/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
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
openmeter/ledger/chargeadapter/usagebased_test.go (1)
489-530: 🏗️ Heavy liftConsider adding tests for the
NoFiatTransactionRequiredpathThe PR explicitly introduces skipping fiat ledger booking and payment authorization/settlement when a run is marked
NoFiatTransactionRequired(both forcredit_onlyandcredit_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_onlyrun with zero fiat — verify thatOnPaymentAuthorized/OnPaymentSettledreturn empty refs without writing any ledger transactions.credit_then_invoicerun 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
📒 Files selected for processing (7)
.agents/skills/charges/SKILL.mdopenmeter/billing/README.mdopenmeter/billing/charges/usagebased/detailedline.goopenmeter/billing/charges/usagebased/service/rating/totals.goopenmeter/billing/derived.gen.goopenmeter/billing/models/stddetailedline/derived.gen.goopenmeter/ledger/chargeadapter/usagebased_test.go
4dbbe0e to
fa80b79
Compare
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:
corrects_run_id) (will be needed for pro-rating)no_fiat_transaction_required(so that we don't start payment/invoice accrued ledger flow when not needed)deltaUsage-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).
Charge line engines no longer have to implement billing recalculation.
billing.LineCalculatoris split out frombilling.LineEngine.LineCalculator, expecting lifecycle hooks to return fully calculated lines.Zero-fiat usage-based runs are handled explicitly.
credit_onlyruns always markNoFiatTransactionRequired.credit_then_invoiceruns derive it from zero totals.Billing rating now supports disabling the credits mutator for charge-owned rating passes.
Migration
Adds a new coalesced migration for:
charge_usage_based.rating_enginecharge_usage_based_runs.no_fiat_transaction_requiredcharge_flat_fee_detailed_line.pricer_reference_idcharge_usage_based_run_detailed_line.pricer_reference_idcharge_usage_based_run_detailed_line.corrects_run_idThe migration backfills:
rating_engine = 'delta'pricer_reference_idfromchild_unique_reference_idcredit_onlyusage-based runs tono_fiat_transaction_required = trueSummary by CodeRabbit
New Features
Documentation
Bug Fixes